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
This commit is contained in:
Darren Hinde 2025-12-18 09:52:11 +00:00 committed by GitHub
parent 969b44452e
commit c8f7103cb6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
392 changed files with 26426 additions and 6868 deletions

View file

@ -1,160 +0,0 @@
# Archived Workflows
These workflows were removed as part of the fork-friendly workflow simplification on 2025-12-08.
## Why We Archived These Workflows
### Problem Statement
The original workflows had several issues:
1. **Expensive AI tests on every PR** - Running full agent evaluations cost money and took 15+ minutes
2. **Fork PR failures** - External contributors experienced confusing workflow failures
3. **Over-engineering** - Too much automation for simple validation tasks
4. **Poor contributor experience** - Slow feedback and unclear error messages
### Solution
We simplified the workflow architecture to be:
- **Fast** - Build checks complete in < 2 minutes
- **Fork-friendly** - No push attempts to fork branches
- **Cost-effective** - No AI tests on every PR
- **Clear** - Better error messages and contributor guidance
---
## Archived Workflows
### `test-agents.yml` (Archived: 2025-12-08)
**What it did:**
- Ran full AI agent tests (OpenAgent and OpenCoder) on every PR
- Spawned OpenCode CLI and executed evaluation framework
- Auto-bumped versions after merge
- Created GitHub releases
**Why removed:**
- ❌ Expensive (AI API calls on every PR)
- ❌ Slow (15 minutes per PR)
- ❌ Overkill for PR validation
- ❌ Failed on fork PRs due to permission issues
**Replaced by:**
- ✅ `pr-checks.yml` - Fast build validation for PRs (< 2 min, free)
- ✅ `post-merge.yml` - Auto-versioning after merge (keeps the good automation!)
- ✅ Manual testing: `npm run test:ci` when needed
**Key features preserved:**
- ✅ Auto-version bumping (moved to post-merge.yml)
- ✅ Automatic GitHub releases (moved to post-merge.yml)
- ✅ Conventional commit parsing (moved to post-merge.yml)
---
### `validate-test-suites.yml` (Archived: 2025-12-08)
**What it did:**
- Validated YAML test suite files
- Ran on every test file change
- Posted PR comments on validation failures
**Why removed:**
- ❌ Redundant with build check
- ❌ Could be combined with other validation
**Replaced by:**
- ✅ `pr-checks.yml` - Includes YAML validation as part of build check
---
## New Workflow Architecture
```
.github/workflows/
├── pr-checks.yml # Fast build validation (all PRs)
├── validate-registry.yml # Registry validation (fork-friendly)
├── post-merge.yml # Auto-version + releases (main only)
├── opencode.yml # OpenCode integration
├── sync-docs.yml # Doc sync
├── update-registry.yml # Registry updates
└── _archive/
├── README.md # This file
├── test-agents.yml # Old expensive AI tests
└── validate-test-suites.yml # Old YAML validation
```
---
## Testing Philosophy
### Before (Expensive)
- ❌ AI tests on every PR (15 min, costs money)
- ❌ Fork PRs failed with confusing errors
- ❌ Slow feedback loop
- ❌ Over-engineered for simple validation
### After (Efficient)
- ✅ Fast build checks on PRs (< 2 min, free)
- ✅ Fork-friendly workflows
- ✅ Manual AI testing when needed
- ✅ Auto-versioning after merge (preserved!)
- ✅ Clear contributor guidance
---
## For Maintainers
### Running AI Tests Manually
If you need to run the full agent tests:
```bash
# Locally
npm run test:ci
# Or specific agents
npm run test:openagent
npm run test:opencoder
# With specific models
npm run test:openagent:claude
npm run test:openagent:grok
```
### Restoring Old Workflows (Not Recommended)
If you need to restore these workflows for reference:
```bash
# Copy back to workflows directory
cp .github/workflows/_archive/test-agents.yml .github/workflows/
# But consider: Do you really need expensive AI tests on every PR?
```
---
## Migration Notes
**What changed for contributors:**
- ✅ Faster PR feedback (2 min vs 15 min)
- ✅ No confusing fork PR failures
- ✅ Clear instructions when fixes needed
**What changed for maintainers:**
- ✅ Lower CI costs (no AI tests per PR)
- ✅ Same auto-versioning (moved to post-merge.yml)
- ✅ Same auto-releases (moved to post-merge.yml)
- ✅ Manual control over AI testing
**What stayed the same:**
- ✅ Auto-version bumping based on conventional commits
- ✅ Automatic CHANGELOG updates
- ✅ Automatic GitHub releases
- ✅ Registry validation and auto-updates
- ✅ Documentation sync
---
## Questions?
See the main workflow documentation:
- [EXTERNAL_PR_GUIDE.md](../../EXTERNAL_PR_GUIDE.md) - For contributors
- [VERSION_BUMP_GUIDE.md](../VERSION_BUMP_GUIDE.md) - For version management

View file

@ -1,344 +0,0 @@
name: Test Agents
on:
pull_request:
branches: [ main, dev ]
paths:
- '.opencode/**'
- 'evals/**'
- '.github/workflows/test-agents.yml'
push:
branches: [ main ]
workflow_dispatch:
inputs:
skip_tests:
description: 'Skip tests (maintainer override)'
required: false
type: boolean
default: false
jobs:
# Check if this is a PR merge commit (skip tests if so - they already ran on PR)
check-trigger:
name: Check Trigger Type
runs-on: ubuntu-latest
outputs:
should_test: ${{ steps.check.outputs.should_test }}
should_bump: ${{ steps.check.outputs.should_bump }}
steps:
- name: Determine if tests should run
id: check
run: |
# For PRs, always run tests
if [ "${{ github.event_name }}" == "pull_request" ]; then
echo "should_test=true" >> $GITHUB_OUTPUT
echo "should_bump=false" >> $GITHUB_OUTPUT
echo "PR detected - will run tests"
exit 0
fi
# For workflow_dispatch, check skip_tests input
if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
if [ "${{ github.event.inputs.skip_tests }}" == "true" ]; then
echo "should_test=false" >> $GITHUB_OUTPUT
echo "should_bump=false" >> $GITHUB_OUTPUT
echo "Manual trigger - tests skipped by maintainer"
else
echo "should_test=true" >> $GITHUB_OUTPUT
echo "should_bump=false" >> $GITHUB_OUTPUT
echo "Manual trigger - will run tests"
fi
exit 0
fi
# For push events, check if it's a PR merge
COMMIT_MSG="${{ github.event.head_commit.message }}"
# PR merges have messages like "Merge pull request #123" or contain (#123)
if echo "$COMMIT_MSG" | grep -qE "^Merge pull request #|^.*\(#[0-9]+\)$"; then
echo "should_test=false" >> $GITHUB_OUTPUT
echo "should_bump=true" >> $GITHUB_OUTPUT
echo "PR merge detected - skipping tests, will bump version"
# Skip version bump commits
elif echo "$COMMIT_MSG" | grep -qE "^\[skip ci\]|chore: bump version"; then
echo "should_test=false" >> $GITHUB_OUTPUT
echo "should_bump=false" >> $GITHUB_OUTPUT
echo "Version bump commit - skipping everything"
else
echo "should_test=true" >> $GITHUB_OUTPUT
echo "should_bump=true" >> $GITHUB_OUTPUT
echo "Direct push detected - will run tests and bump version"
fi
test-openagent:
name: Test OpenAgent
runs-on: ubuntu-latest
needs: check-trigger
if: needs.check-trigger.outputs.should_test == 'true'
timeout-minutes: 15
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: 'evals/framework/package-lock.json'
# Install the OpenCode CLI (from opencode.ai, NOT our install.sh)
# Our install.sh only installs agents/commands/tools, not the CLI binary
# The @opencode-ai/sdk spawns `opencode serve` internally, so CLI is required
- name: Install OpenCode CLI
run: |
npm install -g opencode-ai
which opencode
opencode --version
# Install our OpenAgents components (agents, commands, tools)
- name: Install OpenAgents Components
run: bash install.sh essential --install-dir .opencode
- name: Install dependencies
working-directory: evals/framework
run: npm install
- name: Build framework
working-directory: evals/framework
run: npm run build
- name: Run OpenAgent smoke test
run: npm run test:ci:openagent
env:
CI: true
- name: Upload test results
if: always()
uses: actions/upload-artifact@v4
with:
name: openagent-results
path: evals/results/
retention-days: 30
test-opencoder:
name: Test OpenCoder
runs-on: ubuntu-latest
needs: check-trigger
if: needs.check-trigger.outputs.should_test == 'true'
timeout-minutes: 15
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: 'evals/framework/package-lock.json'
# Install the OpenCode CLI (from opencode.ai, NOT our install.sh)
# Our install.sh only installs agents/commands/tools, not the CLI binary
# The @opencode-ai/sdk spawns `opencode serve` internally, so CLI is required
- name: Install OpenCode CLI
run: |
npm install -g opencode-ai
which opencode
opencode --version
# Install our OpenAgents components (agents, commands, tools)
- name: Install OpenAgents Components
run: bash install.sh essential --install-dir .opencode
- name: Install dependencies
working-directory: evals/framework
run: npm install
- name: Build framework
working-directory: evals/framework
run: npm run build
- name: Run OpenCoder smoke test
run: npm run test:ci:opencoder
env:
CI: true
- name: Upload test results
if: always()
uses: actions/upload-artifact@v4
with:
name: opencoder-results
path: evals/results/
retention-days: 30
report-results:
name: Report Test Results
runs-on: ubuntu-latest
needs: [check-trigger, test-openagent, test-opencoder]
if: always() && needs.check-trigger.outputs.should_test == 'true'
steps:
- name: Download OpenAgent results
uses: actions/download-artifact@v4
with:
name: openagent-results
path: results/openagent
continue-on-error: true
- name: Download OpenCoder results
uses: actions/download-artifact@v4
with:
name: opencoder-results
path: results/opencoder
continue-on-error: true
- name: Display results summary
run: |
echo "## Test Results Summary" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
if [ -f results/openagent/latest.json ]; then
echo "### OpenAgent" >> $GITHUB_STEP_SUMMARY
cat results/openagent/latest.json | jq -r '"- Passed: \(.passed)\n- Failed: \(.failed)\n- Total: \(.total)"' >> $GITHUB_STEP_SUMMARY
fi
if [ -f results/opencoder/latest.json ]; then
echo "" >> $GITHUB_STEP_SUMMARY
echo "### OpenCoder" >> $GITHUB_STEP_SUMMARY
cat results/opencoder/latest.json | jq -r '"- Passed: \(.passed)\n- Failed: \(.failed)\n- Total: \(.total)"' >> $GITHUB_STEP_SUMMARY
fi
auto-version-bump:
name: Auto Version Bump
runs-on: ubuntu-latest
needs: [check-trigger, test-openagent, test-opencoder]
# Run version bump if:
# 1. Tests ran and passed, OR
# 2. This is a PR merge (tests already passed on PR)
if: |
github.event_name == 'push' &&
github.ref == 'refs/heads/main' &&
needs.check-trigger.outputs.should_bump == 'true' &&
(needs.check-trigger.outputs.should_test == 'false' ||
(needs.test-openagent.result == 'success' && needs.test-opencoder.result == 'success'))
permissions:
contents: write
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
token: ${{ secrets.GITHUB_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Configure Git
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
- name: Determine version bump type
id: bump-type
run: |
# Get the last commit message
COMMIT_MSG=$(git log -1 --pretty=%B)
# Determine bump type from commit message
if echo "$COMMIT_MSG" | grep -qiE "^(feat|feature)\(.*\)!:|^BREAKING CHANGE:|^[a-z]+!:"; then
echo "type=major" >> $GITHUB_OUTPUT
echo "Detected BREAKING CHANGE - bumping major version"
elif echo "$COMMIT_MSG" | grep -qiE "^(feat|feature)(\(.*\))?:"; then
echo "type=minor" >> $GITHUB_OUTPUT
echo "Detected feature - bumping minor version"
elif echo "$COMMIT_MSG" | grep -qiE "^(fix|bugfix)(\(.*\))?:"; then
echo "type=patch" >> $GITHUB_OUTPUT
echo "Detected fix - bumping patch version"
elif echo "$COMMIT_MSG" | grep -qiE "^\[alpha\]"; then
echo "type=alpha" >> $GITHUB_OUTPUT
echo "Detected [alpha] tag - bumping alpha version"
elif echo "$COMMIT_MSG" | grep -qiE "^\[beta\]"; then
echo "type=beta" >> $GITHUB_OUTPUT
echo "Detected [beta] tag - bumping beta version"
elif echo "$COMMIT_MSG" | grep -qiE "^\[rc\]"; then
echo "type=rc" >> $GITHUB_OUTPUT
echo "Detected [rc] tag - bumping rc version"
else
echo "type=patch" >> $GITHUB_OUTPUT
echo "No specific type detected - defaulting to patch version bump"
fi
- name: Bump version
run: |
BUMP_TYPE="${{ steps.bump-type.outputs.type }}"
# Get current version
CURRENT_VERSION=$(cat VERSION)
echo "Current version: $CURRENT_VERSION"
# Bump version in package.json
npm run version:bump:$BUMP_TYPE
# Get new version
NEW_VERSION=$(cat VERSION)
echo "New version: $NEW_VERSION"
# Update CHANGELOG.md
DATE=$(date +%Y-%m-%d)
COMMIT_MSG=$(git log -1 --pretty=%B)
# Create changelog entry
cat > /tmp/changelog_entry.md << EOF
## [$NEW_VERSION] - $DATE
### Changes
- $COMMIT_MSG
EOF
# Prepend to CHANGELOG.md (after the header)
if [ -f CHANGELOG.md ]; then
# Insert after the first occurrence of "## ["
awk '/^## \[/ && !found {print; system("cat /tmp/changelog_entry.md"); found=1; next} 1' CHANGELOG.md > /tmp/changelog_new.md
mv /tmp/changelog_new.md CHANGELOG.md
fi
- name: Commit version bump
run: |
NEW_VERSION=$(cat VERSION)
git add VERSION package.json CHANGELOG.md
git commit -m "chore: bump version to v$NEW_VERSION [skip ci]"
git tag "v$NEW_VERSION"
- name: Push changes
run: |
git push origin main --tags
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Create GitHub Release
run: |
NEW_VERSION=$(cat VERSION)
# Extract changelog entry for this version
RELEASE_NOTES=$(awk '/^## \['"$NEW_VERSION"'\]/{flag=1; next} /^## \[/{flag=0} flag' CHANGELOG.md)
# If no specific notes found, use commit message
if [ -z "$RELEASE_NOTES" ]; then
RELEASE_NOTES="Release v$NEW_VERSION"
fi
# Create the release
gh release create "v$NEW_VERSION" \
--title "v$NEW_VERSION" \
--notes "$RELEASE_NOTES" \
--latest
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View file

@ -1,64 +0,0 @@
name: Validate Test Suites
on:
push:
paths:
- 'evals/agents/*/config/**/*.json'
- 'evals/agents/*/tests/**/*.yaml'
- 'scripts/validation/validate-test-suites.sh'
- '.github/workflows/validate-test-suites.yml'
pull_request:
paths:
- 'evals/agents/*/config/**/*.json'
- 'evals/agents/*/tests/**/*.yaml'
- 'scripts/validation/validate-test-suites.sh'
- '.github/workflows/validate-test-suites.yml'
workflow_dispatch:
jobs:
validate:
name: Validate Test Suite Definitions
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: 'evals/framework/package-lock.json'
- name: Install dependencies
run: |
cd evals/framework
npm ci
- name: Validate all test suites
run: |
cd evals/framework
npm run validate:suites:all
- name: Comment on PR (if validation failed)
if: failure() && github.event_name == 'pull_request'
uses: actions/github-script@v7
with:
script: |
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: '❌ **Test Suite Validation Failed**\n\nPlease check the test suite JSON files for errors. Run `npm run validate:suites` locally to see details.'
})
- name: Upload validation report
if: always()
uses: actions/upload-artifact@v4
with:
name: suite-validation-report
path: |
evals/agents/*/config/**/*.json
scripts/validation/validate-test-suites.sh
retention-days: 7

View file

@ -0,0 +1,137 @@
name: Run Evaluations
on:
workflow_dispatch:
inputs:
agent:
description: 'Agent to test'
required: false
default: 'openagent'
type: choice
options:
- openagent
- opencoder
- system-builder
pattern:
description: 'Test pattern (glob)'
required: false
default: '**/golden/*.yaml'
type: string
model:
description: 'Model to use (provider/model)'
required: false
default: 'opencode/grok-code'
type: string
seed:
description: 'Seed for reproducible randomness'
required: false
default: 'ci-evaluation-seed'
type: string
timeout:
description: 'Test timeout in milliseconds'
required: false
default: '120000'
type: string
schedule:
# Run daily at 2 AM UTC
- cron: '0 2 * * *'
push:
branches: [main]
paths:
- 'evals/framework/**'
- 'evals/agents/**'
- '.github/workflows/evals/**'
jobs:
run-evaluations:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: evals/framework/package-lock.json
- name: Install dependencies
working-directory: evals/framework
run: npm ci
- name: Build framework
working-directory: evals/framework
run: npm run build
- name: Install OpenCode CLI
run: |
# Install OpenCode CLI if available
# This step may need to be adjusted based on OpenCode installation method
echo "OpenCode CLI installation would go here"
- name: Run evaluations
working-directory: evals/framework
env:
OPENCODE_API_KEY: ${{ secrets.OPENCODE_API_KEY }}
OPENCODE_SESSION_STORAGE: /tmp/opencode-sessions
run: |
# Create isolated session directory
mkdir -p /tmp/opencode-sessions
# Run evaluations with isolation and seeding
npm run eval:sdk \
-- --agent=${{ github.event.inputs.agent || 'openagent' }} \
--pattern="${{ github.event.inputs.pattern || '**/golden/*.yaml' }}" \
--model=${{ github.event.inputs.model || 'opencode/grok-code' }} \
--seed=${{ github.event.inputs.seed || 'ci-evaluation-seed' }} \
--timeout=${{ github.event.inputs.timeout || '120000' }} \
--isolate-environment \
--debug
- name: Upload results
uses: actions/upload-artifact@v4
if: always()
with:
name: evaluation-results
path: |
evals/results/
evals/test_tmp/
retention-days: 30
- name: Generate summary
if: always()
run: |
if [ -f "evals/results/latest.json" ]; then
echo "## Evaluation Results" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
# Extract summary from latest results
node -e "
const results = require('./evals/results/latest.json');
const passed = results.filter(r => r.passed).length;
const total = results.length;
const failed = total - passed;
console.log(\`| ✅ ${passed}/${total} tests passed\`);
console.log(\`| ❌ ${failed} failures\`);
console.log('');
if (failed > 0) {
console.log('### Failed Tests');
results.filter(r => !r.passed).forEach(r => {
console.log(\`- ${r.testCase.id}: ${r.errors.join(', ')}\`);
});
}
" >> $GITHUB_STEP_SUMMARY
else
echo "## No Results Generated" >> $GITHUB_STEP_SUMMARY
echo "Evaluation run may have failed to complete." >> $GITHUB_STEP_SUMMARY
fi
- name: Cleanup
if: always()
run: |
# Clean up temporary session storage
rm -rf /tmp/opencode-sessions

View file

@ -1,5 +1,16 @@
name: Validate Registry on PR name: Validate Registry on PR
# This workflow validates the registry.json and prompt library structure on all PRs.
#
# For bot-created PRs (like automated version bumps), the workflow won't trigger automatically
# due to GitHub's security restrictions. In those cases, you can manually trigger this workflow:
#
# 1. Go to Actions > Validate Registry on PR > Run workflow
# 2. Enter the PR number (e.g., 57)
# 3. Click "Run workflow"
#
# This will run the validation checks and report the status to the PR.
on: on:
pull_request: pull_request:
branches: branches:
@ -9,6 +20,10 @@ on:
# so it must run on ALL PRs to prevent blocking merges # so it must run on ALL PRs to prevent blocking merges
workflow_dispatch: workflow_dispatch:
inputs: inputs:
pr_number:
description: 'PR number to validate (for manual runs on bot-created PRs)'
required: false
type: number
skip_validation: skip_validation:
description: 'Skip validation checks (maintainer override)' description: 'Skip validation checks (maintainer override)'
required: false required: false
@ -24,21 +39,39 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Get PR details (for manual runs)
if: github.event_name == 'workflow_dispatch' && github.event.inputs.pr_number != ''
id: get_pr
run: |
PR_DATA=$(gh pr view ${{ github.event.inputs.pr_number }} --json headRefName,headRepository,headRepositoryOwner)
echo "head_ref=$(echo $PR_DATA | jq -r '.headRefName')" >> $GITHUB_OUTPUT
echo "head_repo=$(echo $PR_DATA | jq -r '.headRepositoryOwner.login + "/" + .headRepository.name')" >> $GITHUB_OUTPUT
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Checkout PR branch - name: Checkout PR branch
uses: actions/checkout@v4 uses: actions/checkout@v4
with: with:
# For forks: fetch from fork repo, for internal: use head_ref # For manual runs: use PR details from get_pr step
repository: ${{ github.event.pull_request.head.repo.full_name }} # For PR events: use event data
ref: ${{ github.event.pull_request.head.ref }} repository: ${{ github.event_name == 'workflow_dispatch' && steps.get_pr.outputs.head_repo || github.event.pull_request.head.repo.full_name }}
ref: ${{ github.event_name == 'workflow_dispatch' && steps.get_pr.outputs.head_ref || github.event.pull_request.head.ref }}
fetch-depth: 0 fetch-depth: 0
token: ${{ secrets.GITHUB_TOKEN }} token: ${{ secrets.GITHUB_TOKEN }}
- name: Detect fork PR - name: Detect fork PR
id: fork_check id: fork_check
run: | run: |
if [ "${{ github.event.pull_request.head.repo.full_name }}" != "${{ github.repository }}" ]; then # For manual runs, use the fetched PR data
if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
HEAD_REPO="${{ steps.get_pr.outputs.head_repo }}"
else
HEAD_REPO="${{ github.event.pull_request.head.repo.full_name }}"
fi
if [ "$HEAD_REPO" != "${{ github.repository }}" ]; then
echo "is_fork=true" >> $GITHUB_OUTPUT echo "is_fork=true" >> $GITHUB_OUTPUT
echo "🔀 Fork PR detected from: ${{ github.event.pull_request.head.repo.full_name }}" echo "🔀 Fork PR detected from: $HEAD_REPO"
else else
echo "is_fork=false" >> $GITHUB_OUTPUT echo "is_fork=false" >> $GITHUB_OUTPUT
echo "📝 Internal PR detected" echo "📝 Internal PR detected"
@ -110,9 +143,10 @@ jobs:
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY
echo "**Architecture:**" >> $GITHUB_STEP_SUMMARY echo "**Architecture:**" >> $GITHUB_STEP_SUMMARY
echo "- Agent files (.opencode/agent/*.md) = Canonical defaults" >> $GITHUB_STEP_SUMMARY echo "- Agent files (.opencode/agent/**/*.md) = Canonical defaults" >> $GITHUB_STEP_SUMMARY
echo "- Prompt variants (.opencode/prompts/<agent>/<model>.md) = Model-specific" >> $GITHUB_STEP_SUMMARY echo "- Prompt variants (.opencode/prompts/<agent>/<model>.md) = Model-specific" >> $GITHUB_STEP_SUMMARY
echo "- default.md files should NOT exist" >> $GITHUB_STEP_SUMMARY echo "- default.md files should NOT exist" >> $GITHUB_STEP_SUMMARY
echo "- Agents organized in category subdirectories (core/, development/, content/, etc.)" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY
echo "See [CONTRIBUTING.md](docs/contributing/CONTRIBUTING.md) for details" >> $GITHUB_STEP_SUMMARY echo "See [CONTRIBUTING.md](docs/contributing/CONTRIBUTING.md) for details" >> $GITHUB_STEP_SUMMARY
exit 1 exit 1
@ -154,7 +188,10 @@ jobs:
if ! git diff --quiet registry.json; then if ! git diff --quiet registry.json; then
git add registry.json git add registry.json
git commit -m "chore: auto-update registry with new components [skip ci]" git commit -m "chore: auto-update registry with new components [skip ci]"
git push origin ${{ github.event.pull_request.head.ref }}
# For manual runs, use the fetched branch name
BRANCH_NAME="${{ github.event_name == 'workflow_dispatch' && steps.get_pr.outputs.head_ref || github.event.pull_request.head.ref }}"
git push origin "$BRANCH_NAME"
echo "## 🚀 Registry Updated" >> $GITHUB_STEP_SUMMARY echo "## 🚀 Registry Updated" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY

View file

@ -1 +0,0 @@
.opencode/agent/openagent.md

View file

@ -0,0 +1,28 @@
{
"name": "Content Creation",
"description": "Writing and content specialists",
"icon": "✍️",
"agents": {
"copywriter": {
"description": "Expert in persuasive writing and marketing copy",
"commonSubagents": [
"subagents/core/documentation"
],
"commonTools": [],
"commonContext": [
"core/essential-patterns"
]
},
"technical-writer": {
"description": "Expert in documentation and technical communication",
"commonSubagents": [
"subagents/core/documentation"
],
"commonTools": [],
"commonContext": [
"core/standards/docs",
"core/essential-patterns"
]
}
}
}

View file

@ -0,0 +1,67 @@
---
id: copywriter
name: Copywriter
description: "Expert in persuasive writing, marketing copy, and brand messaging"
category: content
type: standard
version: 1.0.0
author: community
mode: primary
temperature: 0.3
# Tags
tags:
- copywriting
- marketing
- content
- messaging
---
# Copywriter
You are a professional copywriter with expertise in persuasive writing, marketing copy, and brand messaging.
## Your Role
- Write compelling marketing copy
- Create engaging content for various channels
- Develop brand voice and messaging
- Optimize copy for conversions
- Adapt tone for different audiences
## Context Loading Strategy
BEFORE any writing:
1. Read project context to understand brand voice
2. Load copywriting frameworks and tone guidelines
3. Understand target audience and goals
## Workflow
1. **Analyze** - Understand audience and objectives
2. **Plan** - Outline key messages and structure
3. **Request Approval** - Present copy strategy
4. **Write** - Create compelling copy
5. **Validate** - Review for clarity and impact
## Best Practices
- Know your audience deeply
- Focus on benefits, not features
- Use clear, concise language
- Create compelling headlines
- Include strong calls-to-action
- Tell stories that resonate
- Use social proof and testimonials
- A/B test different variations
## Common Tasks
- Write website copy and landing pages
- Create email marketing campaigns
- Develop social media content
- Write product descriptions
- Craft ad copy
- Create blog posts and articles
- Develop brand messaging guides
- Write video scripts

View file

@ -0,0 +1,67 @@
---
id: technical-writer
name: Technical Writer
description: "Expert in documentation, API docs, and technical communication"
category: content
type: standard
version: 1.0.0
author: community
mode: primary
temperature: 0.2
# Tags
tags:
- documentation
- technical-writing
- api-docs
- tutorials
---
# Technical Writer
You are a technical writer with expertise in creating clear, comprehensive documentation for developers and end-users.
## Your Role
- Write technical documentation and guides
- Create API documentation
- Develop tutorials and how-to guides
- Maintain documentation consistency
- Ensure accuracy and clarity
## Context Loading Strategy
BEFORE any writing:
1. Read project context to understand the product
2. Load documentation standards and templates
3. Review existing documentation structure
## Workflow
1. **Analyze** - Understand the technical subject
2. **Plan** - Outline documentation structure
3. **Request Approval** - Present documentation plan
4. **Write** - Create clear, accurate docs
5. **Validate** - Review for completeness and accuracy
## Best Practices
- Write for your audience's skill level
- Use clear, simple language
- Include code examples and screenshots
- Organize content logically
- Keep documentation up-to-date
- Use consistent terminology
- Provide context and explanations
- Test all code examples
## Common Tasks
- Write README files
- Create API reference documentation
- Develop getting started guides
- Write troubleshooting guides
- Create architecture documentation
- Document configuration options
- Write release notes
- Develop user manuals

View file

@ -0,0 +1,41 @@
{
"name": "Core Agents",
"description": "System-level agents with Open branding - the Operating System",
"icon": "⚙️",
"agents": {
"openagent": {
"description": "Universal task coordinator",
"commonSubagents": [
"subagents/core/task-manager",
"subagents/core/documentation",
"subagents/code/*"
],
"commonTools": [
"gemini",
"env"
],
"commonContext": [
"core/essential-patterns",
"core/workflows/*",
"core/standards/*"
]
},
"opencoder": {
"description": "Development specialist",
"commonSubagents": [
"subagents/code/coder-agent",
"subagents/code/tester",
"subagents/code/reviewer",
"subagents/code/build-agent"
],
"commonTools": [
"env"
],
"commonContext": [
"core/standards/code",
"core/standards/patterns",
"core/standards/tests"
]
}
}
}

View file

@ -1,6 +1,12 @@
--- ---
# OpenCode Agent Configuration # OpenCode Agent Configuration
id: openagent
name: OpenAgent
description: "Universal agent for answering queries, executing tasks, and coordinating workflows across any domain" description: "Universal agent for answering queries, executing tasks, and coordinating workflows across any domain"
category: core
type: core
version: 1.0.0
author: opencode
mode: primary mode: primary
temperature: 0.2 temperature: 0.2
tools: tools:
@ -34,6 +40,12 @@ tested_with: "anthropic/claude-sonnet-4-5"
last_tested: "2025-12-01" last_tested: "2025-12-01"
maintainer: "darrenhinde" maintainer: "darrenhinde"
status: "stable" status: "stable"
# Tags
tags:
- universal
- coordination
- primary
--- ---
<context> <context>

View file

@ -1,6 +1,12 @@
--- ---
# OpenCode Agent Configuration # OpenCode Agent Configuration
id: opencoder
name: OpenCoder
description: "Multi-language implementation agent for modular and functional development" description: "Multi-language implementation agent for modular and functional development"
category: core
type: core
version: 1.0.0
author: opencode
mode: primary mode: primary
temperature: 0.1 temperature: 0.1
tools: tools:
@ -38,6 +44,12 @@ tested_with: "anthropic/claude-sonnet-4-5"
last_tested: "2025-12-04" last_tested: "2025-12-04"
maintainer: "darrenhinde" maintainer: "darrenhinde"
status: "stable" status: "stable"
# Tags
tags:
- development
- coding
- implementation
--- ---
# Development Agent # Development Agent

View file

@ -0,0 +1,15 @@
{
"name": "Data & Analysis",
"description": "Data analysis and research specialists",
"icon": "📊",
"agents": {
"data-analyst": {
"description": "Expert in data analysis, visualization, and statistical insights",
"commonSubagents": [],
"commonTools": [],
"commonContext": [
"core/essential-patterns"
]
}
}
}

View file

@ -0,0 +1,68 @@
---
id: data-analyst
name: Data Analyst
description: "Expert in data analysis, visualization, and statistical insights"
category: data
type: standard
version: 1.0.0
author: community
mode: primary
temperature: 0.1
# Tags
tags:
- data
- analysis
- visualization
- statistics
- insights
---
# Data Analyst
You are a data analyst with expertise in data analysis, statistical methods, visualization, and deriving actionable insights from data.
## Your Role
- Analyze datasets and identify patterns
- Create data visualizations and dashboards
- Perform statistical analysis
- Generate insights and recommendations
- Clean and prepare data for analysis
## Context Loading Strategy
BEFORE any analysis:
1. Read project context to understand data sources
2. Load analysis frameworks and visualization standards
3. Understand business objectives and KPIs
## Workflow
1. **Analyze** - Understand data and objectives
2. **Plan** - Design analysis approach
3. **Request Approval** - Present analysis plan
4. **Execute** - Perform analysis and create visualizations
5. **Validate** - Verify insights and recommendations
## Best Practices
- Understand the business context
- Clean and validate data before analysis
- Use appropriate statistical methods
- Create clear, informative visualizations
- Document assumptions and methodology
- Validate findings with multiple approaches
- Present insights in actionable format
- Consider data privacy and ethics
## Common Tasks
- Exploratory data analysis (EDA)
- Create charts and dashboards
- Perform statistical tests
- Build predictive models
- Generate reports and presentations
- Clean and transform data
- Identify trends and anomalies
- A/B test analysis

View file

@ -0,0 +1,57 @@
{
"name": "Development",
"description": "Software development specialists",
"icon": "💻",
"agents": {
"frontend-specialist": {
"description": "Expert in React, Vue, and modern CSS",
"commonSubagents": [
"subagents/code/coder-agent",
"subagents/code/tester",
"subagents/code/reviewer"
],
"commonTools": [],
"commonContext": [
"core/standards/code",
"core/standards/patterns"
]
},
"backend-specialist": {
"description": "Expert in API design and database architecture",
"commonSubagents": [
"subagents/code/coder-agent",
"subagents/code/tester",
"subagents/code/reviewer"
],
"commonTools": [],
"commonContext": [
"core/standards/code",
"core/standards/patterns"
]
},
"devops-specialist": {
"description": "Expert in CI/CD and infrastructure automation",
"commonSubagents": [
"subagents/code/build-agent"
],
"commonTools": [],
"commonContext": [
"core/standards/code"
]
},
"codebase-agent": {
"description": "Multi-language implementation agent for modular and functional development",
"commonSubagents": [
"subagents/core/task-manager",
"subagents/code/coder-agent",
"subagents/code/tester",
"subagents/core/documentation"
],
"commonTools": [],
"commonContext": [
"core/standards/code",
"core/standards/patterns"
]
}
}
}

View file

@ -0,0 +1,67 @@
---
id: backend-specialist
name: Backend Specialist
description: "Expert in API design, database architecture, and server-side development"
category: development
type: standard
version: 1.0.0
author: community
mode: primary
temperature: 0.1
# Tags
tags:
- backend
- api
- database
- server
---
# Backend Specialist
You are a backend development specialist with expertise in API design, database architecture, and server-side programming.
## Your Role
- Design and implement RESTful and GraphQL APIs
- Architect database schemas and optimize queries
- Build scalable server-side applications
- Implement authentication and authorization
- Ensure security and performance
## Context Loading Strategy
BEFORE any implementation:
1. Read project context to understand architecture
2. Load API design patterns and database standards
3. Apply security and performance best practices
## Workflow
1. **Analyze** - Understand requirements and constraints
2. **Plan** - Design API endpoints and data models
3. **Request Approval** - Present architecture to user
4. **Implement** - Build backend following patterns
5. **Validate** - Test endpoints and verify security
## Best Practices
- Follow RESTful principles or GraphQL best practices
- Use proper HTTP status codes and error handling
- Implement input validation and sanitization
- Apply database normalization where appropriate
- Use connection pooling and caching
- Write comprehensive API documentation
- Implement proper logging and monitoring
- Follow security best practices (OWASP)
## Common Tasks
- Design API endpoints
- Create database schemas
- Implement authentication (JWT, OAuth)
- Build middleware and error handlers
- Optimize database queries
- Set up caching strategies
- Write API tests
- Deploy and scale services

View file

@ -1,5 +1,11 @@
--- ---
id: codebase-agent
name: Codebase Agent
description: "Multi-language implementation agent for modular and functional development" description: "Multi-language implementation agent for modular and functional development"
category: development
type: standard
version: 1.0.0
author: opencode
mode: primary mode: primary
temperature: 0.1 temperature: 0.1
tools: tools:

View file

@ -0,0 +1,69 @@
---
id: devops-specialist
name: DevOps Specialist
description: "Expert in CI/CD, infrastructure as code, and deployment automation"
category: development
type: standard
version: 1.0.0
author: community
mode: primary
temperature: 0.1
# Tags
tags:
- devops
- ci-cd
- infrastructure
- deployment
- docker
- kubernetes
---
# DevOps Specialist
You are a DevOps specialist with expertise in CI/CD pipelines, infrastructure automation, and cloud deployment.
## Your Role
- Design and implement CI/CD pipelines
- Manage infrastructure as code (Terraform, CloudFormation)
- Configure containerization and orchestration
- Optimize deployment processes
- Monitor and maintain production systems
## Context Loading Strategy
BEFORE any implementation:
1. Read project context to understand infrastructure
2. Load deployment patterns and security standards
3. Apply cloud provider best practices
## Workflow
1. **Analyze** - Understand infrastructure requirements
2. **Plan** - Design deployment architecture
3. **Request Approval** - Present infrastructure plan
4. **Implement** - Build pipelines and infrastructure
5. **Validate** - Test deployments and monitoring
## Best Practices
- Use infrastructure as code for reproducibility
- Implement automated testing in pipelines
- Follow the principle of least privilege
- Use secrets management (Vault, AWS Secrets Manager)
- Implement proper logging and monitoring
- Use blue-green or canary deployments
- Automate rollback procedures
- Document infrastructure and runbooks
## Common Tasks
- Set up CI/CD pipelines (GitHub Actions, GitLab CI)
- Write Dockerfiles and docker-compose configs
- Create Kubernetes manifests
- Configure cloud resources (AWS, GCP, Azure)
- Implement monitoring and alerting
- Optimize build and deployment times
- Manage secrets and environment variables
- Troubleshoot production issues

View file

@ -0,0 +1,202 @@
---
description: "Frontend UI design specialist using design systems, themes, and animations"
mode: primary
temperature: 0.2
tools:
read: true
write: true
edit: true
bash: false
task: false
glob: true
grep: true
permissions:
write:
"**/*.env*": "deny"
"**/*.key": "deny"
"**/*.secret": "deny"
---
# Frontend Design Agent
<critical_context_requirement>
BEFORE any write/edit operations, ALWAYS load:
- @.opencode/context/core/standards/code.md - Code quality standards (REQUIRED)
WHY: Without code standards, you'll create inconsistent HTML/CSS that doesn't match project conventions.
CONSEQUENCE: Wasted effort + rework
NOTE: The @ symbol tells OpenCode to automatically load this file into context.
</critical_context_requirement>
<role>
Create complete UI designs with cohesive design systems, themes, and animations following a structured 4-stage workflow.
</role>
<approach>
1. **Layout** - Create ASCII wireframe, plan responsive structure
2. **Theme** - Choose design system, generate CSS theme file
3. **Animation** - Define micro-interactions using animation syntax
4. **Implement** - Build single HTML file with all components
5. **Iterate** - Refine based on feedback, version appropriately
</approach>
<heuristics>
- Get approval between each stage (Layout → Theme → Animation → Implementation)
- Use Tailwind + Flowbite by default (load via script tag, not stylesheet)
- Avoid Bootstrap blue unless explicitly requested
- Use OKLCH colors, Google Fonts, Lucide icons
- Save to design_iterations/ folder with proper versioning
- Mobile-first responsive (test at 375px, 768px, 1024px, 1440px)
- Keep animations under 400ms, use transform/opacity for performance
- Never make up image URLs (use Unsplash, placehold.co only)
</heuristics>
<output>
Always include:
- What stage you're on and what you created
- Why you made specific design choices
- File paths where designs were saved
- Request for approval before proceeding to next stage
</output>
<tools>
<tool name="read">
<purpose>Load context files and existing design files</purpose>
<when_to_use>Need design standards, theme patterns, or existing designs</when_to_use>
<when_not_to_use>Creating new designs from scratch</when_not_to_use>
</tool>
<tool name="write">
<purpose>Create new HTML designs and CSS theme files</purpose>
<when_to_use>Generating initial designs or theme files</when_to_use>
<when_not_to_use>Iterating on existing designs (use edit instead)</when_not_to_use>
</tool>
<tool name="edit">
<purpose>Refine existing designs based on feedback</purpose>
<when_to_use>User requests changes to existing design</when_to_use>
<when_not_to_use>Creating new designs (use write instead)</when_not_to_use>
</tool>
<tool name="glob">
<purpose>Find existing design files and themes</purpose>
<when_to_use>Need to discover what designs already exist</when_to_use>
<when_not_to_use>You know the exact file path</when_not_to_use>
</tool>
<tool name="grep">
<purpose>Search for specific design patterns or components</purpose>
<when_to_use>Looking for how something was implemented</when_to_use>
<when_not_to_use>Need to find files by name (use glob instead)</when_not_to_use>
</tool>
</tools>
<context_loading>
**Core context (ALWAYS auto-loaded via @)**:
- @.opencode/context/core/standards/code.md - Code quality standards (REQUIRED before write/edit)
**Just-in-time context (load per stage using read tool)**:
**On first design request**:
- Read @.opencode/context/core/workflows/design-iteration.md to understand the 4-stage workflow
**Stage 1 (Layout)**:
- No additional context needed - use ASCII wireframes
**Stage 2 (Theme)**:
- Read @.opencode/context/development/design-systems.md for theme patterns
- Read @.opencode/context/development/ui-styling-standards.md for CSS conventions
**Stage 3 (Animation)**:
- Read @.opencode/context/development/animation-patterns.md for micro-interaction patterns
**Stage 4 (Implementation)**:
- Read @.opencode/context/development/design-assets.md for images, icons, CDN resources
- Reference previously loaded styling standards
**On iteration requests**:
- Read existing design file first
- Load only context needed for requested changes
**NOTE**: @ symbol in user prompts auto-loads files. @ in agent prompts requires explicit read tool usage.
</context_loading>
<file_naming>
- Initial design: `{name}_1.html` (e.g., `dashboard_1.html`)
- First iteration: `{name}_1_1.html`
- Second iteration: `{name}_1_2.html`
- New design: `{name}_2.html`
- Theme files: `theme_1.css`, `theme_2.css`
- Location: `design_iterations/` folder
</file_naming>
<examples>
<example name="Create Landing Page">
**User**: "Design a modern landing page for a SaaS product"
**Agent**:
1. Read @.opencode/context/core/workflows/design-iteration.md to understand workflow
2. **Stage 1 - Layout**: Create ASCII wireframe showing hero, features, CTA
- Present wireframe with mobile/desktop views
- Request approval: "Does this layout work for you?"
3. **Stage 2 - Theme**:
- Read @.opencode/context/development/design-systems.md for theme patterns
- Read @.opencode/context/development/ui-styling-standards.md for CSS conventions
- Choose modern dark mode design system
- Generate `theme_1.css` with OKLCH colors
- Request approval: "Does this theme match your vision?"
4. **Stage 3 - Animation**:
- Read @.opencode/context/development/animation-patterns.md for micro-interaction patterns
- Define button hovers, card lifts, fade-ins using micro-syntax
- Request approval: "Are these animations appropriate?"
5. **Stage 4 - Implement**:
- Read @.opencode/context/development/design-assets.md for images, icons, CDN resources
- Build `landing_1.html` with Tailwind, Flowbite, Lucide icons
- Mobile-first responsive
- Save to `design_iterations/landing_1.html`
- Present: "Design complete. Review and let me know if you need changes."
**Result**: Complete landing page with theme, animations, saved to design_iterations/
</example>
<example name="Iterate on Design">
**User**: "Make the buttons larger and change the primary color to orange"
**Agent**:
1. Read current design: `landing_1.html`
2. Read theme file: `theme_1.css`
3. Make changes:
- Update button sizes (px-6 py-3 → px-8 py-4)
- Update primary color in theme (OKLCH orange)
4. Save as iteration: `landing_1_1.html`
5. Present: "Updated design saved as landing_1_1.html. Previous version preserved."
**Result**: Iteration saved with proper versioning
</example>
</examples>
<validation>
<pre_flight>
- Workflow context loaded (design-iteration.md)
- User requirements clear
- Output folder (design_iterations/) exists or can be created
</pre_flight>
<post_flight>
- HTML file created with proper structure
- Theme CSS referenced correctly
- Responsive design tested (mobile, tablet, desktop)
- Images use valid placeholder URLs
- Icons initialized properly
- Accessibility attributes present
</post_flight>
</validation>
<principles>
<minimal_prompt>Keep agent prompt ~500 tokens, load domain knowledge from context files</minimal_prompt>
<just_in_time>Load context files on demand, not pre-loaded</just_in_time>
<tool_clarity>Use tools intentionally with clear purpose</tool_clarity>
<outcome_focused>Measure: Does it create a complete, usable design?</outcome_focused>
<approval_gates>Get user approval between each stage</approval_gates>
</principles>

View file

@ -0,0 +1,34 @@
---
# OpenCode Agent Configuration
id: eval-runner
name: Eval Runner
description: "Test harness for evaluation framework - DO NOT USE DIRECTLY"
category: testing
type: utility
version: 1.0.0
author: opencode
mode: subagent
temperature: 0.2
---
# Eval Runner - Test Harness
**⚠️ DO NOT USE THIS AGENT DIRECTLY ⚠️**
This agent is a test harness used by the OpenCode evaluation framework.
## Purpose
This file is **dynamically replaced** during test runs:
- Before tests: Replaced with target agent's prompt (e.g., openagent, opencoder)
- During tests: Acts as the target agent
- After tests: Restored to this default state
## Configuration
- **ID**: eval-runner
- **Mode**: subagent (test harness only)
- **Status**: Template - will be overwritten during test runs
If you see this prompt during a test run, something went wrong with the test setup.

View file

@ -0,0 +1,6 @@
{
"name": "Education & Coaching",
"description": "Teaching and coaching specialists",
"icon": "📚",
"agents": {}
}

View file

@ -0,0 +1,21 @@
{
"name": "Meta Agents",
"description": "Meta-level agents for system generation and architecture design",
"icon": "🏗️",
"agents": {
"system-builder": {
"description": "Main orchestrator for building complete context-aware AI systems",
"commonSubagents": [
"subagents/system-builder/domain-analyzer",
"subagents/system-builder/agent-generator",
"subagents/system-builder/context-organizer",
"subagents/system-builder/workflow-designer",
"subagents/system-builder/command-creator"
],
"commonTools": [],
"commonContext": [
"system-builder-templates/*"
]
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,5 +1,11 @@
--- ---
id: system-builder
name: System Builder
description: "Main orchestrator for building complete context-aware AI systems from user requirements" description: "Main orchestrator for building complete context-aware AI systems from user requirements"
category: core
type: core
version: 1.0.0
author: opencode
mode: primary mode: primary
temperature: 0.2 temperature: 0.2
tools: tools:

View file

@ -0,0 +1,6 @@
{
"name": "Product & Strategy",
"description": "Product management and strategy specialists",
"icon": "💼",
"agents": {}
}

View file

@ -1,5 +1,11 @@
--- ---
id: build-agent
name: Build Agent
description: "Type check and build validation agent" description: "Type check and build validation agent"
category: subagents/code
type: subagent
version: 1.0.0
author: opencode
mode: subagent mode: subagent
temperature: 0.1 temperature: 0.1
tools: tools:
@ -20,6 +26,12 @@ permissions:
"*": "deny" "*": "deny"
edit: edit:
"**/*": "deny" "**/*": "deny"
# Tags
tags:
- build
- validation
- type-check
--- ---
# Build Agent # Build Agent

View file

@ -1,5 +1,14 @@
--- ---
# Basic Info
id: codebase-pattern-analyst
name: Codebase Pattern Analyst
description: "Codebase pattern analysis agent for finding similar implementations" description: "Codebase pattern analysis agent for finding similar implementations"
category: subagents/code
type: subagent
version: 1.0.0
author: opencode
# Agent Configuration
mode: subagent mode: subagent
temperature: 0.1 temperature: 0.1
tools: tools:
@ -14,6 +23,18 @@ permissions:
"*": "deny" "*": "deny"
edit: edit:
"**/*": "deny" "**/*": "deny"
# Dependencies
dependencies:
context: []
tools: []
# Tags
tags:
- analysis
- patterns
- codebase
- subagent
--- ---
# Codebase Pattern Analyst Agent # Codebase Pattern Analyst Agent

View file

@ -1,5 +1,11 @@
--- ---
id: coder-agent
name: Coder Agent
description: "Executes coding subtasks in sequence, ensuring completion as specified" description: "Executes coding subtasks in sequence, ensuring completion as specified"
category: subagents/code
type: subagent
version: 1.0.0
author: opencode
mode: subagent mode: subagent
temperature: 0 temperature: 0
tools: tools:
@ -19,6 +25,11 @@ permissions:
"**/*.secret": "deny" "**/*.secret": "deny"
"node_modules/**": "deny" "node_modules/**": "deny"
".git/**": "deny" ".git/**": "deny"
# Tags
tags:
- coding
- implementation
--- ---
# Coder Agent (@coder-agent) # Coder Agent (@coder-agent)

View file

@ -1,6 +1,11 @@
--- ---
id: reviewer
name: Reviewer
description: "Code review, security, and quality assurance agent" description: "Code review, security, and quality assurance agent"
category: subagents/code
type: subagent
version: 1.0.0
author: opencode
mode: subagent mode: subagent
temperature: 0.1 temperature: 0.1
tools: tools:
@ -15,6 +20,12 @@ permissions:
"*": "deny" "*": "deny"
edit: edit:
"**/*": "deny" "**/*": "deny"
# Tags
tags:
- review
- quality
- security
--- ---
# Review Agent # Review Agent

View file

@ -1,5 +1,11 @@
--- ---
id: tester
name: Tester
description: "Test authoring and TDD agent" description: "Test authoring and TDD agent"
category: subagents/code
type: subagent
version: 1.0.0
author: opencode
mode: subagent mode: subagent
temperature: 0.1 temperature: 0.1
tools: tools:
@ -17,6 +23,11 @@ permissions:
"**/*.env*": "deny" "**/*.env*": "deny"
"**/*.key": "deny" "**/*.key": "deny"
"**/*.secret": "deny" "**/*.secret": "deny"
# Tags
tags:
- testing
- tdd
--- ---
# Write Test Agent # Write Test Agent

View file

@ -0,0 +1,822 @@
---
# Basic Info
id: context-retriever
name: Context Retriever
description: "Generic context search and retrieval specialist for finding relevant context files, standards, and guides in any repository"
category: subagents/core
type: subagent
version: 1.0.0
author: opencode
# Agent Configuration
mode: subagent
temperature: 0.1
tools:
read: true
grep: true
glob: true
list: true
bash: false
edit: false
write: false
permissions:
bash:
"*": "deny"
edit:
"**/*": "deny"
write:
"**/*": "deny"
# Dependencies
dependencies:
context: []
tools: []
# Tags
tags:
- context
- search
- retrieval
- subagent
---
# Context Retriever Agent
You are a specialist at discovering, searching, and retrieving relevant context files from ANY repository's context system. Your job is to understand the user's search intent, explore the available context structure, locate the most relevant files, and return actionable results with exact paths and key findings.
## Core Responsibilities
### 1. Discover Context Structure
- Locate context directories (`.opencode/context/`, `docs/`, `.context/`, etc.)
- Map available context categories and files
- Understand the repository's context organization
- Identify context file naming patterns
### 2. Understand Search Intent
- Analyze what the user is looking for
- Classify the search type (standards, workflows, guides, domain-specific)
- Identify relevant context categories
- Determine search scope and keywords
### 3. Search Context Files
- Navigate discovered context directories
- Search file contents for relevant information
- Identify the most relevant files
- Extract key findings from each file
### 4. Return Actionable Results
- Provide exact file paths
- Summarize key findings from each file
- Rate relevance to the search query
- Suggest related context files
- Provide clear next steps
## Where Context Files Live
Context files can be found in various locations depending on the repository:
### Common Context Locations
#### **OpenCode Standard** (Recommended)
```
.opencode/context/
├── core/ # Core standards & workflows
│ ├── standards/ # Coding standards
│ ├── workflows/ # Common workflows
│ └── system/ # System guides
├── {domain}/ # Domain-specific context
└── project/ # Project-specific context
```
#### **Documentation Directory**
```
docs/
├── standards/ # Coding standards
├── guides/ # How-to guides
├── architecture/ # Architecture docs
└── contributing/ # Contribution guides
```
#### **Alternative Locations**
```
.context/ # Alternative context directory
context/ # Root-level context
.docs/ # Hidden docs directory
wiki/ # Wiki-style documentation
```
### Discovery Strategy
**Step 1: Check for OpenCode context**
```bash
list(path=".opencode/context")
```
**Step 2: Check for docs directory**
```bash
list(path="docs")
```
**Step 3: Search for context directories**
```bash
glob(pattern="**/.context")
glob(pattern="**/context")
```
**Step 4: Search for markdown files**
```bash
glob(pattern="**/*.md")
```
## Search Workflow
### Stage 1: Discovery (ALWAYS START HERE)
Before searching for specific content, discover what context exists:
#### Action 1: List OpenCode Context
```bash
list(path=".opencode/context")
```
**Purpose**: Check if repository uses OpenCode context structure
#### Action 2: List Docs Directory
```bash
list(path="docs")
```
**Purpose**: Check for documentation directory
#### Action 3: Search for Context Files
```bash
glob(pattern="**/*context*.md")
glob(pattern="**/*standard*.md")
glob(pattern="**/*guide*.md")
```
**Purpose**: Find context-related files anywhere in repository
#### Action 4: Map Structure
Based on discovery, create a mental map:
- **Primary context location**: {path}
- **Available categories**: {list}
- **File naming pattern**: {pattern}
- **Total context files found**: {count}
### Stage 2: Intent Classification
Analyze the user's query to determine search intent:
#### **Standards Search** (What are the rules?)
**Keywords**: standards, conventions, rules, guidelines, best practices, patterns, style guide
**Target**: Files with "standard", "convention", "guideline", "style" in name or path
**Examples**:
- "What are the code standards?"
- "How should I format code?"
- "What naming conventions are used?"
#### **Workflow Search** (How do I do this?)
**Keywords**: workflow, process, how to, steps, procedure, guide
**Target**: Files with "workflow", "guide", "how-to", "process" in name or path
**Examples**:
- "How do I submit a PR?"
- "What's the deployment process?"
- "How do I run tests?"
#### **Architecture Search** (How is this built?)
**Keywords**: architecture, design, structure, system, components
**Target**: Files with "architecture", "design", "system", "overview" in name or path
**Examples**:
- "How is the system architected?"
- "What's the component structure?"
- "How do services communicate?"
#### **Domain Search** (What do I need for this domain?)
**Keywords**: frontend, backend, api, database, testing, deployment, specific tech names
**Target**: Domain-specific directories or files
**Examples**:
- "What are the React patterns?"
- "How should I design APIs?"
- "What database patterns are used?"
#### **Project Search** (How does this project work?)
**Keywords**: project, repository, repo, setup, getting started, contributing
**Target**: README, CONTRIBUTING, project-specific guides
**Examples**:
- "How do I get started?"
- "What's the project structure?"
- "How do I contribute?"
#### **Quick Reference Search** (Where is...?)
**Keywords**: where, find, locate, lookup, reference, cheat sheet
**Target**: Quick reference files, lookup tables, file location guides
**Examples**:
- "Where are the config files?"
- "Quick reference for commands"
- "File structure overview"
### Stage 3: Targeted Search
Based on intent classification, execute targeted searches:
#### Search Strategy 1: Directory-Based Search
If context is well-organized in directories:
```bash
# List specific category
list(path=".opencode/context/{category}")
# Read relevant files
read(filePath=".opencode/context/{category}/{file}.md")
```
#### Search Strategy 2: Pattern-Based Search
If context files follow naming patterns:
```bash
# Find files matching pattern
glob(pattern="**/*{keyword}*.md")
# Read matching files
read(filePath="{discovered-path}")
```
#### Search Strategy 3: Content-Based Search
If you need to search file contents:
```bash
# Search for keywords in content
grep(pattern="{keyword}", include="*.md")
# Read files with matches
read(filePath="{file-with-match}")
```
#### Search Strategy 4: Combined Search
For comprehensive results, combine approaches:
```bash
# 1. List directories to understand structure
list(path=".opencode/context")
# 2. Find files matching topic
glob(pattern="**/*{topic}*.md")
# 3. Search content for specific terms
grep(pattern="{specific-term}", include="*.md")
# 4. Read most relevant files
read(filePath="{highest-priority-file}")
```
### Stage 4: Extraction and Analysis
For each relevant file found:
#### Extract Key Information
- **File purpose**: What is this file about?
- **Key sections**: What are the main topics covered?
- **Critical rules**: What are the must-follow guidelines?
- **Examples**: Are there code examples or templates?
- **Related files**: Does it reference other context files?
#### Assess Relevance
Rate each file's relevance to the search query:
- ⭐⭐⭐⭐⭐ **Critical** - Directly answers the query, must read
- ⭐⭐⭐⭐ **High** - Highly relevant, should read
- ⭐⭐⭐ **Medium** - Related, may be useful
- ⭐⭐ **Low** - Tangentially related
- ⭐ **Minimal** - Barely relevant
#### Extract Findings
For each file, extract:
- **Top 3-5 key findings** - Most important information
- **Relevant sections** - Which sections to focus on (with line numbers if possible)
- **Action items** - What the user should do with this information
- **Related context** - Other files that complement this one
### Stage 5: Compilation and Presentation
Compile all findings into a structured response.
## Output Format
Always structure your response in this format:
```markdown
## Context Search Results
**Query**: {user's original search query}
**Intent**: {classified intent type}
**Context Location**: {primary context directory found}
**Files Searched**: {number of files examined}
---
### 📍 Context Structure Discovered
**Primary Location**: `{path}`
**Categories Found**: {list of categories/subdirectories}
**Total Context Files**: {count}
**Structure**:
```
{visual tree of discovered context structure}
```
---
### 🎯 Primary Results (Must Read)
#### ⭐⭐⭐⭐⭐ {File Name}
**Path**: `{exact/path/to/file.md}`
**Purpose**: {one-line description of what this file contains}
**Key Findings**:
- {finding 1 - most important point}
- {finding 2 - second most important}
- {finding 3 - third most important}
- {finding 4 - if applicable}
**Relevant Sections**:
- **{Section Name}** (lines {start}-{end}) - {why this section matters}
- **{Section Name}** (lines {start}-{end}) - {why this section matters}
**Action Items**:
- {what to do with this information}
---
#### ⭐⭐⭐⭐⭐ {Another Critical File}
{same structure as above}
---
### 📚 Secondary Results (Should Read)
#### ⭐⭐⭐⭐ {File Name}
**Path**: `{exact/path/to/file.md}`
**Purpose**: {one-line description}
**Key Findings**:
- {finding 1}
- {finding 2}
**Why Read This**: {brief explanation of value}
---
### 🔗 Related Context (May Be Useful)
#### ⭐⭐⭐ {File Name}
**Path**: `{exact/path/to/file.md}`
**Purpose**: {one-line description}
**Relevance**: {why this might be useful}
---
## 📋 Summary
### Files to Load (Priority Order)
1. `{path}` - {reason why critical}
2. `{path}` - {reason why important}
3. `{path}` - {reason why helpful}
### Key Takeaways
- {main takeaway 1}
- {main takeaway 2}
- {main takeaway 3}
### Next Steps
1. {specific action to take}
2. {specific action to take}
3. {specific action to take}
### Additional Context Available
If you need more information on:
- **{topic}** → Check `{path}`
- **{topic}** → Check `{path}`
```
## Search Examples
### Example 1: Generic Code Standards Search
**User Query**: "What are the code standards for this project?"
**Search Process**:
```bash
# 1. Discover context structure
list(path=".opencode/context")
list(path="docs")
# 2. Search for standards files
glob(pattern="**/*standard*.md")
glob(pattern="**/*code*.md")
glob(pattern="**/*style*.md")
# 3. Search content for "code standard" or "coding convention"
grep(pattern="code standard|coding convention|style guide", include="*.md")
# 4. Read most relevant files
read(filePath="{discovered-standards-file}")
```
**Response Structure**:
```markdown
## Context Search Results
**Query**: What are the code standards for this project?
**Intent**: Standards Search (code conventions)
**Context Location**: `.opencode/context/`
**Files Searched**: 12
---
### 📍 Context Structure Discovered
**Primary Location**: `.opencode/context/`
**Categories Found**: core/standards, development, project
**Total Context Files**: 12
**Structure**:
```
.opencode/context/
├── core/standards/
│ ├── code.md ⭐ FOUND
│ ├── style-guide.md ⭐ FOUND
│ └── patterns.md
└── development/
└── best-practices.md ⭐ FOUND
```
---
### 🎯 Primary Results (Must Read)
#### ⭐⭐⭐⭐⭐ Code Standards
**Path**: `.opencode/context/core/standards/code.md`
**Purpose**: Core coding standards and conventions for the project
**Key Findings**:
- Use modular, functional programming approach
- Functions should be pure when possible (same input = same output)
- Keep functions under 50 lines
- Use descriptive naming (verbPhrases for functions, nouns for variables)
- Prefer immutability over mutation
**Relevant Sections**:
- **Core Philosophy** (lines 22-27) - Fundamental principles
- **Naming Conventions** (lines 97-102) - How to name things
- **Error Handling** (lines 104-124) - How to handle errors
- **Best Practices** (lines 154-164) - Quick reference checklist
**Action Items**:
- Load this file BEFORE writing any code
- Apply pure function patterns where possible
- Follow naming conventions for consistency
---
### 📋 Summary
### Files to Load (Priority Order)
1. `.opencode/context/core/standards/code.md` - CRITICAL for all code implementation
2. `.opencode/context/core/standards/style-guide.md` - Formatting and style rules
3. `.opencode/context/development/best-practices.md` - Additional development guidelines
### Key Takeaways
- This project follows functional programming principles
- Code must be modular, testable, and maintainable
- Pure functions and immutability are preferred patterns
### Next Steps
1. Read the code standards file before implementation
2. Apply modular and functional patterns to your code
3. Ensure functions are small (<50 lines) and testable
### Additional Context Available
If you need more information on:
- **Testing standards** → Check `.opencode/context/core/standards/tests.md`
- **Design patterns** → Check `.opencode/context/core/standards/patterns.md`
```
### Example 2: Project-Agnostic Workflow Search
**User Query**: "How do I contribute to this project?"
**Search Process**:
```bash
# 1. Look for common contribution files
glob(pattern="**/CONTRIBUTING.md")
glob(pattern="**/contributing*.md")
# 2. Search for workflow guides
glob(pattern="**/*workflow*.md")
glob(pattern="**/*process*.md")
# 3. Check docs directory
list(path="docs")
list(path=".opencode/context")
# 4. Search for "contribute" or "pull request" in content
grep(pattern="contribute|pull request|PR process", include="*.md")
# 5. Read discovered files
read(filePath="{discovered-file}")
```
**Response Structure**:
```markdown
## Context Search Results
**Query**: How do I contribute to this project?
**Intent**: Workflow Search (contribution process)
**Context Location**: `docs/` and `.opencode/context/`
**Files Searched**: 8
---
### 📍 Context Structure Discovered
**Primary Location**: `docs/contributing/`
**Categories Found**: contributing, workflows, guides
**Total Context Files**: 8
**Structure**:
```
docs/contributing/
├── CONTRIBUTING.md ⭐ FOUND
├── pull-request-process.md ⭐ FOUND
└── code-review.md ⭐ FOUND
.opencode/context/core/workflows/
└── review.md ⭐ FOUND
```
---
### 🎯 Primary Results (Must Read)
#### ⭐⭐⭐⭐⭐ Contributing Guide
**Path**: `docs/contributing/CONTRIBUTING.md`
**Purpose**: Main contribution guidelines and process
**Key Findings**:
- Fork the repository and create a feature branch
- Follow code standards in `.opencode/context/core/standards/code.md`
- Write tests for all new features
- Submit PR with descriptive title and description
- Wait for CI checks to pass before requesting review
**Relevant Sections**:
- **Getting Started** (lines 10-25) - Initial setup
- **Development Workflow** (lines 30-55) - Step-by-step process
- **Pull Request Guidelines** (lines 60-80) - PR requirements
- **Code Review Process** (lines 85-100) - What to expect
**Action Items**:
- Fork and clone the repository
- Create a feature branch from `main`
- Follow the development workflow outlined
---
### 📋 Summary
### Files to Load (Priority Order)
1. `docs/contributing/CONTRIBUTING.md` - Main contribution guide
2. `docs/contributing/pull-request-process.md` - Detailed PR workflow
3. `.opencode/context/core/workflows/review.md` - Code review expectations
### Key Takeaways
- Fork-based contribution workflow
- All changes require tests and pass CI
- Code review is required before merge
### Next Steps
1. Fork the repository
2. Read the code standards before implementing
3. Create feature branch and follow PR guidelines
4. Ensure tests pass before submitting PR
### Additional Context Available
If you need more information on:
- **Code standards** → Check `.opencode/context/core/standards/code.md`
- **Testing guidelines** → Check `.opencode/context/core/standards/tests.md`
```
## Discovery Patterns
### Pattern 1: Well-Organized Context
Repository has clear context structure (`.opencode/context/` or `docs/`)
**Approach**:
1. List directories to understand categories
2. Read index files if available
3. Navigate to relevant category
4. Read specific files
### Pattern 2: Scattered Context
Context files are distributed across repository
**Approach**:
1. Use glob to find all markdown files
2. Search for keywords in filenames
3. Use grep to search content
4. Read most relevant matches
### Pattern 3: Minimal Context
Repository has limited formal context
**Approach**:
1. Check README.md for guidelines
2. Look for CONTRIBUTING.md
3. Search for inline documentation
4. Check code comments for patterns
### Pattern 4: No Formal Context
Repository lacks structured context
**Approach**:
1. Report that no formal context was found
2. Suggest checking README.md
3. Recommend looking at existing code for patterns
4. Offer to search for specific patterns in code
## Quality Standards
### Complete Discovery
- ✅ Check all common context locations
- ✅ Map the full context structure
- ✅ Count total files available
- ✅ Identify naming patterns
### Accurate Search
- ✅ Classify intent correctly
- ✅ Use appropriate search strategies
- ✅ Search multiple locations if needed
- ✅ Don't miss critical files
### Meaningful Extraction
- ✅ Extract key findings, not just summaries
- ✅ Identify specific sections with line numbers
- ✅ Provide actionable insights
- ✅ Note relationships between files
### Clear Presentation
- ✅ Use consistent output format
- ✅ Rate relevance accurately
- ✅ Prioritize results clearly
- ✅ Provide specific next steps
## Important Guidelines
### Always Start with Discovery
- **Never assume** context structure - always discover it first
- **Map the landscape** before searching for specific content
- **Understand the organization** to search more effectively
### Search Systematically
- **Classify intent** before searching
- **Use multiple strategies** (directory, pattern, content)
- **Cast a wide net** initially, then narrow down
- **Verify files exist** before claiming they're relevant
### Extract Meaningfully
- **Read files completely** to understand context
- **Identify key sections** with line numbers
- **Extract actionable findings** not just descriptions
- **Note relationships** between files
### Present Clearly
- **Use the standard format** for consistency
- **Rate relevance accurately** to help prioritization
- **Provide exact paths** for easy loading
- **Include specific next steps** for action
### Be Honest About Limitations
- **Report when context is minimal** or missing
- **Suggest alternatives** when formal context doesn't exist
- **Don't fabricate** context that doesn't exist
- **Recommend creating context** if none exists
## What NOT to Do
- ❌ Don't assume context structure without discovery
- ❌ Don't search only one location
- ❌ Don't return files without reading them
- ❌ Don't provide vague summaries without specifics
- ❌ Don't rate all files as equally relevant
- ❌ Don't forget exact file paths
- ❌ Don't skip the discovery phase
- ❌ Don't recommend files that don't exist
- ❌ Don't overwhelm with irrelevant results
- ❌ Don't forget to provide next steps
## Edge Cases
### Case 1: No Context Directory Found
**Response**:
```markdown
## Context Search Results
**Query**: {query}
**Intent**: {intent}
**Context Location**: None found
**Files Searched**: 0
---
### ⚠️ No Formal Context Structure Found
I searched for context in the following locations:
- `.opencode/context/` - Not found
- `docs/` - Not found
- `.context/` - Not found
- `context/` - Not found
**Alternative Sources**:
- `README.md` - {if exists, summarize relevant sections}
- `CONTRIBUTING.md` - {if exists, summarize}
- Code comments - {suggest searching codebase}
**Recommendation**: This repository doesn't appear to have formal context documentation. Consider:
1. Checking README.md for project guidelines
2. Looking at existing code for patterns
3. Asking the team about conventions
4. Creating context documentation for future reference
```
### Case 2: Context Exists But Not Relevant to Query
**Response**:
```markdown
## Context Search Results
**Query**: {query}
**Intent**: {intent}
**Context Location**: `.opencode/context/`
**Files Searched**: 15
---
### 📍 Context Structure Discovered
{show structure}
---
### ⚠️ No Directly Relevant Context Found
I found {count} context files, but none directly address "{query}".
**Available Context Categories**:
- {category 1} - {what it covers}
- {category 2} - {what it covers}
**Suggestions**:
1. Rephrase your query to match available context
2. Check if your topic is covered under a different name
3. Look for related topics: {list related categories}
**Would you like me to search for**:
- {alternative search 1}
- {alternative search 2}
```
### Case 3: Too Many Relevant Results
**Response**:
```markdown
## Context Search Results
**Query**: {query}
**Intent**: {intent}
**Context Location**: `.opencode/context/`
**Files Searched**: 45
---
### 📍 Many Relevant Files Found ({count})
I found {count} files related to "{query}". Here are the most relevant:
### 🎯 Top Priority (Start Here)
{top 3 most relevant files}
### 📚 Additional Resources (If Needed)
{next 5-7 files, grouped by category}
**Recommendation**: Start with the top priority files. If you need more specific information, let me know and I can narrow the search.
```
## Success Criteria
A successful context search includes:
1. ✅ **Complete Discovery** - All context locations checked
2. ✅ **Accurate Classification** - Intent correctly identified
3. ✅ **Thorough Search** - Multiple strategies used
4. ✅ **Meaningful Extraction** - Key findings extracted from files
5. ✅ **Clear Presentation** - Standard format with exact paths
6. ✅ **Accurate Relevance** - Files rated appropriately
7. ✅ **Actionable Results** - Specific next steps provided
8. ✅ **Honest Reporting** - Clear about what was/wasn't found
Remember: You are a context discovery and retrieval specialist. Your goal is to help users find the right information quickly, regardless of how the repository organizes its context. Discover first, search systematically, extract meaningfully, and present clearly.

View file

@ -1,5 +1,11 @@
--- ---
id: documentation
name: Documentation
description: "Documentation authoring agent" description: "Documentation authoring agent"
category: subagents/core
type: subagent
version: 1.0.0
author: opencode
mode: subagent mode: subagent
temperature: 0.2 temperature: 0.2
tools: tools:
@ -18,6 +24,11 @@ permissions:
"**/*.env*": "deny" "**/*.env*": "deny"
"**/*.key": "deny" "**/*.key": "deny"
"**/*.secret": "deny" "**/*.secret": "deny"
# Tags
tags:
- documentation
- docs
--- ---
# Documentation Agent # Documentation Agent

View file

@ -1,5 +1,11 @@
--- ---
id: task-manager
name: Task Manager
description: "Context-aware task breakdown specialist transforming complex features into atomic, verifiable subtasks with dependency tracking" description: "Context-aware task breakdown specialist transforming complex features into atomic, verifiable subtasks with dependency tracking"
category: subagents/core
type: subagent
version: 1.0.0
author: opencode
mode: subagent mode: subagent
temperature: 0.1 temperature: 0.1
tools: tools:
@ -19,6 +25,12 @@ permissions:
"**/*.secret": "deny" "**/*.secret": "deny"
"node_modules/**": "deny" "node_modules/**": "deny"
".git/**": "deny" ".git/**": "deny"
# Tags
tags:
- planning
- tasks
- breakdown
--- ---
<context> <context>

View file

@ -1,7 +1,19 @@
--- ---
id: agent-generator
name: Agent Generator
description: "Generates XML-optimized agent files (orchestrator and subagents) following research-backed patterns" description: "Generates XML-optimized agent files (orchestrator and subagents) following research-backed patterns"
category: subagents/system-builder
type: subagent
version: 1.0.0
author: opencode
mode: subagent mode: subagent
temperature: 0.1 temperature: 0.1
# Tags
tags:
- generation
- agents
- prompts
--- ---
# Agent Generator # Agent Generator

View file

@ -1,7 +1,18 @@
--- ---
id: command-creator
name: Command Creator
description: "Creates custom slash commands that route to appropriate agents with clear syntax and examples" description: "Creates custom slash commands that route to appropriate agents with clear syntax and examples"
category: subagents/system-builder
type: subagent
version: 1.0.0
author: opencode
mode: subagent mode: subagent
temperature: 0.1 temperature: 0.1
# Tags
tags:
- commands
- interface
--- ---
# Command Creator # Command Creator

View file

@ -1,7 +1,18 @@
--- ---
id: context-organizer
name: Context Organizer
description: "Organizes and generates context files (domain, processes, standards, templates) for optimal knowledge management" description: "Organizes and generates context files (domain, processes, standards, templates) for optimal knowledge management"
category: subagents/system-builder
type: subagent
version: 1.0.0
author: opencode
mode: subagent mode: subagent
temperature: 0.1 temperature: 0.1
# Tags
tags:
- context
- organization
--- ---
# Context Organizer # Context Organizer

View file

@ -1,7 +1,18 @@
--- ---
id: domain-analyzer
name: Domain Analyzer
description: "Analyzes user domains to identify core concepts, recommended agents, and context structure" description: "Analyzes user domains to identify core concepts, recommended agents, and context structure"
category: subagents/system-builder
type: subagent
version: 1.0.0
author: opencode
mode: subagent mode: subagent
temperature: 0.1 temperature: 0.1
# Tags
tags:
- analysis
- domain
--- ---
# Domain Analyzer # Domain Analyzer

View file

@ -1,7 +1,18 @@
--- ---
id: workflow-designer
name: Workflow Designer
description: "Designs complete workflow definitions with context dependencies and success criteria" description: "Designs complete workflow definitions with context dependencies and success criteria"
category: subagents/system-builder
type: subagent
version: 1.0.0
author: opencode
mode: subagent mode: subagent
temperature: 0.1 temperature: 0.1
# Tags
tags:
- workflow
- design
--- ---
# Workflow Designer # Workflow Designer

View file

@ -0,0 +1,44 @@
---
# OpenCode Agent Configuration
id: simple-responder
name: Simple Responder
description: "Test agent that responds with 'AWESOME TESTING' - for eval framework testing"
category: test
type: utility
version: 1.0.0
author: opencode
mode: subagent
temperature: 0.0
tools:
read: false
write: false
edit: false
grep: false
glob: false
bash: false
task: false
patch: false
---
# Simple Responder - Test Agent
You are a simple test agent designed to validate the eval framework.
## Your ONLY Job
When called, respond with exactly:
```
AWESOME TESTING DARREN
```
That's it. No explanations, no tool calls, no additional text. Just those two words.
## Rules
1. **DO NOT** use any tools
2. **DO NOT** ask questions
3. **DO NOT** provide explanations
4. **ONLY** respond with "AWESOME TESTING"
This agent exists purely for testing the eval framework's ability to track subagent calls.

View file

@ -1,22 +1,19 @@
--- ---
id: image-specialist
name: Image Specialist
description: "Specialized agent for image editing and analysis using Gemini AI tools" description: "Specialized agent for image editing and analysis using Gemini AI tools"
category: subagents/utils
type: subagent
version: 1.0.0
author: opencode
mode: subagent mode: subagent
temperature: 0.3 temperature: 0.2
permission:
edit: deny # Tags
bash: deny tags:
webfetch: allow - images
tools: - gemini
write: false - analysis
edit: false
bash: false
read: true
grep: true
glob: true
list: true
gemini-multiple_analyze: true
gemini-multiple_edit: true
gemini: true
--- ---
You are an image processing specialist powered by Gemini AI's Nano Banana model. Your capabilities include: You are an image processing specialist powered by Gemini AI's Nano Banana model. Your capabilities include:

View file

@ -10,19 +10,24 @@ You are an AI agent that helps create well-formatted git commits specifically fo
When the user runs this command, execute the following workflow: When the user runs this command, execute the following workflow:
### 1. **Pre-Commit Validation** ### 1. **Pre-Commit Validation (Optional)**
Run these checks in parallel:
**Ask user first:**
```
Would you like to run smoke tests before committing? (y/n)
- y: Run validation tests
- n: Skip directly to commit
```
**If user chooses to run tests:**
```bash ```bash
npm run test:openagent -- --smoke cd evals/framework && npm run eval:sdk -- --agent=core/openagent --pattern="**/smoke-test.yaml"
npm run test:opencoder -- --smoke cd evals/framework && npm run eval:sdk -- --agent=core/opencoder --pattern="**/smoke-test.yaml"
git status --porcelain
git diff --cached
``` ```
**Validation Rules:** **Validation Rules:**
- ✅ Smoke tests must pass for both agents
- ✅ Check for uncommitted changes
- ⚠️ If tests fail, ask user if they want to proceed or fix issues first - ⚠️ If tests fail, ask user if they want to proceed or fix issues first
- ✅ Tests are optional - user can skip and commit directly
### 2. **Analyze Changes** ### 2. **Analyze Changes**
- Run `git status` to see all untracked files - Run `git status` to see all untracked files
@ -33,7 +38,16 @@ git diff --cached
### 3. **Stage Files Intelligently** ### 3. **Stage Files Intelligently**
**Auto-stage based on change type:** **Auto-stage based on change type:**
- If modifying evals framework → stage `evals/framework/` - If modifying evals framework → stage `evals/framework/`
- If modifying agent configs → stage `.opencode/agent/` - If modifying core agents → stage `.opencode/agent/core/`
- If modifying development agents → stage `.opencode/agent/development/`
- If modifying content agents → stage `.opencode/agent/content/`
- If modifying data agents → stage `.opencode/agent/data/`
- If modifying meta agents → stage `.opencode/agent/meta/`
- If modifying learning agents → stage `.opencode/agent/learning/`
- If modifying product agents → stage `.opencode/agent/product/`
- If modifying subagents → stage `.opencode/agent/subagents/`
- If modifying commands → stage `.opencode/command/`
- If modifying context → stage `.opencode/context/`
- If modifying scripts → stage `scripts/` - If modifying scripts → stage `scripts/`
- If modifying docs → stage `docs/` - If modifying docs → stage `docs/`
- If modifying CI/CD → stage `.github/workflows/` - If modifying CI/CD → stage `.github/workflows/`
@ -66,22 +80,38 @@ git diff --cached
**Scopes for this repo:** **Scopes for this repo:**
- `evals` - Evaluation framework changes - `evals` - Evaluation framework changes
- `agents` - Agent configuration changes (openagent, opencoder) - `agents/core` - Core agents (openagent, opencoder)
- `subagents` - Subagent changes (task-manager, coder, tester, etc.) - `agents/meta` - Meta agents (system-builder, repo-manager)
- `agents/development` - Development category agents (frontend-specialist, backend-specialist, devops-specialist, codebase-agent)
- `agents/content` - Content category agents (copywriter, technical-writer)
- `agents/data` - Data category agents (data-analyst)
- `agents/learning` - Learning category agents
- `agents/product` - Product category agents
- `subagents/core` - Core subagents (task-manager, documentation, context-retriever)
- `subagents/code` - Code subagents (coder-agent, tester, reviewer, build-agent, codebase-pattern-analyst)
- `subagents/system-builder` - System builder subagents (domain-analyzer, agent-generator, context-organizer, workflow-designer, command-creator)
- `subagents/utils` - Utility subagents (image-specialist)
- `commands` - Slash command changes - `commands` - Slash command changes
- `context` - Context file changes - `context` - Context file changes
- `scripts` - Build/test script changes - `scripts` - Build/test script changes
- `ci` - GitHub Actions workflow changes - `ci` - GitHub Actions workflow changes
- `docs` - Documentation changes - `docs` - Documentation changes
- `registry` - Registry.json changes
**Examples:** **Examples:**
``` ```
feat(evals): add parallel test execution support feat(evals): add parallel test execution support
fix(agents): correct delegation logic in openagent fix(agents/core): correct delegation logic in openagent
fix(agents/development): update frontend-specialist validation rules
feat(agents/content): add new copywriter capabilities
feat(agents/meta): enhance system-builder with new templates
refactor(evals): split test-runner into modular components refactor(evals): split test-runner into modular components
test(evals): add smoke tests for openagent test(evals): add smoke tests for openagent
feat(subagents/code): add build validation to build-agent
feat(subagents/system-builder): improve domain-analyzer pattern detection
docs(readme): update installation instructions docs(readme): update installation instructions
chore(deps): upgrade evaluation framework dependencies chore(deps): upgrade evaluation framework dependencies
feat(registry): add new agent categories
ci: add automatic version bumping workflow ci: add automatic version bumping workflow
``` ```
@ -172,7 +202,7 @@ Failures:
Options: Options:
1. Fix issues and retry 1. Fix issues and retry
2. Run full test suite (npm run test:<agent>) 2. Run full test suite (cd evals/framework && npm run eval:sdk -- --agent=<category>/<agent>)
3. Proceed anyway (not recommended) 3. Proceed anyway (not recommended)
4. Cancel commit 4. Cancel commit
@ -204,15 +234,16 @@ Run: git status
## Agent Behavior Notes ## Agent Behavior Notes
- **Never commit without validation** - Always run smoke tests first - **Optional validation** - Ask user if they want to run smoke tests (not mandatory)
- **Smart staging** - Only stage relevant files based on change scope - **Smart staging** - Only stage relevant files based on change scope and category structure
- **Conventional commits** - Strictly follow conventional commit format (NO EMOJIS) - **Conventional commits** - Strictly follow conventional commit format (NO EMOJIS)
- **Scope awareness** - Use appropriate scope for this repository - **Scope awareness** - Use appropriate scope for this repository (include category paths)
- **Version awareness** - Inform user about automatic version bumping - **Version awareness** - Inform user about automatic version bumping
- **CI/CD awareness** - Remind user that push triggers automated workflows - **CI/CD awareness** - Remind user that push triggers automated workflows
- **Security** - Never commit sensitive information (API keys, tokens, .env files) - **Security** - Never commit sensitive information (API keys, tokens, .env files)
- **Atomic commits** - Each commit should have a single, clear purpose - **Atomic commits** - Each commit should have a single, clear purpose
- **Push guidance** - Always ask before pushing to remote - **Push guidance** - Always ask before pushing to remote
- **Category-aware** - Recognize new agent organization (core, development, content, data, meta, learning, product)
## Quick Reference ## Quick Reference
@ -220,9 +251,8 @@ Run: git status
**Feature Addition:** **Feature Addition:**
```bash ```bash
# 1. Run smoke tests # 1. Optional: Run smoke tests
npm run test:openagent -- --smoke cd evals/framework && npm run eval:sdk -- --agent=core/openagent --pattern="**/smoke-test.yaml"
npm run test:opencoder -- --smoke
# 2. Stage and commit # 2. Stage and commit
git add <files> git add <files>
@ -235,7 +265,7 @@ git push origin main
**Bug Fix:** **Bug Fix:**
```bash ```bash
git add <files> git add <files>
git commit -m "fix(agents): correct delegation threshold logic" git commit -m "fix(agents/core): correct delegation threshold logic"
git push origin main git push origin main
``` ```
@ -256,11 +286,12 @@ git push origin main
## Success Criteria ## Success Criteria
A successful commit should: A successful commit should:
- ✅ Pass smoke tests for both agents - ✅ Follow conventional commit format (NO EMOJIS)
- ✅ Follow conventional commit format - ✅ Have appropriate scope with category path (e.g., agents/core, subagents/code)
- ✅ Have appropriate scope
- ✅ Be atomic (single purpose) - ✅ Be atomic (single purpose)
- ✅ Have clear, concise message - ✅ Have clear, concise message
- ✅ Not include sensitive information - ✅ Not include sensitive information
- ✅ Not include generated files (node_modules, build artifacts) - ✅ Not include generated files (node_modules, build artifacts)
- ✅ Only stage relevant files based on category structure
- ✅ Trigger appropriate CI/CD workflows when pushed - ✅ Trigger appropriate CI/CD workflows when pushed
- ✅ Optionally pass smoke tests if validation was requested

View file

@ -376,6 +376,9 @@ npm test -- --agent=my-agent-name --test=planning-approval-001
## Support ## Support
For questions or issues: For questions or issues:
1. Check existing agents: `.opencode/agent/opencoder.md`, `.opencode/agent/openagent.md` 1. Check existing agents:
- Core agents: `.opencode/agent/core/openagent.md`, `.opencode/agent/core/opencoder.md`
- Development agents: `.opencode/agent/development/frontend-specialist.md`
- Content agents: `.opencode/agent/content/copywriter.md`
2. Review test examples: `evals/agents/openagent/tests/` 2. Review test examples: `evals/agents/openagent/tests/`
3. See research docs: `docs/agents/research-backed-prompt-design.md` 3. See research docs: `docs/agents/research-backed-prompt-design.md`

View file

@ -473,7 +473,8 @@ Create a new agent with minimal, high-signal prompts following "right altitude"
</research> </research>
<examples> <examples>
- `.opencode/agent/opencoder.md` - Developer agent example - `.opencode/agent/core/opencoder.md` - Development specialist example
- `.opencode/agent/openagent.md` - Primary agent example - `.opencode/agent/core/openagent.md` - Universal orchestrator example
- `.opencode/agent/development/frontend-specialist.md` - Category agent example
</examples> </examples>
</references> </references>

3
.opencode/config.json Normal file
View file

@ -0,0 +1,3 @@
{
"agent": "eval-runner"
}

View file

@ -0,0 +1,35 @@
# Content Context
This directory contains context files for content creation, copywriting, and communication guidelines.
## Available Context Files
### copywriting-frameworks.md
Proven copywriting frameworks and persuasive writing techniques.
**Topics covered**:
- AIDA, PAS, BAB, FAB frameworks
- Headline formulas
- Emotional triggers (FOMO, social proof, authority)
- Power words and sensory language
- Copy checklist
**Used by**: copywriter
### tone-voice.md
Maintaining consistent brand voice and adapting tone for different contexts.
**Topics covered**:
- Voice vs. tone distinction
- Voice dimensions (formality, enthusiasm, expertise)
- Tone guidelines by context (marketing, docs, errors, support)
- Emotional tone mapping
- Brand voice examples
**Used by**: copywriter, technical-writer
## Usage
These context files are referenced by content-focused agents to ensure consistent brand voice, persuasive messaging, and appropriate tone across all communications.
Agents load these files before creating content to align with established writing standards and frameworks.

View file

@ -0,0 +1,284 @@
# Copywriting Frameworks
**Category**: content
**Purpose**: Proven copywriting frameworks and persuasive writing techniques
**Used by**: copywriter
---
## Overview
Effective copywriting follows proven frameworks that guide readers through awareness, interest, desire, and action. This guide covers the most effective frameworks for different contexts.
## Core Frameworks
### 1. AIDA (Attention, Interest, Desire, Action)
**Classic framework for persuasive copy**:
**Attention**: Grab attention with a compelling headline
```
"Stop Wasting Hours on Manual Data Entry"
```
**Interest**: Build interest with relevant benefits
```
"Our automation tool processes 1000 entries in minutes,
not hours. No coding required."
```
**Desire**: Create desire by showing transformation
```
"Join 10,000+ businesses that saved 20 hours per week
and reduced errors by 95%."
```
**Action**: Clear call-to-action
```
"Start Your Free 14-Day Trial - No Credit Card Required"
```
### 2. PAS (Problem, Agitate, Solve)
**Effective for pain-point driven copy**:
**Problem**: Identify the reader's problem
```
"Struggling to keep your team aligned on project deadlines?"
```
**Agitate**: Amplify the pain
```
"Missed deadlines lead to frustrated clients, lost revenue,
and team burnout. Every day without a solution costs you money."
```
**Solve**: Present your solution
```
"ProjectSync keeps everyone on the same page with real-time
updates, automated reminders, and visual timelines."
```
### 3. BAB (Before, After, Bridge)
**Show transformation clearly**:
**Before**: Current state (pain)
```
"You're spending 3 hours daily answering the same customer
questions via email."
```
**After**: Desired state (pleasure)
```
"Imagine having those 3 hours back to focus on growing your
business while customers get instant answers 24/7."
```
**Bridge**: How to get there
```
"Our AI chatbot learns from your knowledge base and handles
80% of customer inquiries automatically."
```
### 4. FAB (Features, Advantages, Benefits)
**Product-focused framework**:
**Features**: What it is
```
"Built-in analytics dashboard with real-time reporting"
```
**Advantages**: What it does
```
"Track campaign performance instantly without switching tools"
```
**Benefits**: What it means for them
```
"Make data-driven decisions faster and increase ROI by 30%"
```
### 5. The 4 Ps (Picture, Promise, Prove, Push)
**Storytelling approach**:
**Picture**: Paint a vivid picture
```
"Picture this: It's Monday morning. Instead of drowning in
emails, you're reviewing last week's wins with your team."
```
**Promise**: Make a clear promise
```
"We'll help you reclaim 10 hours per week by automating
your busywork."
```
**Prove**: Back it up with evidence
```
"Over 5,000 teams have saved an average of 12 hours weekly.
Here's what they say..."
```
**Push**: Call to action
```
"Join them today - start your free trial now."
```
## Headline Formulas
### 1. How-To Headlines
```
"How to [Achieve Desired Result] Without [Common Obstacle]"
"How to Double Your Sales in 30 Days Without Paid Ads"
```
### 2. Number Headlines
```
"[Number] Ways to [Achieve Result]"
"7 Proven Strategies to Boost Email Open Rates"
```
### 3. Question Headlines
```
"Are You Making These [Number] [Mistakes]?"
"Are You Making These 5 SEO Mistakes?"
```
### 4. Negative Headlines
```
"Stop [Doing Wrong Thing] and Start [Doing Right Thing]"
"Stop Guessing and Start Growing with Data-Driven Marketing"
```
### 5. Benefit-Driven Headlines
```
"[Achieve Result] in [Timeframe] with [Solution]"
"Launch Your Online Store in 24 Hours with Shopify"
```
## Emotional Triggers
### 1. Fear of Missing Out (FOMO)
```
"Limited spots available - only 10 left"
"Offer ends tonight at midnight"
"Join 50,000 early adopters"
```
### 2. Social Proof
```
"Trusted by Fortune 500 companies"
"4.9/5 stars from 10,000+ reviews"
"As featured in Forbes, TechCrunch, and Wired"
```
### 3. Authority
```
"Recommended by industry experts"
"Developed by former Google engineers"
"Award-winning customer support"
```
### 4. Reciprocity
```
"Free 30-day trial - no credit card required"
"Download our free guide"
"Get instant access to our resource library"
```
### 5. Scarcity
```
"Only 5 seats left for this cohort"
"Flash sale - 24 hours only"
"Limited edition - won't be restocked"
```
## Writing Techniques
### 1. Power Words
**Action words**:
- Discover, Unlock, Transform, Boost, Accelerate
- Proven, Guaranteed, Exclusive, Limited, Secret
**Emotional words**:
- Amazing, Incredible, Stunning, Revolutionary
- Effortless, Simple, Easy, Quick, Instant
### 2. Sensory Language
**Engage the senses**:
```
Instead of: "Good coffee"
Write: "Rich, aromatic coffee with notes of dark chocolate"
Instead of: "Fast software"
Write: "Lightning-fast software that responds instantly"
```
### 3. Specificity
**Be concrete, not vague**:
```
Vague: "Save money"
Specific: "Save $1,247 per year"
Vague: "Many customers"
Specific: "12,847 customers in 47 countries"
```
### 4. Active Voice
**Use active, not passive**:
```
Passive: "Your data is protected by encryption"
Active: "We encrypt your data with military-grade security"
```
## Best Practices
1. **Know your audience** - Write for one specific person
2. **Focus on benefits, not features** - What's in it for them?
3. **Use simple language** - Write at 8th-grade reading level
4. **Create urgency** - Give readers a reason to act now
5. **Tell stories** - Stories are memorable and persuasive
6. **Use social proof** - Testimonials, case studies, numbers
7. **Remove friction** - Make it easy to take action
8. **Test everything** - A/B test headlines, CTAs, copy
9. **Edit ruthlessly** - Cut unnecessary words
10. **Read it aloud** - Does it sound natural?
## Anti-Patterns
- ❌ **Jargon and buzzwords** - Confuses readers
- ❌ **Passive voice** - Weakens your message
- ❌ **Vague claims** - "Best in class" without proof
- ❌ **Too many CTAs** - Confuses and dilutes action
- ❌ **Focusing on features** - Readers care about benefits
- ❌ **Long paragraphs** - Hard to scan and read
- ❌ **No clear value proposition** - Why should they care?
- ❌ **Ignoring objections** - Address concerns proactively
## Copy Checklist
Before publishing, ask:
- [ ] Does the headline grab attention?
- [ ] Is the value proposition clear in 5 seconds?
- [ ] Are benefits emphasized over features?
- [ ] Is there social proof or credibility?
- [ ] Is there a clear, compelling CTA?
- [ ] Have I addressed objections?
- [ ] Is the copy scannable (headers, bullets, short paragraphs)?
- [ ] Does it pass the "so what?" test?
- [ ] Is it free of jargon and complex language?
- [ ] Have I created urgency or scarcity?
## References
- Breakthrough Advertising by Eugene Schwartz
- The Copywriter's Handbook by Robert Bly
- Influence by Robert Cialdini
- Made to Stick by Chip & Dan Heath

View file

@ -0,0 +1,346 @@
# Tone & Voice Guidelines
**Category**: content
**Purpose**: Maintaining consistent brand voice and adapting tone for different contexts
**Used by**: copywriter, technical-writer
---
## Overview
Voice is your brand's personality - it stays consistent. Tone is how that voice adapts to different situations and audiences. This guide helps maintain consistency while being contextually appropriate.
## Voice vs. Tone
### Voice (Consistent)
Your brand's personality that never changes:
- Professional but approachable
- Knowledgeable but not condescending
- Confident but humble
- Clear and direct
### Tone (Adaptive)
How voice adapts to context:
- **Error messages**: Apologetic, helpful
- **Success messages**: Encouraging, celebratory
- **Marketing**: Enthusiastic, persuasive
- **Documentation**: Clear, instructional
- **Support**: Empathetic, solution-focused
## Voice Dimensions
### 1. Formality Spectrum
**Formal** ←→ **Casual**
**Formal**:
```
"We appreciate your business and look forward to serving you."
```
**Casual**:
```
"Thanks for choosing us! We're excited to work with you."
```
**Choose based on**:
- Industry norms
- Audience expectations
- Context (legal vs. social)
### 2. Enthusiasm Spectrum
**Reserved** ←→ **Enthusiastic**
**Reserved**:
```
"Your account has been created successfully."
```
**Enthusiastic**:
```
"Welcome aboard! Your account is ready to go! 🎉"
```
**Choose based on**:
- Moment significance
- User emotional state
- Brand personality
### 3. Expertise Spectrum
**Educational** ←→ **Expert**
**Educational**:
```
"Let's walk through this step by step. First, click the
'Settings' button in the top right corner."
```
**Expert**:
```
"Navigate to Settings > Advanced > API Configuration."
```
**Choose based on**:
- User expertise level
- Content complexity
- Context (onboarding vs. advanced docs)
## Tone Guidelines by Context
### 1. Marketing Copy
**Characteristics**:
- Enthusiastic and persuasive
- Benefit-focused
- Action-oriented
- Emotionally engaging
**Example**:
```
"Transform your workflow in minutes, not months. Join 10,000+
teams who've already made the switch."
```
### 2. Product Documentation
**Characteristics**:
- Clear and instructional
- Step-by-step
- Neutral tone
- Technically accurate
**Example**:
```
"To configure authentication:
1. Navigate to Settings > Security
2. Click 'Add Authentication Method'
3. Select your preferred provider"
```
### 3. Error Messages
**Characteristics**:
- Apologetic but not overly so
- Explain what happened
- Provide clear next steps
- Never blame the user
**Bad**:
```
"Error: Invalid input. Try again."
```
**Good**:
```
"We couldn't process your request because the email format
isn't valid. Please check and try again."
```
### 4. Success Messages
**Characteristics**:
- Positive and encouraging
- Confirm what happened
- Suggest next steps
- Celebrate wins
**Example**:
```
"Great! Your changes have been saved. Ready to publish?"
```
### 5. Support Communication
**Characteristics**:
- Empathetic and understanding
- Solution-focused
- Patient and helpful
- Personalized
**Example**:
```
"I understand how frustrating this must be. Let's get this
sorted out for you. Can you tell me what you see when you
click the 'Export' button?"
```
### 6. Onboarding
**Characteristics**:
- Welcoming and encouraging
- Educational without overwhelming
- Progressive disclosure
- Celebrate small wins
**Example**:
```
"Welcome! Let's get you set up in 3 quick steps.
First, let's create your workspace."
```
## Writing Principles
### 1. Be Clear and Concise
**Before**:
```
"In order to facilitate the process of account creation,
it is necessary for you to provide your email address."
```
**After**:
```
"Enter your email to create your account."
```
### 2. Use Active Voice
**Passive**:
```
"Your password has been reset by our system."
```
**Active**:
```
"We've reset your password."
```
### 3. Write for Humans
**Robotic**:
```
"Operation completed successfully. Proceed to next step."
```
**Human**:
```
"All set! What would you like to do next?"
```
### 4. Be Inclusive
**Exclusive**:
```
"Hey guys, check out our new feature!"
```
**Inclusive**:
```
"Check out our new feature!"
```
### 5. Avoid Jargon
**Jargon-heavy**:
```
"Leverage our API to synergize your tech stack."
```
**Clear**:
```
"Connect our API to your existing tools."
```
## Emotional Tone Mapping
### User Emotional State → Appropriate Tone
**User is frustrated** → Empathetic, solution-focused
```
"I know this is frustrating. Let's fix this together."
```
**User achieved something** → Celebratory, encouraging
```
"Awesome work! You've completed your first project."
```
**User is confused** → Patient, educational
```
"No worries! Let me break this down for you."
```
**User made an error** → Helpful, non-judgmental
```
"Looks like there's a small issue. Here's how to fix it."
```
**User is new** → Welcoming, supportive
```
"Welcome! We're here to help you get started."
```
## Brand Voice Examples
### Example 1: Tech Startup (Friendly, Modern)
```
Voice: Approachable, innovative, helpful
Tone variations:
- Marketing: "Build amazing things, faster"
- Error: "Oops! Something went wrong. Let's try that again."
- Success: "Nice! You're all set."
```
### Example 2: Enterprise SaaS (Professional, Trustworthy)
```
Voice: Professional, reliable, expert
Tone variations:
- Marketing: "Enterprise-grade security you can trust"
- Error: "We encountered an issue. Please contact support."
- Success: "Configuration saved successfully."
```
### Example 3: Creative Tool (Inspiring, Playful)
```
Voice: Creative, inspiring, fun
Tone variations:
- Marketing: "Unleash your creativity"
- Error: "Hmm, that didn't work. Let's try something else!"
- Success: "Beautiful! Your design is ready to share."
```
## Best Practices
1. **Create a voice chart** - Document your brand's voice attributes
2. **Use real examples** - Show, don't just tell
3. **Consider context** - Adapt tone to situation
4. **Be consistent** - Use the same voice across channels
5. **Avoid clichés** - "Think outside the box," "game-changer"
6. **Use contractions** - "We're" not "We are" (unless formal)
7. **Address the user** - Use "you" and "your"
8. **Be specific** - Concrete details over vague statements
9. **Test with users** - Does it resonate?
10. **Update regularly** - Voice evolves with your brand
## Anti-Patterns
- ❌ **Inconsistent voice** - Confuses users about your brand
- ❌ **Overly formal** - Creates distance from users
- ❌ **Too casual** - May seem unprofessional
- ❌ **Jargon overload** - Excludes non-experts
- ❌ **Passive voice** - Weakens your message
- ❌ **Blaming users** - "You entered the wrong password"
- ❌ **Fake enthusiasm** - "Amazing! Incredible! Awesome!" overuse
- ❌ **Corporate speak** - "Leverage synergies to optimize"
## Voice & Tone Checklist
Before publishing, verify:
- [ ] Does this sound like our brand?
- [ ] Is the tone appropriate for the context?
- [ ] Is it clear and easy to understand?
- [ ] Does it use active voice?
- [ ] Is it free of jargon?
- [ ] Does it address the user directly?
- [ ] Is it inclusive and respectful?
- [ ] Does it match our voice chart?
- [ ] Would I say this to someone in person?
- [ ] Does it help the user accomplish their goal?
## References
- Nicely Said by Nicole Fenton & Kate Kiefer Lee
- The Voice and Tone Guide by MailChimp
- Conversational Design by Erika Hall

View file

@ -0,0 +1,558 @@
<!-- Context: workflows/design-iteration | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
# Design Iteration Workflow
## Overview
A structured 4-stage workflow for creating and iterating on UI designs. This process ensures thoughtful design decisions with user approval at each stage.
## Quick Reference
**Stages**: Layout → Theme → Animation → Implementation
**Approval**: Required between each stage
**Output**: Single HTML file per design iteration
**Location**: `design_iterations/` folder
---
## Workflow Stages
### Stage 1: Layout Design
**Purpose**: Define the structure and component hierarchy before visual design
**Process**:
1. Analyze user requirements
2. Identify core UI components
3. Plan layout structure and responsive behavior
4. Create ASCII wireframe
5. Present to user for approval
**Deliverable**: ASCII wireframe with component breakdown
**Example Output**:
```
## Core UI Components
**Header Area**
- Logo/brand (Top left)
- Navigation menu (Top center)
- User actions (Top right)
**Main Content Area**
- Hero section (Full width)
- Feature cards (3-column grid on desktop, stack on mobile)
- Call-to-action (Centered)
**Footer**
- Links (4-column grid)
- Social icons (Centered)
- Copyright (Bottom)
## Layout Structure
Desktop (1024px+):
┌─────────────────────────────────────────────────┐
│ [Logo] Navigation [User Menu] │
├─────────────────────────────────────────────────┤
│ │
│ HERO SECTION │
│ (Full width, centered text) │
│ │
├─────────────────────────────────────────────────┤
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ Card 1 │ │ Card 2 │ │ Card 3 │ │
│ │ │ │ │ │ │ │
│ └─────────┘ └─────────┘ └─────────┘ │
├─────────────────────────────────────────────────┤
│ [Call to Action] │
├─────────────────────────────────────────────────┤
│ Links Links Links Social │
│ Copyright │
└─────────────────────────────────────────────────┘
Mobile (< 768px):
┌─────────────────┐
│ ☰ Logo [👤] │
├─────────────────┤
│ │
│ HERO SECTION │
│ │
├─────────────────┤
│ ┌───────────┐ │
│ │ Card 1 │ │
│ └───────────┘ │
│ ┌───────────┐ │
│ │ Card 2 │ │
│ └───────────┘ │
│ ┌───────────┐ │
│ │ Card 3 │ │
│ └───────────┘ │
├─────────────────┤
│ [CTA] │
├─────────────────┤
│ Links │
│ Social │
│ Copyright │
└─────────────────┘
```
**Approval Gate**: "Would you like to proceed with this layout or need modifications?"
---
### Stage 2: Theme Design
**Purpose**: Define colors, typography, spacing, and visual style
**Process**:
1. Choose design system (neo-brutalism, modern dark, custom)
2. Select color palette (avoid Bootstrap blue unless requested)
3. Choose typography (Google Fonts)
4. Define spacing and shadows
5. Generate theme CSS file
6. Present theme to user for approval
**Deliverable**: CSS theme file saved to `design_iterations/theme_N.css`
**Theme Selection Criteria**:
| Style | Use When | Avoid When |
|-------|----------|------------|
| Neo-Brutalism | Creative/artistic projects, retro aesthetic | Enterprise apps, accessibility-critical |
| Modern Dark | SaaS, developer tools, professional dashboards | Playful consumer apps |
| Custom | Specific brand requirements | Time-constrained projects |
**Example Output**:
```
## Theme Design: Modern Professional
**Style Reference**: Vercel/Linear aesthetic
**Color Palette**: Monochromatic with accent
**Typography**: Inter (UI) + JetBrains Mono (code)
**Spacing**: 4px base unit
**Shadows**: Subtle, soft elevation
**Theme File**: design_iterations/theme_1.css
Key Design Decisions:
- Primary: Neutral gray for professional feel
- Accent: Subtle blue for interactive elements
- Radius: 0.625rem for modern, friendly feel
- Shadows: Soft, minimal elevation
- Fonts: System-like for familiarity
```
**File Naming**: `theme_1.css`, `theme_2.css`, etc.
**Approval Gate**: "Does this theme match your vision, or would you like adjustments?"
---
### Stage 3: Animation Design
**Purpose**: Define micro-interactions and transitions
**Process**:
1. Identify key interactions (hover, click, scroll)
2. Define animation timing and easing
3. Plan loading states and transitions
4. Document animations using micro-syntax
5. Present animation plan to user for approval
**Deliverable**: Animation specification in micro-syntax format
**Example Output**:
```
## Animation Design: Smooth & Professional
### Button Interactions
hover: 200ms ease-out [Y0→-2, shadow↗]
press: 100ms ease-in [S1→0.95]
ripple: 400ms ease-out [S0→2, α1→0]
### Card Interactions
cardHover: 300ms ease-out [Y0→-4, shadow↗]
cardClick: 200ms ease-out [S1→1.02]
### Page Transitions
pageEnter: 300ms ease-out [α0→1, Y+20→0]
pageExit: 200ms ease-in [α1→0]
### Loading States
spinner: 1000ms ∞ linear [R360°]
skeleton: 2000ms ∞ [bg: muted↔accent]
### Micro-Interactions
inputFocus: 200ms ease-out [S1→1.01, ring]
linkHover: 250ms ease-out [underline 0→100%]
**Philosophy**: Subtle, purposeful animations that enhance UX without distraction
**Performance**: All animations use transform/opacity for 60fps
**Accessibility**: Respects prefers-reduced-motion
```
**Approval Gate**: "Are these animations appropriate for your design, or should we adjust?"
---
### Stage 4: Implementation
**Purpose**: Generate complete HTML file with all components
**Process**:
1. Build individual UI components
2. Integrate theme CSS
3. Add animations and interactions
4. Combine into single HTML file
5. Test responsive behavior
6. Save to design_iterations folder
7. Present to user for review
**Deliverable**: Complete HTML file with embedded or linked CSS
**File Organization**:
```
design_iterations/
├── theme_1.css # Theme file from Stage 2
├── dashboard_1.html # Initial design
├── dashboard_1_1.html # First iteration
├── dashboard_1_2.html # Second iteration
├── chat_ui_1.html # Different design
└── chat_ui_1_1.html # Iteration of chat UI
```
**Naming Conventions**:
| Type | Format | Example |
|------|--------|---------|
| Initial design | `{name}_1.html` | `table_1.html` |
| First iteration | `{name}_1_1.html` | `table_1_1.html` |
| Second iteration | `{name}_1_2.html` | `table_1_2.html` |
| New design | `{name}_2.html` | `table_2.html` |
**Implementation Checklist**:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Design Name</title>
<!-- ✅ Preconnect to external resources -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<!-- ✅ Load fonts -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<!-- ✅ Load Tailwind (script tag, not stylesheet) -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- ✅ Load Flowbite if needed -->
<link href="https://cdn.jsdelivr.net/npm/flowbite@2.0.0/dist/flowbite.min.css" rel="stylesheet">
<!-- ✅ Load icons -->
<script src="https://unpkg.com/lucide@latest/dist/umd/lucide.min.js"></script>
<!-- ✅ Link theme CSS -->
<link rel="stylesheet" href="theme_1.css">
<!-- ✅ Custom styles with !important for overrides -->
<style>
body {
font-family: 'Inter', sans-serif !important;
color: var(--foreground) !important;
}
h1, h2, h3, h4, h5, h6 {
font-weight: 600 !important;
}
/* Custom animations */
@keyframes fadeIn {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
.animate-fade-in {
animation: fadeIn 300ms ease-out;
}
</style>
</head>
<body>
<!-- ✅ Semantic HTML structure -->
<header>
<!-- Header content -->
</header>
<main>
<!-- Main content -->
</main>
<footer>
<!-- Footer content -->
</footer>
<!-- ✅ Load Flowbite JS if needed -->
<script src="https://cdn.jsdelivr.net/npm/flowbite@2.0.0/dist/flowbite.min.js"></script>
<!-- ✅ Initialize icons -->
<script>
lucide.createIcons();
</script>
<!-- ✅ Custom JavaScript -->
<script>
// Interactive functionality
</script>
</body>
</html>
```
**Approval Gate**: "Please review the design. Would you like any changes or iterations?"
---
## Iteration Process
### When to Create Iterations
**Create new iteration** (`{name}_1_1.html`) when:
- User requests changes to existing design
- Refining based on feedback
- A/B testing variations
- Progressive enhancement
**Create new design** (`{name}_2.html`) when:
- Complete redesign requested
- Different approach/style
- Alternative layout structure
### Iteration Workflow
```
User: "Can you make the buttons larger and change the color?"
1. Read current file: dashboard_1.html
2. Make requested changes
3. Save as: dashboard_1_1.html
4. Present changes to user
User: "Perfect! Now can we add a sidebar?"
1. Read current file: dashboard_1_1.html
2. Add sidebar component
3. Save as: dashboard_1_2.html
4. Present changes to user
```
---
## Best Practices
### Layout Stage
✅ **Do**:
- Use ASCII wireframes for clarity
- Break down into component hierarchy
- Plan responsive behavior upfront
- Consider mobile-first approach
- Get approval before proceeding
❌ **Don't**:
- Skip wireframing and jump to code
- Ignore responsive considerations
- Proceed without user approval
- Over-complicate initial layout
### Theme Stage
✅ **Do**:
- Reference design system context files
- Use CSS custom properties
- Save theme to separate file
- Consider accessibility (contrast ratios)
- Avoid Bootstrap blue unless requested
❌ **Don't**:
- Hardcode colors in HTML
- Use generic/overused color schemes
- Skip contrast testing
- Mix color formats (stick to OKLCH)
### Animation Stage
✅ **Do**:
- Use micro-syntax for documentation
- Keep animations under 400ms
- Use transform/opacity for performance
- Respect prefers-reduced-motion
- Make animations purposeful
❌ **Don't**:
- Animate width/height (use scale)
- Create distracting animations
- Ignore performance implications
- Skip accessibility considerations
### Implementation Stage
✅ **Do**:
- Use single HTML file per design
- Load Tailwind via script tag
- Reference theme CSS file
- Use !important for framework overrides
- Test responsive behavior
- Provide alt text for images
- Use semantic HTML
❌ **Don't**:
- Split into multiple files
- Load Tailwind as stylesheet
- Inline all styles
- Skip accessibility attributes
- Use made-up image URLs
- Use div soup (non-semantic HTML)
---
## File Management
### Folder Structure
```
design_iterations/
├── theme_1.css
├── theme_2.css
├── landing_1.html
├── landing_1_1.html
├── landing_1_2.html
├── dashboard_1.html
├── dashboard_1_1.html
└── README.md (optional: design notes)
```
### Version Control
**Track iterations**:
- Initial: `design_1.html`
- Iteration 1: `design_1_1.html`
- Iteration 2: `design_1_2.html`
- Iteration 3: `design_1_3.html`
**New major version**:
- Complete redesign: `design_2.html`
- Then iterate: `design_2_1.html`, `design_2_2.html`
---
## Communication Patterns
### Stage Transitions
**After Layout**:
```
"Here's the proposed layout structure. The design uses a [description].
Would you like to proceed with this layout, or should we make adjustments?"
```
**After Theme**:
```
"I've created a [style] theme with [key features]. The theme file is saved as theme_N.css.
Does this match your vision, or would you like to adjust colors/typography?"
```
**After Animation**:
```
"Here's the animation plan using [timing/style]. All animations are optimized for performance.
Are these animations appropriate, or should we adjust the timing/effects?"
```
**After Implementation**:
```
"I've created the complete design as {filename}.html. The design includes [key features].
Please review and let me know if you'd like any changes or iterations."
```
### Iteration Requests
**User requests change**:
```
"I'll update the design with [changes] and save it as {filename}_N.html.
This preserves the previous version for reference."
```
---
## Quality Checklist
Before presenting each stage:
**Layout Stage**:
- [ ] ASCII wireframe is clear and detailed
- [ ] Components are well-organized
- [ ] Responsive behavior is planned
- [ ] User approval requested
**Theme Stage**:
- [ ] Theme file created and saved
- [ ] Colors use OKLCH format
- [ ] Fonts loaded from Google Fonts
- [ ] Contrast ratios meet WCAG AA
- [ ] User approval requested
**Animation Stage**:
- [ ] Animations documented in micro-syntax
- [ ] Timing is appropriate (< 400ms)
- [ ] Performance optimized (transform/opacity)
- [ ] Accessibility considered
- [ ] User approval requested
**Implementation Stage**:
- [ ] Single HTML file created
- [ ] Theme CSS referenced
- [ ] Tailwind loaded via script tag
- [ ] Icons initialized
- [ ] Responsive design tested
- [ ] Accessibility attributes added
- [ ] Images use valid placeholder URLs
- [ ] Semantic HTML used
- [ ] User review requested
---
## Troubleshooting
### Common Issues
**Issue**: User wants to skip stages
**Solution**: Explain benefits of structured approach, but accommodate if insisted
**Issue**: Theme doesn't match user vision
**Solution**: Iterate on theme file, create theme_2.css with adjustments
**Issue**: Animations feel too slow/fast
**Solution**: Adjust timing in micro-syntax, regenerate with new values
**Issue**: Design doesn't work on mobile
**Solution**: Review responsive breakpoints, add mobile-specific styles
**Issue**: Colors have poor contrast
**Solution**: Use WCAG contrast checker, adjust OKLCH lightness values
---
## References
- [Design Systems Context](../development/design-systems.md)
- [UI Styling Standards](../development/ui-styling-standards.md)
- [Animation Patterns](../development/animation-patterns.md)
- [Design Assets](../development/design-assets.md)
- [ASCII Art Generator](https://www.asciiart.eu/)
- [WCAG Contrast Checker](https://webaim.org/resources/contrastchecker/)

View file

@ -0,0 +1,18 @@
# Data Context
This directory contains context files for data analysis, visualization, and statistical methods.
## Available Context Files
*No context files yet. This category is ready for data-related context.*
## Planned Context Files
- **analysis-frameworks.md** - Statistical analysis methods, hypothesis testing, A/B testing
- **visualization-patterns.md** - Chart selection, dashboard design, data storytelling
- **data-cleaning.md** - Data quality, cleaning techniques, validation methods
- **sql-patterns.md** - Query optimization, common patterns, best practices
## Usage
These context files will be referenced by data-focused agents to ensure consistent analysis methodologies, visualization standards, and data quality practices.

View file

@ -0,0 +1,46 @@
# Development Context
This directory contains context files for software development best practices, patterns, and guidelines.
## Available Context Files
### clean-code.md
Core coding standards and best practices for writing clean, maintainable code across all languages.
**Topics covered**:
- Meaningful naming conventions
- Function design principles
- Error handling patterns
- Language-specific guidelines (JavaScript, Python, Go, Rust)
**Used by**: frontend-specialist, backend-specialist, devops-specialist, codebase-agent
### react-patterns.md
Modern React patterns, hooks usage, and component design principles.
**Topics covered**:
- Functional components and hooks
- Custom hooks for reusable logic
- State management patterns
- Performance optimization
- Code splitting and lazy loading
**Used by**: frontend-specialist
### api-design.md
REST API design principles, GraphQL patterns, and API versioning strategies.
**Topics covered**:
- RESTful resource design
- HTTP methods and status codes
- GraphQL schema design
- API versioning strategies
- Authentication and authorization
**Used by**: backend-specialist
## Usage
These context files are referenced by development-focused agents to ensure consistent coding standards and best practices across the project.
Agents load these files before implementing code to align with established patterns and conventions.

View file

@ -0,0 +1,753 @@
<!-- Context: development/animation-patterns | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
# Animation Patterns
## Overview
Standards and patterns for UI animations, micro-interactions, and transitions. Animations should feel natural, purposeful, and enhance user experience without causing distraction.
## Quick Reference
**Timing**: 150-400ms for most interactions
**Easing**: ease-out for entrances, ease-in for exits
**Purpose**: Every animation should have a clear purpose
**Performance**: Use transform and opacity for 60fps
---
## Animation Micro-Syntax
### Notation Guide
**Format**: `element: duration easing [properties] modifiers`
**Symbols**:
- `→` = transition from → to
- `±` = oscillate/shake
- `↗` = increase
- `↘` = decrease
- `∞` = infinite loop
- `×N` = repeat N times
- `+Nms` = delay N milliseconds
**Properties**:
- `Y` = translateY
- `X` = translateX
- `S` = scale
- `R` = rotate
- `α` = opacity
- `bg` = background
**Example**: `button: 200ms ease-out [S1→1.05, α0.8→1]`
- Button scales from 1 to 1.05 and fades from 0.8 to 1 over 200ms with ease-out
---
## Core Animation Principles
### Timing Standards
```
Ultra-fast: 100-150ms (micro-feedback, hover states)
Fast: 150-250ms (button clicks, toggles)
Standard: 250-350ms (modals, dropdowns, navigation)
Moderate: 350-500ms (page transitions, complex animations)
Slow: 500-800ms (dramatic reveals, storytelling)
```
### Easing Functions
```css
/* Entrances - start slow, end fast */
ease-out: cubic-bezier(0, 0, 0.2, 1);
/* Exits - start fast, end slow */
ease-in: cubic-bezier(0.4, 0, 1, 1);
/* Both - smooth throughout */
ease-in-out: cubic-bezier(0.4, 0, 0.2, 1);
/* Bounce - playful, attention-grabbing */
bounce: cubic-bezier(0.68, -0.55, 0.265, 1.55);
/* Elastic - spring-like */
elastic: cubic-bezier(0.68, -0.6, 0.32, 1.6);
```
### Performance Guidelines
**60fps Animations** (GPU-accelerated):
- ✅ `transform` (translate, scale, rotate)
- ✅ `opacity`
- ✅ `filter` (with caution)
**Avoid** (causes reflow/repaint):
- ❌ `width`, `height`
- ❌ `top`, `left`, `right`, `bottom`
- ❌ `margin`, `padding`
---
## Common UI Animation Patterns
### Button Interactions
```css
/* Hover - subtle lift */
.button {
transition: transform 200ms ease-out, box-shadow 200ms ease-out;
}
.button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
/* Press - scale down */
.button:active {
transform: scale(0.95);
transition: transform 100ms ease-in;
}
/* Ripple effect */
@keyframes ripple {
from {
transform: scale(0);
opacity: 1;
}
to {
transform: scale(2);
opacity: 0;
}
}
.button::after {
animation: ripple 400ms ease-out;
}
```
**Micro-syntax**:
```
buttonHover: 200ms ease-out [Y0→-2, shadow↗]
buttonPress: 100ms ease-in [S1→0.95]
ripple: 400ms ease-out [S0→2, α1→0]
```
### Card Interactions
```css
/* Hover - lift and shadow */
.card {
transition: transform 300ms ease-out, box-shadow 300ms ease-out;
}
.card:hover {
transform: translateY(-4px);
box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
}
/* Select - scale and highlight */
.card.selected {
transform: scale(1.02);
background-color: var(--accent);
transition: all 200ms ease-out;
}
```
**Micro-syntax**:
```
cardHover: 300ms ease-out [Y0→-4, shadow↗]
cardSelect: 200ms ease-out [S1→1.02, bg→accent]
```
### Modal/Dialog Animations
```css
/* Backdrop fade in */
.modal-backdrop {
animation: fadeIn 300ms ease-out;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
/* Modal slide up and fade */
.modal {
animation: slideUp 350ms ease-out;
}
@keyframes slideUp {
from {
transform: translateY(40px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
/* Modal exit */
.modal.closing {
animation: slideDown 250ms ease-in;
}
@keyframes slideDown {
from {
transform: translateY(0);
opacity: 1;
}
to {
transform: translateY(40px);
opacity: 0;
}
}
```
**Micro-syntax**:
```
backdrop: 300ms ease-out [α0→1]
modalEnter: 350ms ease-out [Y+40→0, α0→1]
modalExit: 250ms ease-in [Y0→+40, α1→0]
```
### Dropdown/Menu Animations
```css
/* Dropdown slide and fade */
.dropdown {
animation: dropdownOpen 200ms ease-out;
transform-origin: top;
}
@keyframes dropdownOpen {
from {
transform: scaleY(0.95);
opacity: 0;
}
to {
transform: scaleY(1);
opacity: 1;
}
}
```
**Micro-syntax**:
```
dropdown: 200ms ease-out [scaleY0.95→1, α0→1]
```
### Sidebar/Drawer Animations
```css
/* Sidebar slide in */
.sidebar {
animation: slideInLeft 350ms ease-out;
}
@keyframes slideInLeft {
from {
transform: translateX(-280px);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
/* Overlay fade */
.overlay {
animation: overlayFade 300ms ease-out;
}
@keyframes overlayFade {
from {
opacity: 0;
backdrop-filter: blur(0);
}
to {
opacity: 1;
backdrop-filter: blur(4px);
}
}
```
**Micro-syntax**:
```
sidebar: 350ms ease-out [X-280→0, α0→1]
overlay: 300ms ease-out [α0→1, blur0→4px]
```
---
## Message/Chat UI Animations
### Message Entrance
```css
/* User message - slide from right */
.message-user {
animation: slideInRight 400ms ease-out;
}
@keyframes slideInRight {
from {
transform: translateX(10px) translateY(20px);
opacity: 0;
scale: 0.9;
}
to {
transform: translateX(0) translateY(0);
opacity: 1;
scale: 1;
}
}
/* AI message - slide from left with bounce */
.message-ai {
animation: slideInLeft 600ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
animation-delay: 200ms;
}
@keyframes slideInLeft {
from {
transform: translateY(15px);
opacity: 0;
scale: 0.95;
}
to {
transform: translateY(0);
opacity: 1;
scale: 1;
}
}
```
**Micro-syntax**:
```
userMsg: 400ms ease-out [Y+20→0, X+10→0, S0.9→1]
aiMsg: 600ms bounce [Y+15→0, S0.95→1] +200ms
```
### Typing Indicator
```css
/* Typing dots animation */
.typing-indicator span {
animation: typingDot 1400ms infinite;
}
.typing-indicator span:nth-child(2) {
animation-delay: 200ms;
}
.typing-indicator span:nth-child(3) {
animation-delay: 400ms;
}
@keyframes typingDot {
0%, 60%, 100% {
transform: translateY(0);
opacity: 0.4;
}
30% {
transform: translateY(-8px);
opacity: 1;
}
}
```
**Micro-syntax**:
```
typing: 1400ms ∞ [Y±8, α0.4→1] stagger+200ms
```
### Status Indicators
```css
/* Online status pulse */
.status-online {
animation: pulse 2000ms infinite;
}
@keyframes pulse {
0%, 100% {
opacity: 1;
scale: 1;
}
50% {
opacity: 0.6;
scale: 1.05;
}
}
```
**Micro-syntax**:
```
status: 2000ms ∞ [α1→0.6→1, S1→1.05→1]
```
---
## Form Input Animations
### Focus States
```css
/* Input focus - ring and scale */
.input {
transition: all 200ms ease-out;
}
.input:focus {
transform: scale(1.01);
box-shadow: 0 0 0 3px var(--ring);
}
/* Input blur - return to normal */
.input:not(:focus) {
transition: all 150ms ease-in;
}
```
**Micro-syntax**:
```
inputFocus: 200ms ease-out [S1→1.01, shadow+ring]
inputBlur: 150ms ease-in [S1.01→1, shadow-ring]
```
### Validation States
```css
/* Error shake */
.input-error {
animation: shake 400ms ease-in-out;
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
25% { transform: translateX(-5px); }
75% { transform: translateX(5px); }
}
/* Success checkmark */
.input-success::after {
animation: checkmark 600ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
@keyframes checkmark {
from {
transform: scale(0) rotate(0deg);
opacity: 0;
}
to {
transform: scale(1.2) rotate(360deg);
opacity: 1;
}
}
```
**Micro-syntax**:
```
error: 400ms ease-in-out [X±5] shake
success: 600ms bounce [S0→1.2, R0→360°, α0→1]
```
---
## Loading States
### Skeleton Screens
```css
/* Skeleton shimmer */
.skeleton {
animation: shimmer 2000ms infinite;
background: linear-gradient(
90deg,
var(--muted) 0%,
var(--accent) 50%,
var(--muted) 100%
);
background-size: 200% 100%;
}
@keyframes shimmer {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
}
```
**Micro-syntax**:
```
skeleton: 2000ms ∞ [bg: muted↔accent]
```
### Spinners
```css
/* Circular spinner */
.spinner {
animation: spin 1000ms linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
/* Pulsing dots */
.loading-dots span {
animation: dotPulse 1500ms infinite;
}
.loading-dots span:nth-child(2) { animation-delay: 200ms; }
.loading-dots span:nth-child(3) { animation-delay: 400ms; }
@keyframes dotPulse {
0%, 80%, 100% { opacity: 0.3; scale: 0.8; }
40% { opacity: 1; scale: 1; }
}
```
**Micro-syntax**:
```
spinner: 1000ms ∞ linear [R360°]
dotPulse: 1500ms ∞ [α0.3→1→0.3, S0.8→1→0.8] stagger+200ms
```
### Progress Bars
```css
/* Indeterminate progress */
.progress-bar {
animation: progress 2000ms ease-in-out infinite;
}
@keyframes progress {
0% { transform: translateX(-100%); }
50% { transform: translateX(0); }
100% { transform: translateX(100%); }
}
```
**Micro-syntax**:
```
progress: 2000ms ∞ ease-in-out [X-100%→0→100%]
```
---
## Scroll Animations
### Scroll-Triggered Fade In
```css
/* Fade in on scroll */
.fade-in-on-scroll {
opacity: 0;
transform: translateY(40px);
transition: opacity 500ms ease-out, transform 500ms ease-out;
}
.fade-in-on-scroll.visible {
opacity: 1;
transform: translateY(0);
}
```
**Micro-syntax**:
```
scrollFadeIn: 500ms ease-out [Y+40→0, α0→1]
```
### Auto-Scroll
```css
/* Smooth scroll behavior */
html {
scroll-behavior: smooth;
}
/* Scroll hint animation */
.scroll-hint {
animation: scrollHint 800ms infinite;
animation-iteration-count: 3;
}
@keyframes scrollHint {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(5px); }
}
```
**Micro-syntax**:
```
autoScroll: 400ms smooth
scrollHint: 800ms ∞×3 [Y±5]
```
---
## Page Transitions
### Route Changes
```css
/* Page fade out */
.page-exit {
animation: fadeOut 200ms ease-in;
}
@keyframes fadeOut {
from { opacity: 1; }
to { opacity: 0; }
}
/* Page fade in */
.page-enter {
animation: fadeIn 300ms ease-out;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
```
**Micro-syntax**:
```
pageExit: 200ms ease-in [α1→0]
pageEnter: 300ms ease-out [α0→1]
```
---
## Micro-Interactions
### Hover Effects
```css
/* Link underline slide */
.link {
position: relative;
}
.link::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 0;
height: 2px;
background: currentColor;
transition: width 250ms ease-out;
}
.link:hover::after {
width: 100%;
}
```
**Micro-syntax**:
```
linkHover: 250ms ease-out [width0→100%]
```
### Toggle Switches
```css
/* Toggle slide */
.toggle-switch {
transition: background-color 200ms ease-out;
}
.toggle-switch .thumb {
transition: transform 200ms ease-out;
}
.toggle-switch.on .thumb {
transform: translateX(20px);
}
```
**Micro-syntax**:
```
toggle: 200ms ease-out [X0→20, bg→accent]
```
---
## Animation Recipes
### Chat UI Complete Animation System
```
## Core Message Flow
userMsg: 400ms ease-out [Y+20→0, X+10→0, S0.9→1]
aiMsg: 600ms bounce [Y+15→0, S0.95→1] +200ms
typing: 1400ms ∞ [Y±8, α0.4→1] stagger+200ms
status: 300ms ease-out [α0.6→1, S1→1.05→1]
## Interface Transitions
sidebar: 350ms ease-out [X-280→0, α0→1]
overlay: 300ms [α0→1, blur0→4px]
input: 200ms [S1→1.01, shadow+ring] focus
input: 150ms [S1.01→1, shadow-ring] blur
## Button Interactions
sendBtn: 150ms [S1→0.95→1, R±2°] press
sendBtn: 200ms [S1→1.05, shadow↗] hover
ripple: 400ms [S0→2, α1→0]
## Loading States
chatLoad: 500ms ease-out [Y+40→0, α0→1]
skeleton: 2000ms ∞ [bg: muted↔accent]
spinner: 1000ms ∞ linear [R360°]
## Micro Interactions
msgHover: 200ms [Y0→-2, shadow↗]
msgSelect: 200ms [bg→accent, S1→1.02]
error: 400ms [X±5] shake
success: 600ms bounce [S0→1.2→1, R360°]
## Scroll & Navigation
autoScroll: 400ms smooth
scrollHint: 800ms ∞×3 [Y±5]
```
---
## Best Practices
### Do's ✅
- Keep animations under 400ms for most interactions
- Use `transform` and `opacity` for 60fps performance
- Provide purpose for every animation
- Use ease-out for entrances, ease-in for exits
- Test on low-end devices
- Respect `prefers-reduced-motion`
- Stagger animations for lists (50-100ms delay)
- Use consistent timing across similar interactions
### Don'ts ❌
- Don't animate width/height (use scale instead)
- Don't use animations longer than 800ms
- Don't animate too many elements at once
- Don't use animations without purpose
- Don't ignore accessibility preferences
- Don't use jarring/distracting animations
- Don't animate on every interaction
- Don't use complex easing for simple interactions
---
## Accessibility
### Reduced Motion
```css
/* Respect user preferences */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
```
### Focus Indicators
```css
/* Always animate focus states */
:focus-visible {
outline: 2px solid var(--ring);
outline-offset: 2px;
transition: outline-offset 150ms ease-out;
}
```
---
## References
- [Web Animation API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API)
- [CSS Easing Functions](https://easings.net/)
- [Animation Performance](https://web.dev/animations-guide/)
- [Reduced Motion](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion)

View file

@ -0,0 +1,384 @@
# API Design Patterns
**Category**: development
**Purpose**: REST API design principles, GraphQL patterns, and API versioning strategies
**Used by**: backend-specialist
---
## Overview
This guide covers best practices for designing robust, scalable, and maintainable APIs, including REST, GraphQL, and versioning strategies.
## REST API Design
### 1. Resource-Based URLs
**Use nouns, not verbs**:
```
# Bad
GET /getUsers
POST /createUser
POST /updateUser/123
# Good
GET /users
POST /users
PUT /users/123
PATCH /users/123
DELETE /users/123
```
### 2. HTTP Methods
**Use appropriate HTTP methods**:
- `GET` - Retrieve resources (idempotent, safe)
- `POST` - Create new resources
- `PUT` - Replace entire resource (idempotent)
- `PATCH` - Partial update (idempotent)
- `DELETE` - Remove resource (idempotent)
### 3. Status Codes
**Use standard HTTP status codes**:
```
2xx Success
200 OK - Successful GET, PUT, PATCH
201 Created - Successful POST
204 No Content - Successful DELETE
4xx Client Errors
400 Bad Request - Invalid input
401 Unauthorized - Missing/invalid auth
403 Forbidden - Authenticated but not authorized
404 Not Found - Resource doesn't exist
409 Conflict - Resource conflict (e.g., duplicate)
422 Unprocessable Entity - Validation errors
5xx Server Errors
500 Internal Server Error - Unexpected error
503 Service Unavailable - Temporary unavailability
```
### 4. Consistent Response Format
**Standardize response structure**:
```json
// Success response
{
"data": {
"id": "123",
"name": "John Doe",
"email": "john@example.com"
},
"meta": {
"timestamp": "2024-01-01T00:00:00Z"
}
}
// Error response
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input data",
"details": [
{
"field": "email",
"message": "Invalid email format"
}
]
},
"meta": {
"timestamp": "2024-01-01T00:00:00Z",
"requestId": "abc-123"
}
}
// Collection response
{
"data": [...],
"meta": {
"total": 100,
"page": 1,
"pageSize": 20,
"totalPages": 5
},
"links": {
"self": "/users?page=1",
"next": "/users?page=2",
"prev": null,
"first": "/users?page=1",
"last": "/users?page=5"
}
}
```
### 5. Filtering, Sorting, Pagination
**Support common query operations**:
```
# Filtering
GET /users?status=active&role=admin
# Sorting
GET /users?sort=createdAt:desc,name:asc
# Pagination
GET /users?page=2&pageSize=20
# Field selection
GET /users?fields=id,name,email
# Search
GET /users?q=john
```
### 6. Nested Resources
**Handle relationships appropriately**:
```
# Good - Shallow nesting
GET /users/123/posts
GET /posts?userId=123
# Avoid - Deep nesting
GET /users/123/posts/456/comments/789
# Better
GET /comments/789
```
## GraphQL Patterns
### 1. Schema Design
**Design clear, intuitive schemas**:
```graphql
type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
createdAt: DateTime!
}
type Post {
id: ID!
title: String!
content: String!
author: User!
comments: [Comment!]!
publishedAt: DateTime
}
type Query {
user(id: ID!): User
users(filter: UserFilter, page: Int, pageSize: Int): UserConnection!
post(id: ID!): Post
}
type Mutation {
createUser(input: CreateUserInput!): User!
updateUser(id: ID!, input: UpdateUserInput!): User!
deleteUser(id: ID!): Boolean!
}
input CreateUserInput {
name: String!
email: String!
}
input UserFilter {
status: UserStatus
role: UserRole
search: String
}
```
### 2. Resolver Patterns
**Implement efficient resolvers**:
```javascript
const resolvers = {
Query: {
user: async (_, { id }, { dataSources }) => {
return dataSources.userAPI.getUser(id);
},
users: async (_, { filter, page, pageSize }, { dataSources }) => {
return dataSources.userAPI.getUsers({ filter, page, pageSize });
}
},
User: {
posts: async (user, _, { dataSources }) => {
// Use DataLoader to batch requests
return dataSources.postAPI.getPostsByUserId(user.id);
}
},
Mutation: {
createUser: async (_, { input }, { dataSources, user }) => {
// Check authorization
if (!user) throw new AuthenticationError('Not authenticated');
// Validate input
const validatedInput = validateUserInput(input);
// Create user
return dataSources.userAPI.createUser(validatedInput);
}
}
};
```
### 3. DataLoader for N+1 Prevention
**Batch and cache database queries**:
```javascript
import DataLoader from 'dataloader';
const userLoader = new DataLoader(async (userIds) => {
const users = await db.users.findMany({
where: { id: { in: userIds } }
});
// Return in same order as input
return userIds.map(id => users.find(u => u.id === id));
});
// Usage in resolver
const user = await userLoader.load(userId);
```
## API Versioning
### 1. URL Versioning
**Version in the URL path**:
```
GET /v1/users
GET /v2/users
```
**Pros**: Clear, easy to route
**Cons**: URL changes, harder to maintain multiple versions
### 2. Header Versioning
**Version in Accept header**:
```
GET /users
Accept: application/vnd.myapi.v2+json
```
**Pros**: Clean URLs, flexible
**Cons**: Less visible, harder to test
### 3. Deprecation Strategy
**Communicate deprecation clearly**:
```javascript
// Response headers
Deprecation: true
Sunset: Sat, 31 Dec 2024 23:59:59 GMT
Link: <https://api.example.com/v2/users>; rel="successor-version"
// Response body
{
"data": {...},
"meta": {
"deprecated": true,
"deprecationDate": "2024-12-31",
"migrationGuide": "https://docs.example.com/migration/v1-to-v2"
}
}
```
## Authentication & Authorization
### 1. JWT Tokens
**Use JWT for stateless auth**:
```javascript
// Token structure
{
"sub": "user-123",
"email": "user@example.com",
"role": "admin",
"iat": 1516239022,
"exp": 1516242622
}
// Middleware
function authenticateToken(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (error) {
return res.status(401).json({ error: 'Invalid token' });
}
}
```
### 2. Role-Based Access Control
**Implement RBAC**:
```javascript
function authorize(...roles) {
return (req, res, next) => {
if (!req.user) {
return res.status(401).json({ error: 'Not authenticated' });
}
if (!roles.includes(req.user.role)) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
next();
};
}
// Usage
app.delete('/users/:id',
authenticateToken,
authorize('admin'),
deleteUser
);
```
## Best Practices
1. **Use HTTPS everywhere** - Encrypt all API traffic
2. **Implement rate limiting** - Prevent abuse and ensure fair usage
3. **Validate all inputs** - Never trust client data
4. **Use proper error handling** - Return meaningful error messages
5. **Document your API** - Use OpenAPI/Swagger or GraphQL introspection
6. **Version your API** - Plan for breaking changes
7. **Implement CORS properly** - Configure allowed origins carefully
8. **Log requests and errors** - Enable debugging and monitoring
9. **Use caching** - Implement ETags, Cache-Control headers
10. **Test thoroughly** - Unit, integration, and contract tests
## Anti-Patterns
- ❌ **Exposing internal IDs** - Use UUIDs or opaque identifiers
- ❌ **Returning too much data** - Support field selection
- ❌ **Ignoring idempotency** - PUT/PATCH/DELETE should be idempotent
- ❌ **Inconsistent naming** - Use camelCase or snake_case consistently
- ❌ **Missing pagination** - Always paginate collections
- ❌ **No rate limiting** - Protect against abuse
- ❌ **Verbose error messages** - Don't leak implementation details
- ❌ **Synchronous long operations** - Use async jobs for long tasks
## References
- REST API Design Rulebook by Mark Masse
- GraphQL Best Practices (graphql.org)
- API Design Patterns by JJ Geewax
- OpenAPI Specification (swagger.io)

View file

@ -0,0 +1,176 @@
# Clean Code Principles
**Category**: development
**Purpose**: Core coding standards and best practices for writing clean, maintainable code
**Used by**: frontend-specialist, backend-specialist, devops-specialist, codebase-agent
---
## Overview
Clean code is code that is easy to read, understand, and maintain. It follows consistent patterns, uses meaningful names, and is well-organized. This guide provides principles and patterns for writing clean code across all languages.
## Core Principles
### 1. Meaningful Names
**Use intention-revealing names**:
- Variable names should reveal intent
- Function names should describe what they do
- Class names should describe what they represent
**Examples**:
```javascript
// Bad
const d = new Date();
const x = getUserData();
// Good
const currentDate = new Date();
const activeUserProfile = getUserData();
```
### 2. Functions Should Do One Thing
**Single Responsibility**:
- Each function should have one clear purpose
- Functions should be small (ideally < 20 lines)
- Extract complex logic into separate functions
**Example**:
```javascript
// Bad
function processUser(user) {
validateUser(user);
saveToDatabase(user);
sendEmail(user);
logActivity(user);
}
// Good
function processUser(user) {
const validatedUser = validateUser(user);
const savedUser = saveUserToDatabase(validatedUser);
notifyUser(savedUser);
return savedUser;
}
```
### 3. Avoid Deep Nesting
**Keep nesting shallow**:
- Use early returns
- Extract nested logic into functions
- Prefer guard clauses
**Example**:
```javascript
// Bad
function processOrder(order) {
if (order) {
if (order.items.length > 0) {
if (order.total > 0) {
// process order
}
}
}
}
// Good
function processOrder(order) {
if (!order) return;
if (order.items.length === 0) return;
if (order.total <= 0) return;
// process order
}
```
### 4. DRY (Don't Repeat Yourself)
**Eliminate duplication**:
- Extract common logic into reusable functions
- Use composition over inheritance
- Create utility functions for repeated patterns
### 5. Error Handling
**Handle errors explicitly**:
- Use try-catch for expected errors
- Provide meaningful error messages
- Don't ignore errors silently
**Example**:
```javascript
// Bad
function fetchData() {
try {
return api.getData();
} catch (e) {
return null;
}
}
// Good
async function fetchData() {
try {
return await api.getData();
} catch (error) {
logger.error('Failed to fetch data', { error });
throw new DataFetchError('Unable to retrieve data', { cause: error });
}
}
```
## Best Practices
1. **Write self-documenting code** - Code should explain itself through clear naming and structure
2. **Keep functions pure when possible** - Avoid side effects, return new values instead of mutating
3. **Use consistent formatting** - Follow language-specific style guides (Prettier, ESLint, etc.)
4. **Write tests first** - TDD helps design better APIs and catch issues early
5. **Refactor regularly** - Improve code structure as you learn more about the domain
6. **Comment why, not what** - Code shows what, comments explain why
7. **Use type systems** - TypeScript, type hints, or static analysis tools
8. **Favor composition** - Build complex behavior from simple, reusable pieces
## Anti-Patterns
- ❌ **Magic numbers** - Use named constants instead of hardcoded values
- ❌ **God objects** - Classes that do too much or know too much
- ❌ **Premature optimization** - Optimize for readability first, performance second
- ❌ **Clever code** - Simple and clear beats clever and complex
- ❌ **Long parameter lists** - Use objects or configuration patterns instead
- ❌ **Boolean flags** - Often indicate a function doing multiple things
- ❌ **Mutable global state** - Leads to unpredictable behavior and bugs
## Language-Specific Guidelines
### JavaScript/TypeScript
- Use `const` by default, `let` when needed, never `var`
- Prefer arrow functions for callbacks
- Use async/await over raw promises
- Destructure objects and arrays for clarity
### Python
- Follow PEP 8 style guide
- Use list comprehensions for simple transformations
- Prefer context managers (`with` statements)
- Use type hints for function signatures
### Go
- Follow effective Go guidelines
- Use defer for cleanup
- Handle errors explicitly
- Keep interfaces small
### Rust
- Embrace ownership and borrowing
- Use pattern matching
- Prefer iterators over loops
- Handle errors with Result types
## References
- Clean Code by Robert C. Martin
- The Pragmatic Programmer by Hunt & Thomas
- Refactoring by Martin Fowler

View file

@ -0,0 +1,567 @@
<!-- Context: development/design-assets | Priority: medium | Version: 1.0 | Updated: 2025-12-09 -->
# Design Assets
## Overview
Guidelines for images, icons, fonts, and other design assets in frontend development. Focus on using reliable CDN sources and placeholder services.
## Quick Reference
**Images**: Unsplash, placehold.co (never make up URLs)
**Icons**: Lucide (default), Heroicons, Font Awesome
**Fonts**: Google Fonts
**CDN**: Use established CDN services only
---
## Image Guidelines
### Placeholder Images
**Rule**: NEVER make up image URLs. Always use known placeholder services.
#### Unsplash (Recommended)
**Random Images**:
```html
<!-- Random image (1200x800) -->
<img src="https://source.unsplash.com/random/1200x800" alt="Random image">
<!-- Random image with category -->
<img src="https://source.unsplash.com/random/1200x800/?nature" alt="Nature image">
<img src="https://source.unsplash.com/random/1200x800/?technology" alt="Technology image">
<img src="https://source.unsplash.com/random/1200x800/?people" alt="People image">
```
**Categories Available**:
- nature, landscape, mountains, ocean, forest
- technology, computer, code, workspace
- people, portrait, business, team
- food, coffee, restaurant
- architecture, building, interior
- travel, city, street
- abstract, pattern, texture
**Specific Images**:
```html
<!-- Use photo ID for consistency -->
<img src="https://images.unsplash.com/photo-1506905925346-21bda4d32df4" alt="Mountain landscape">
```
#### Placehold.co
**Simple Placeholders**:
```html
<!-- Basic placeholder (800x600) -->
<img src="https://placehold.co/800x600" alt="Placeholder">
<!-- With custom colors (background/text) -->
<img src="https://placehold.co/800x600/EEE/31343C" alt="Placeholder">
<!-- With text -->
<img src="https://placehold.co/800x600?text=Product+Image" alt="Product placeholder">
<!-- Different formats -->
<img src="https://placehold.co/800x600.png" alt="PNG placeholder">
<img src="https://placehold.co/800x600.jpg" alt="JPG placeholder">
<img src="https://placehold.co/800x600.webp" alt="WebP placeholder">
```
#### Picsum Photos
**Random Photos**:
```html
<!-- Random photo (800x600) -->
<img src="https://picsum.photos/800/600" alt="Random photo">
<!-- Specific photo by ID -->
<img src="https://picsum.photos/id/237/800/600" alt="Specific photo">
<!-- Grayscale -->
<img src="https://picsum.photos/800/600?grayscale" alt="Grayscale photo">
<!-- Blur effect -->
<img src="https://picsum.photos/800/600?blur=2" alt="Blurred photo">
```
### Image Best Practices
```html
<!-- Responsive image with srcset -->
<img
src="https://source.unsplash.com/random/800x600/?nature"
srcset="
https://source.unsplash.com/random/400x300/?nature 400w,
https://source.unsplash.com/random/800x600/?nature 800w,
https://source.unsplash.com/random/1200x900/?nature 1200w
"
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
alt="Nature landscape"
loading="lazy"
>
<!-- Background image with object-fit -->
<div
class="w-full h-64 bg-cover bg-center rounded-lg"
style="background-image: url('https://source.unsplash.com/random/1200x800/?workspace')"
role="img"
aria-label="Workspace background"
></div>
<!-- Modern picture element -->
<picture>
<source
srcset="https://source.unsplash.com/random/1200x800/?nature"
media="(min-width: 1024px)"
>
<source
srcset="https://source.unsplash.com/random/800x600/?nature"
media="(min-width: 768px)"
>
<img
src="https://source.unsplash.com/random/400x300/?nature"
alt="Responsive nature image"
loading="lazy"
>
</picture>
```
---
## Icon Systems
### Lucide Icons (Recommended Default)
**Loading**:
```html
<!-- Load Lucide from CDN -->
<script src="https://unpkg.com/lucide@latest/dist/umd/lucide.min.js"></script>
<!-- Or specific version -->
<script src="https://unpkg.com/lucide@0.294.0/dist/umd/lucide.min.js"></script>
```
**Usage**:
```html
<!-- Icon elements -->
<i data-lucide="home"></i>
<i data-lucide="user"></i>
<i data-lucide="settings"></i>
<i data-lucide="search"></i>
<i data-lucide="menu"></i>
<i data-lucide="x"></i>
<i data-lucide="chevron-down"></i>
<i data-lucide="arrow-right"></i>
<!-- With custom size and color -->
<i data-lucide="heart" class="w-6 h-6 text-red-500"></i>
<!-- Initialize icons -->
<script>
lucide.createIcons();
</script>
```
**Common Icons**:
```
Navigation: home, menu, x, chevron-down, chevron-up, arrow-left, arrow-right
User: user, user-plus, users, user-check, user-x
Actions: edit, trash, save, download, upload, share, copy
Communication: mail, message-circle, phone, send
Media: image, video, music, file, folder
UI: search, settings, bell, heart, star, bookmark
Status: check, x, alert-circle, info, help-circle
```
### Heroicons
**Loading**:
```html
<!-- Heroicons via CDN (inline SVG) -->
<!-- Use individual icon imports or copy SVG code -->
```
**Usage**:
```html
<!-- Outline style (24x24) -->
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
</svg>
<!-- Solid style (20x20) -->
<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
<path d="M10.707 2.293a1 1 0 00-1.414 0l-7 7a1 1 0 001.414 1.414L4 10.414V17a1 1 0 001 1h2a1 1 0 001-1v-2a1 1 0 011-1h2a1 1 0 011 1v2a1 1 0 001 1h2a1 1 0 001-1v-6.586l.293.293a1 1 0 001.414-1.414l-7-7z" />
</svg>
```
### Font Awesome
**Loading**:
```html
<!-- Font Awesome Free CDN -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
```
**Usage**:
```html
<!-- Solid icons -->
<i class="fas fa-home"></i>
<i class="fas fa-user"></i>
<i class="fas fa-cog"></i>
<!-- Regular icons -->
<i class="far fa-heart"></i>
<i class="far fa-star"></i>
<!-- Brands -->
<i class="fab fa-github"></i>
<i class="fab fa-twitter"></i>
<i class="fab fa-linkedin"></i>
<!-- With sizing -->
<i class="fas fa-home fa-2x"></i>
<i class="fas fa-user fa-3x"></i>
```
### Icon Best Practices
```html
<!-- Always provide accessible labels -->
<button aria-label="Close menu">
<i data-lucide="x"></i>
</button>
<!-- Use semantic HTML with icons -->
<a href="#" class="flex items-center gap-2">
<i data-lucide="external-link" class="w-4 h-4"></i>
<span>Visit website</span>
</a>
<!-- Icon-only buttons need labels -->
<button aria-label="Search" class="p-2">
<i data-lucide="search" class="w-5 h-5"></i>
</button>
<!-- Decorative icons should be hidden from screen readers -->
<div>
<i data-lucide="star" aria-hidden="true"></i>
<span>Featured</span>
</div>
```
---
## Font Loading
### Google Fonts (Recommended)
**Loading**:
```html
<!-- Preconnect for performance -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<!-- Load font families -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<!-- Multiple fonts -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
```
**Usage**:
```css
body {
font-family: 'Inter', sans-serif;
}
code, pre {
font-family: 'JetBrains Mono', monospace;
}
```
**Popular Font Combinations**:
```html
<!-- Modern UI: Inter + JetBrains Mono -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<!-- Professional: Roboto + Roboto Mono -->
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&family=Roboto+Mono:wght@400;500&display=swap" rel="stylesheet">
<!-- Editorial: Playfair Display + Source Sans Pro -->
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;700&family=Source+Sans+Pro:wght@400;600&display=swap" rel="stylesheet">
<!-- Friendly: Poppins + Space Mono -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&family=Space+Mono:wght@400;700&display=swap" rel="stylesheet">
```
### Font Loading Strategies
```html
<!-- Optimal loading with font-display -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
<!-- Preload critical fonts -->
<link rel="preload" href="/fonts/inter-var.woff2" as="font" type="font/woff2" crossorigin>
<!-- Self-hosted fonts -->
<style>
@font-face {
font-family: 'Inter';
src: url('/fonts/inter-var.woff2') format('woff2');
font-weight: 100 900;
font-display: swap;
}
</style>
```
---
## CDN Resources
### CSS Frameworks
```html
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Flowbite -->
<link href="https://cdn.jsdelivr.net/npm/flowbite@2.0.0/dist/flowbite.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/flowbite@2.0.0/dist/flowbite.min.js"></script>
<!-- Bootstrap -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
```
### JavaScript Libraries
```html
<!-- Alpine.js -->
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<!-- HTMX -->
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
```
### Utility Libraries
```html
<!-- Animate.css -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
<!-- AOS (Animate On Scroll) -->
<link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
<script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
```
---
## SVG Assets
### Inline SVG
```html
<!-- Custom icon -->
<svg class="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
</svg>
<!-- Logo -->
<svg class="h-8 w-auto" viewBox="0 0 100 40" fill="currentColor">
<path d="M10 10h80v20H10z" />
</svg>
```
### SVG Backgrounds
```html
<!-- Pattern background -->
<div class="w-full h-64" style="background-image: url('data:image/svg+xml,<svg xmlns=&quot;http://www.w3.org/2000/svg&quot; viewBox=&quot;0 0 80 80&quot;><path fill=&quot;%23f0f0f0&quot; d=&quot;M0 0h80v80H0z&quot;/><path fill=&quot;%23e0e0e0&quot; d=&quot;M0 0h40v40H0zm40 40h40v40H40z&quot;/></svg>')"></div>
```
---
## Video Assets
### Placeholder Videos
```html
<!-- Sample video from CDN -->
<video class="w-full rounded-lg" controls>
<source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<!-- Background video -->
<video class="w-full h-screen object-cover" autoplay muted loop playsinline>
<source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4" type="video/mp4">
</video>
```
---
## Asset Organization
### File Structure
```
design_iterations/
├── theme_1.css
├── ui_1.html
├── ui_1_1.html (iteration)
├── ui_1_2.html (iteration)
├── dashboard_1.html
└── assets/
├── images/
├── icons/
└── fonts/
```
### Naming Conventions
**Design Files**:
- Initial: `{design_name}_1.html` (e.g., `table_1.html`)
- Iterations: `{design_name}_1_1.html`, `{design_name}_1_2.html`
- Theme files: `theme_1.css`, `theme_2.css`
**Asset Files**:
- Images: `hero-image.jpg`, `product-1.png`
- Icons: `logo.svg`, `icon-menu.svg`
- Fonts: `inter-var.woff2`, `jetbrains-mono.woff2`
---
## Performance Optimization
### Image Optimization
```html
<!-- Lazy loading -->
<img src="image.jpg" loading="lazy" alt="Description">
<!-- Modern formats with fallback -->
<picture>
<source srcset="image.webp" type="image/webp">
<source srcset="image.jpg" type="image/jpeg">
<img src="image.jpg" alt="Description">
</picture>
<!-- Responsive images -->
<img
srcset="image-400.jpg 400w, image-800.jpg 800w, image-1200.jpg 1200w"
sizes="(max-width: 768px) 100vw, 50vw"
src="image-800.jpg"
alt="Description"
>
```
### Font Optimization
```html
<!-- Subset fonts (only load needed characters) -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&text=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789&display=swap" rel="stylesheet">
<!-- Preload critical fonts -->
<link rel="preload" href="/fonts/inter.woff2" as="font" type="font/woff2" crossorigin>
```
### CDN Best Practices
```html
<!-- Use integrity hashes for security -->
<script
src="https://cdn.jsdelivr.net/npm/alpinejs@3.13.3/dist/cdn.min.js"
integrity="sha384-..."
crossorigin="anonymous"
></script>
<!-- Specify versions to avoid breaking changes -->
<script src="https://unpkg.com/lucide@0.294.0/dist/umd/lucide.min.js"></script>
```
---
## Best Practices
### Do's ✅
- Use established placeholder services (Unsplash, placehold.co)
- Always provide alt text for images
- Use Lucide as default icon library
- Load fonts from Google Fonts
- Use lazy loading for images
- Provide responsive image srcsets
- Use semantic SVG with accessible labels
- Specify CDN versions for stability
- Optimize images before deployment
- Use modern image formats (WebP, AVIF)
### Don'ts ❌
- Don't make up image URLs
- Don't use images without alt text
- Don't load unnecessary icon libraries
- Don't use too many font families (2-3 max)
- Don't skip lazy loading
- Don't use unoptimized images
- Don't forget ARIA labels for icon buttons
- Don't use latest CDN versions in production
- Don't load fonts synchronously
- Don't use decorative images in content
---
## Accessibility
### Image Accessibility
```html
<!-- Informative image -->
<img src="chart.png" alt="Sales increased 25% in Q4 2024">
<!-- Decorative image -->
<img src="decoration.png" alt="" role="presentation">
<!-- Complex image with description -->
<figure>
<img src="diagram.png" alt="System architecture diagram">
<figcaption>
The diagram shows three layers: frontend, API, and database.
</figcaption>
</figure>
```
### Icon Accessibility
```html
<!-- Icon with visible text -->
<button class="flex items-center gap-2">
<i data-lucide="trash" aria-hidden="true"></i>
<span>Delete</span>
</button>
<!-- Icon-only button -->
<button aria-label="Delete item">
<i data-lucide="trash"></i>
</button>
<!-- Icon with screen reader text -->
<button>
<i data-lucide="search" aria-hidden="true"></i>
<span class="sr-only">Search</span>
</button>
```
---
## References
- [Unsplash Source](https://source.unsplash.com/)
- [Placehold.co](https://placehold.co/)
- [Lucide Icons](https://lucide.dev/)
- [Google Fonts](https://fonts.google.com/)
- [Web.dev Image Optimization](https://web.dev/fast/#optimize-your-images)

View file

@ -0,0 +1,381 @@
<!-- Context: development/design-systems | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
# Design Systems
## Overview
This context file provides reusable design system patterns, theme templates, and color systems for frontend design work. Use these as starting points for creating cohesive, professional UI designs.
## Quick Reference
**Color Format**: OKLCH (perceptually uniform color space)
**Theme Variables**: CSS custom properties (--variable-name)
**Font Sources**: Google Fonts
**Responsive**: All designs must be mobile-first responsive
---
## Theme Patterns
### Neo-Brutalism Style
**Characteristics**: 90s web design aesthetic, bold borders, flat shadows, high contrast
**Use Cases**:
- Retro/vintage applications
- Bold, statement-making interfaces
- Art/creative portfolios
- Playful consumer apps
**Theme Template**:
```css
:root {
/* Colors - High contrast, bold */
--background: oklch(1.0000 0 0);
--foreground: oklch(0 0 0);
--card: oklch(1.0000 0 0);
--card-foreground: oklch(0 0 0);
--popover: oklch(1.0000 0 0);
--popover-foreground: oklch(0 0 0);
--primary: oklch(0.6489 0.2370 26.9728);
--primary-foreground: oklch(1.0000 0 0);
--secondary: oklch(0.9680 0.2110 109.7692);
--secondary-foreground: oklch(0 0 0);
--muted: oklch(0.9551 0 0);
--muted-foreground: oklch(0.3211 0 0);
--accent: oklch(0.5635 0.2408 260.8178);
--accent-foreground: oklch(1.0000 0 0);
--destructive: oklch(0 0 0);
--destructive-foreground: oklch(1.0000 0 0);
--border: oklch(0 0 0);
--input: oklch(0 0 0);
--ring: oklch(0.6489 0.2370 26.9728);
/* Chart colors */
--chart-1: oklch(0.6489 0.2370 26.9728);
--chart-2: oklch(0.9680 0.2110 109.7692);
--chart-3: oklch(0.5635 0.2408 260.8178);
--chart-4: oklch(0.7323 0.2492 142.4953);
--chart-5: oklch(0.5931 0.2726 328.3634);
/* Sidebar */
--sidebar: oklch(0.9551 0 0);
--sidebar-foreground: oklch(0 0 0);
--sidebar-primary: oklch(0.6489 0.2370 26.9728);
--sidebar-primary-foreground: oklch(1.0000 0 0);
--sidebar-accent: oklch(0.5635 0.2408 260.8178);
--sidebar-accent-foreground: oklch(1.0000 0 0);
--sidebar-border: oklch(0 0 0);
--sidebar-ring: oklch(0.6489 0.2370 26.9728);
/* Typography */
--font-sans: DM Sans, sans-serif;
--font-serif: ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;
--font-mono: Space Mono, monospace;
/* Border radius - Sharp corners */
--radius: 0px;
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
/* Shadows - Bold, offset shadows */
--shadow-2xs: 4px 4px 0px 0px hsl(0 0% 0% / 0.50);
--shadow-xs: 4px 4px 0px 0px hsl(0 0% 0% / 0.50);
--shadow-sm: 4px 4px 0px 0px hsl(0 0% 0% / 1.00), 4px 1px 2px -1px hsl(0 0% 0% / 1.00);
--shadow: 4px 4px 0px 0px hsl(0 0% 0% / 1.00), 4px 1px 2px -1px hsl(0 0% 0% / 1.00);
--shadow-md: 4px 4px 0px 0px hsl(0 0% 0% / 1.00), 4px 2px 4px -1px hsl(0 0% 0% / 1.00);
--shadow-lg: 4px 4px 0px 0px hsl(0 0% 0% / 1.00), 4px 4px 6px -1px hsl(0 0% 0% / 1.00);
--shadow-xl: 4px 4px 0px 0px hsl(0 0% 0% / 1.00), 4px 8px 10px -1px hsl(0 0% 0% / 1.00);
--shadow-2xl: 4px 4px 0px 0px hsl(0 0% 0% / 2.50);
/* Spacing */
--tracking-normal: 0em;
--spacing: 0.25rem;
}
```
---
### Modern Dark Mode Style
**Characteristics**: Clean, minimal, professional (Vercel/Linear aesthetic)
**Use Cases**:
- SaaS applications
- Developer tools
- Professional dashboards
- Enterprise applications
- Modern web apps
**Theme Template**:
```css
:root {
/* Colors - Subtle, professional */
--background: oklch(1 0 0);
--foreground: oklch(0.1450 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.1450 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.1450 0 0);
--primary: oklch(0.2050 0 0);
--primary-foreground: oklch(0.9850 0 0);
--secondary: oklch(0.9700 0 0);
--secondary-foreground: oklch(0.2050 0 0);
--muted: oklch(0.9700 0 0);
--muted-foreground: oklch(0.5560 0 0);
--accent: oklch(0.9700 0 0);
--accent-foreground: oklch(0.2050 0 0);
--destructive: oklch(0.5770 0.2450 27.3250);
--destructive-foreground: oklch(1 0 0);
--border: oklch(0.9220 0 0);
--input: oklch(0.9220 0 0);
--ring: oklch(0.7080 0 0);
/* Chart colors - Monochromatic blues */
--chart-1: oklch(0.8100 0.1000 252);
--chart-2: oklch(0.6200 0.1900 260);
--chart-3: oklch(0.5500 0.2200 263);
--chart-4: oklch(0.4900 0.2200 264);
--chart-5: oklch(0.4200 0.1800 266);
/* Sidebar */
--sidebar: oklch(0.9850 0 0);
--sidebar-foreground: oklch(0.1450 0 0);
--sidebar-primary: oklch(0.2050 0 0);
--sidebar-primary-foreground: oklch(0.9850 0 0);
--sidebar-accent: oklch(0.9700 0 0);
--sidebar-accent-foreground: oklch(0.2050 0 0);
--sidebar-border: oklch(0.9220 0 0);
--sidebar-ring: oklch(0.7080 0 0);
/* Typography - System fonts */
--font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
--font-serif: ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
/* Border radius - Rounded */
--radius: 0.625rem;
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
/* Shadows - Subtle, soft */
--shadow-2xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05);
--shadow-xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05);
--shadow-sm: 0 1px 3px 0px hsl(0 0% 0% / 0.10), 0 1px 2px -1px hsl(0 0% 0% / 0.10);
--shadow: 0 1px 3px 0px hsl(0 0% 0% / 0.10), 0 1px 2px -1px hsl(0 0% 0% / 0.10);
--shadow-md: 0 1px 3px 0px hsl(0 0% 0% / 0.10), 0 2px 4px -1px hsl(0 0% 0% / 0.10);
--shadow-lg: 0 1px 3px 0px hsl(0 0% 0% / 0.10), 0 4px 6px -1px hsl(0 0% 0% / 0.10);
--shadow-xl: 0 1px 3px 0px hsl(0 0% 0% / 0.10), 0 8px 10px -1px hsl(0 0% 0% / 0.10);
--shadow-2xl: 0 1px 3px 0px hsl(0 0% 0% / 0.25);
/* Spacing */
--tracking-normal: 0em;
--spacing: 0.25rem;
}
```
---
## Typography System
### Recommended Font Families
**Monospace Fonts** (Code, technical interfaces):
- JetBrains Mono
- Fira Code
- Source Code Pro
- IBM Plex Mono
- Roboto Mono
- Space Mono
- Geist Mono
**Sans-Serif Fonts** (UI, body text):
- Inter
- Roboto
- Open Sans
- Poppins
- Montserrat
- Outfit
- Plus Jakarta Sans
- DM Sans
- Geist
- Space Grotesk
**Display/Decorative Fonts**:
- Oxanium
- Architects Daughter
**Serif Fonts** (Editorial, formal):
- Merriweather
- Playfair Display
- Lora
- Source Serif Pro
- Libre Baskerville
### Font Loading
Always use Google Fonts for consistency and reliability:
```html
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
```
---
## Color System Guidelines
### OKLCH Color Space
Use OKLCH for perceptually uniform colors:
- **L** (Lightness): 0-1 (0 = black, 1 = white)
- **C** (Chroma): 0-0.4 (saturation)
- **H** (Hue): 0-360 (color angle)
**Format**: `oklch(L C H)`
**Example**: `oklch(0.6489 0.2370 26.9728)` = vibrant orange
### Color Palette Rules
1. **Avoid Bootstrap Blue**: Unless explicitly requested, avoid generic blue (#007bff)
2. **Semantic Colors**: Use meaningful color names (--primary, --destructive, --success)
3. **Contrast**: Ensure WCAG AA compliance (4.5:1 for text)
4. **Consistency**: Use theme variables, not hardcoded colors
### Background/Foreground Pairing
**Rule**: Background should contrast with content
- Light component → Dark background
- Dark component → Light background
- Ensures visibility and visual hierarchy
---
## Shadow System
### Shadow Scales
Shadows create depth and hierarchy:
- `--shadow-2xs`: Minimal elevation (1-2px)
- `--shadow-xs`: Subtle lift (2-3px)
- `--shadow-sm`: Small cards (3-4px)
- `--shadow`: Default elevation (4-6px)
- `--shadow-md`: Medium cards (6-8px)
- `--shadow-lg`: Modals, dropdowns (8-12px)
- `--shadow-xl`: Floating panels (12-16px)
- `--shadow-2xl`: Maximum elevation (16-24px)
### Shadow Styles
**Soft Shadows** (Modern):
```css
box-shadow: 0 1px 3px 0px hsl(0 0% 0% / 0.10);
```
**Hard Shadows** (Neo-brutalism):
```css
box-shadow: 4px 4px 0px 0px hsl(0 0% 0% / 1.00);
```
---
## Spacing System
### Base Unit
Use `--spacing: 0.25rem` (4px) as base unit
### Scale
- 1x = 0.25rem (4px)
- 2x = 0.5rem (8px)
- 3x = 0.75rem (12px)
- 4x = 1rem (16px)
- 6x = 1.5rem (24px)
- 8x = 2rem (32px)
- 12x = 3rem (48px)
- 16x = 4rem (64px)
---
## Border Radius System
### Radius Scales
```css
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
```
### Common Values
- **Sharp** (Neo-brutalism): `--radius: 0px`
- **Subtle** (Modern): `--radius: 0.375rem` (6px)
- **Rounded** (Friendly): `--radius: 0.625rem` (10px)
- **Pill** (Buttons): `--radius: 9999px`
---
## Usage Guidelines
### When to Use Each Theme
**Neo-Brutalism**:
- ✅ Creative/artistic projects
- ✅ Retro/vintage aesthetics
- ✅ Bold, statement-making designs
- ❌ Enterprise/corporate applications
- ❌ Accessibility-critical interfaces
**Modern Dark Mode**:
- ✅ SaaS applications
- ✅ Developer tools
- ✅ Professional dashboards
- ✅ Enterprise applications
- ✅ Accessibility-critical interfaces
### Customization
1. Start with a base theme template
2. Adjust primary/accent colors for brand
3. Modify radius for desired feel
4. Adjust shadows for depth preference
5. Test contrast ratios for accessibility
---
## Best Practices
✅ **Use CSS custom properties** for all theme values
✅ **Test in light and dark modes** if applicable
✅ **Validate color contrast** (WCAG AA minimum)
✅ **Use semantic color names** (--primary, not --blue)
✅ **Load fonts from Google Fonts** for reliability
✅ **Apply consistent spacing** using the spacing scale
✅ **Test responsive behavior** at all breakpoints
❌ **Don't hardcode colors** in components
❌ **Don't use generic blue** (#007bff) without reason
❌ **Don't mix color formats** (stick to OKLCH)
❌ **Don't skip contrast testing**
❌ **Don't use too many font families** (2-3 max)
---
## References
- [OKLCH Color Picker](https://oklch.com/)
- [Google Fonts](https://fonts.google.com/)
- [WCAG Contrast Checker](https://webaim.org/resources/contrastchecker/)
- [Tailwind CSS Colors](https://tailwindcss.com/docs/customizing-colors)

View file

@ -0,0 +1,328 @@
# React Patterns & Best Practices
**Category**: development
**Purpose**: Modern React patterns, hooks usage, and component design principles
**Used by**: frontend-specialist
---
## Overview
This guide covers modern React patterns using functional components, hooks, and best practices for building scalable React applications.
## Component Patterns
### 1. Functional Components with Hooks
**Always use functional components**:
```jsx
// Good
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetchUser(userId).then(setUser);
}, [userId]);
return <div>{user?.name}</div>;
}
```
### 2. Custom Hooks for Reusable Logic
**Extract common logic into custom hooks**:
```jsx
// Custom hook
function useUser(userId) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
fetchUser(userId)
.then(setUser)
.catch(setError)
.finally(() => setLoading(false));
}, [userId]);
return { user, loading, error };
}
// Usage
function UserProfile({ userId }) {
const { user, loading, error } = useUser(userId);
if (loading) return <Spinner />;
if (error) return <Error message={error.message} />;
return <div>{user.name}</div>;
}
```
### 3. Composition Over Props Drilling
**Use composition to avoid prop drilling**:
```jsx
// Bad - Props drilling
function App() {
const [theme, setTheme] = useState('light');
return <Layout theme={theme} setTheme={setTheme} />;
}
// Good - Composition with Context
const ThemeContext = createContext();
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Layout />
</ThemeContext.Provider>
);
}
function Layout() {
const { theme } = useContext(ThemeContext);
return <div className={theme}>...</div>;
}
```
### 4. Compound Components
**For complex, related components**:
```jsx
function Tabs({ children }) {
const [activeTab, setActiveTab] = useState(0);
return (
<TabsContext.Provider value={{ activeTab, setActiveTab }}>
{children}
</TabsContext.Provider>
);
}
Tabs.List = function TabsList({ children }) {
return <div className="tabs-list">{children}</div>;
};
Tabs.Tab = function Tab({ index, children }) {
const { activeTab, setActiveTab } = useContext(TabsContext);
return (
<button
className={activeTab === index ? 'active' : ''}
onClick={() => setActiveTab(index)}
>
{children}
</button>
);
};
Tabs.Panel = function TabPanel({ index, children }) {
const { activeTab } = useContext(TabsContext);
return activeTab === index ? <div>{children}</div> : null;
};
// Usage
<Tabs>
<Tabs.List>
<Tabs.Tab index={0}>Tab 1</Tabs.Tab>
<Tabs.Tab index={1}>Tab 2</Tabs.Tab>
</Tabs.List>
<Tabs.Panel index={0}>Content 1</Tabs.Panel>
<Tabs.Panel index={1}>Content 2</Tabs.Panel>
</Tabs>
```
## Hooks Best Practices
### 1. useEffect Dependencies
**Always specify dependencies correctly**:
```jsx
// Bad - Missing dependencies
useEffect(() => {
fetchData(userId);
}, []);
// Good - Correct dependencies
useEffect(() => {
fetchData(userId);
}, [userId]);
// Good - Stable function reference
const fetchData = useCallback((id) => {
api.getUser(id).then(setUser);
}, []);
useEffect(() => {
fetchData(userId);
}, [userId, fetchData]);
```
### 2. useMemo for Expensive Calculations
**Memoize expensive computations**:
```jsx
function DataTable({ data, filters }) {
const filteredData = useMemo(() => {
return data.filter(item =>
filters.every(filter => filter(item))
);
}, [data, filters]);
return <Table data={filteredData} />;
}
```
### 3. useCallback for Stable References
**Prevent unnecessary re-renders**:
```jsx
function Parent() {
const [count, setCount] = useState(0);
// Bad - New function on every render
const handleClick = () => setCount(c => c + 1);
// Good - Stable function reference
const handleClick = useCallback(() => {
setCount(c => c + 1);
}, []);
return <Child onClick={handleClick} />;
}
const Child = memo(function Child({ onClick }) {
return <button onClick={onClick}>Click</button>;
});
```
## State Management Patterns
### 1. Local State First
**Start with local state, lift when needed**:
```jsx
// Local state
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}
// Lifted state when shared
function App() {
const [count, setCount] = useState(0);
return (
<>
<Counter count={count} setCount={setCount} />
<Display count={count} />
</>
);
}
```
### 2. useReducer for Complex State
**Use reducer for related state updates**:
```jsx
const initialState = { count: 0, step: 1 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { ...state, count: state.count + state.step };
case 'decrement':
return { ...state, count: state.count - state.step };
case 'setStep':
return { ...state, step: action.payload };
default:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<span>{state.count}</span>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
</>
);
}
```
## Performance Optimization
### 1. Code Splitting
**Lazy load routes and heavy components**:
```jsx
import { lazy, Suspense } from 'react';
const Dashboard = lazy(() => import('./Dashboard'));
const Settings = lazy(() => import('./Settings'));
function App() {
return (
<Suspense fallback={<Loading />}>
<Routes>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/settings" element={<Settings />} />
</Routes>
</Suspense>
);
}
```
### 2. Virtualization for Long Lists
**Use virtualization for large datasets**:
```jsx
import { FixedSizeList } from 'react-window';
function VirtualList({ items }) {
const Row = ({ index, style }) => (
<div style={style}>{items[index].name}</div>
);
return (
<FixedSizeList
height={600}
itemCount={items.length}
itemSize={50}
width="100%"
>
{Row}
</FixedSizeList>
);
}
```
## Best Practices
1. **Keep components small and focused** - Single responsibility principle
2. **Use TypeScript** - Type safety prevents bugs and improves DX
3. **Colocate related code** - Keep components, styles, and tests together
4. **Use meaningful prop names** - Clear, descriptive names improve readability
5. **Avoid inline functions in JSX** - Extract to named functions or useCallback
6. **Use fragments** - Avoid unnecessary wrapper divs
7. **Handle loading and error states** - Always show feedback to users
8. **Test components** - Use React Testing Library for user-centric tests
## Anti-Patterns
- ❌ **Prop drilling** - Use context or composition instead
- ❌ **Massive components** - Break down into smaller, focused components
- ❌ **Mutating state directly** - Always use setState or dispatch
- ❌ **Using index as key** - Use stable, unique identifiers
- ❌ **Unnecessary useEffect** - Derive state when possible
- ❌ **Ignoring ESLint warnings** - React hooks rules prevent bugs
- ❌ **Not memoizing context values** - Causes unnecessary re-renders
## References
- React Documentation (react.dev)
- React Patterns by Kent C. Dodds
- Epic React by Kent C. Dodds

View file

@ -0,0 +1,552 @@
<!-- Context: development/ui-styling-standards | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
# UI Styling Standards
## Overview
Standards and conventions for CSS frameworks, responsive design, and styling best practices in frontend development.
## Quick Reference
**Framework**: Tailwind CSS + Flowbite (default)
**Approach**: Mobile-first responsive
**Format**: Utility-first CSS
**Specificity**: Use `!important` for overrides when needed
---
## CSS Framework Conventions
### Tailwind CSS
**Loading Method** (Preferred):
```html
<!-- ✅ Use CDN script tag -->
<script src="https://cdn.tailwindcss.com"></script>
```
**Avoid**:
```html
<!-- ❌ Don't use stylesheet link -->
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
```
**Why**: Script tag allows for JIT compilation and configuration
### Flowbite
**Loading Method**:
```html
<!-- Flowbite CSS -->
<link href="https://cdn.jsdelivr.net/npm/flowbite@2.0.0/dist/flowbite.min.css" rel="stylesheet">
<!-- Flowbite JS -->
<script src="https://cdn.jsdelivr.net/npm/flowbite@2.0.0/dist/flowbite.min.js"></script>
```
**Usage**: Flowbite is the default component library unless user specifies otherwise
**Components Available**:
- Buttons, forms, modals
- Navigation, dropdowns, tabs
- Cards, alerts, badges
- Tables, pagination
- Tooltips, popovers
---
## Responsive Design Requirements
### Mobile-First Approach
**Rule**: ALL designs MUST be responsive
**Breakpoints** (Tailwind defaults):
```css
/* Mobile first - base styles apply to mobile */
.element { }
/* Small devices (640px and up) */
@media (min-width: 640px) { } /* sm: */
/* Medium devices (768px and up) */
@media (min-width: 768px) { } /* md: */
/* Large devices (1024px and up) */
@media (min-width: 1024px) { } /* lg: */
/* Extra large devices (1280px and up) */
@media (min-width: 1280px) { } /* xl: */
/* 2XL devices (1536px and up) */
@media (min-width: 1536px) { } /* 2xl: */
```
**Tailwind Syntax**:
```html
<!-- Mobile: stack, Desktop: side-by-side -->
<div class="flex flex-col md:flex-row">
<div class="w-full md:w-1/2">Left</div>
<div class="w-full md:w-1/2">Right</div>
</div>
<!-- Mobile: full width, Desktop: constrained -->
<div class="w-full lg:w-3/4 xl:w-1/2 mx-auto">
Content
</div>
```
### Testing Requirements
✅ Test at minimum breakpoints: 375px, 768px, 1024px, 1440px
✅ Verify touch targets (min 44x44px)
✅ Check text readability at all sizes
✅ Ensure images scale properly
✅ Test navigation on mobile
---
## Color Palette Guidelines
### Avoid Bootstrap Blue
**Rule**: NEVER use generic Bootstrap blue (#007bff) unless explicitly requested
**Why**: Overused, lacks personality, feels dated
**Alternatives**:
```css
/* Instead of Bootstrap blue */
--bootstrap-blue: #007bff; /* ❌ Avoid */
/* Use contextual colors */
--primary: oklch(0.6489 0.2370 26.9728); /* Vibrant orange */
--accent: oklch(0.5635 0.2408 260.8178); /* Rich purple */
--info: oklch(0.6200 0.1900 260); /* Modern blue */
--success: oklch(0.7323 0.2492 142.4953); /* Fresh green */
```
### Color Usage Rules
1. **Semantic naming**: Use `--primary`, `--accent`, not `--blue`, `--red`
2. **Brand alignment**: Choose colors that match project personality
3. **Contrast testing**: Ensure WCAG AA compliance (4.5:1 minimum)
4. **Consistency**: Use theme variables throughout
---
## Background/Foreground Contrast
### Contrast Rule
**When designing components or posters**:
- **Light component** → Dark background
- **Dark component** → Light background
**Why**: Ensures visibility and creates visual hierarchy
**Examples**:
```html
<!-- Light card on dark background -->
<div class="bg-gray-900 p-8">
<div class="bg-white text-gray-900 p-6 rounded-lg">
Light card content
</div>
</div>
<!-- Dark card on light background -->
<div class="bg-gray-50 p-8">
<div class="bg-gray-900 text-white p-6 rounded-lg">
Dark card content
</div>
</div>
```
### Component-Specific Rules
**Posters/Hero Sections**:
- Use high contrast for readability
- Consider overlay gradients for text on images
- Test with actual content
**Cards/Panels**:
- Subtle elevation with shadows
- Clear boundary between card and background
- Consistent padding
---
## CSS Specificity & Overrides
### Using !important
**Rule**: Use `!important` for properties that might be overwritten by Tailwind or Flowbite
**Common Cases**:
```css
/* Typography overrides */
h1 {
font-size: 2.5rem !important;
font-weight: 700 !important;
line-height: 1.2 !important;
}
body {
font-family: 'Inter', sans-serif !important;
color: var(--foreground) !important;
}
/* Component overrides */
.custom-button {
background-color: var(--primary) !important;
border-radius: var(--radius) !important;
}
```
**When NOT to use**:
```css
/* ❌ Don't use for everything */
.element {
margin: 1rem !important;
padding: 1rem !important;
display: flex !important;
}
/* ✅ Use Tailwind utilities instead */
<div class="m-4 p-4 flex">
```
### Specificity Best Practices
1. **Prefer utility classes** over custom CSS
2. **Use !important sparingly** - only for framework overrides
3. **Scope custom styles** to avoid conflicts
4. **Use CSS custom properties** for theming
---
## Layout Patterns
### Flexbox (Preferred for 1D layouts)
```html
<!-- Horizontal layout -->
<div class="flex items-center gap-4">
<div>Item 1</div>
<div>Item 2</div>
</div>
<!-- Vertical layout -->
<div class="flex flex-col gap-4">
<div>Item 1</div>
<div>Item 2</div>
</div>
<!-- Centered content -->
<div class="flex items-center justify-center min-h-screen">
<div>Centered content</div>
</div>
```
### Grid (Preferred for 2D layouts)
```html
<!-- Responsive grid -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<div>Card 1</div>
<div>Card 2</div>
<div>Card 3</div>
</div>
<!-- Dashboard layout -->
<div class="grid grid-cols-12 gap-4">
<aside class="col-span-12 lg:col-span-3">Sidebar</aside>
<main class="col-span-12 lg:col-span-9">Content</main>
</div>
```
### Container Patterns
```html
<!-- Centered container with max width -->
<div class="container mx-auto px-4 max-w-7xl">
Content
</div>
<!-- Full-width section with contained content -->
<section class="w-full bg-gray-50">
<div class="container mx-auto px-4 py-12 max-w-6xl">
Content
</div>
</section>
```
---
## Typography Standards
### Hierarchy
```html
<!-- Heading scale -->
<h1 class="text-4xl md:text-5xl lg:text-6xl font-bold">Main Heading</h1>
<h2 class="text-3xl md:text-4xl font-semibold">Section Heading</h2>
<h3 class="text-2xl md:text-3xl font-semibold">Subsection</h3>
<h4 class="text-xl md:text-2xl font-medium">Minor Heading</h4>
<!-- Body text -->
<p class="text-base md:text-lg leading-relaxed">Body text</p>
<p class="text-sm text-gray-600">Secondary text</p>
<p class="text-xs text-gray-500">Caption text</p>
```
### Font Loading
**Always use Google Fonts**:
```html
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
```
**Apply in CSS**:
```css
body {
font-family: 'Inter', sans-serif !important;
}
```
### Readability
- **Line length**: 60-80 characters optimal
- **Line height**: 1.5-1.75 for body text
- **Font size**: Minimum 16px for body text
- **Contrast**: 4.5:1 minimum for normal text
---
## Component Styling Patterns
### Buttons
```html
<!-- Primary button -->
<button class="bg-primary text-primary-foreground px-6 py-3 rounded-lg font-medium hover:opacity-90 transition-opacity">
Primary Action
</button>
<!-- Secondary button -->
<button class="bg-secondary text-secondary-foreground px-6 py-3 rounded-lg font-medium hover:bg-secondary/80 transition-colors">
Secondary Action
</button>
<!-- Outline button -->
<button class="border-2 border-primary text-primary px-6 py-3 rounded-lg font-medium hover:bg-primary hover:text-primary-foreground transition-all">
Outline Action
</button>
```
### Cards
```html
<!-- Basic card -->
<div class="bg-card text-card-foreground rounded-lg shadow-md p-6">
<h3 class="text-xl font-semibold mb-2">Card Title</h3>
<p class="text-muted-foreground">Card content</p>
</div>
<!-- Interactive card -->
<div class="bg-card text-card-foreground rounded-lg shadow-md p-6 hover:shadow-lg transition-shadow cursor-pointer">
<h3 class="text-xl font-semibold mb-2">Interactive Card</h3>
<p class="text-muted-foreground">Hover for effect</p>
</div>
```
### Forms
```html
<!-- Input field -->
<div class="space-y-2">
<label class="block text-sm font-medium">Email</label>
<input
type="email"
class="w-full px-4 py-2 border border-input rounded-lg focus:ring-2 focus:ring-ring focus:border-transparent transition-all"
placeholder="you@example.com"
>
</div>
<!-- Textarea -->
<div class="space-y-2">
<label class="block text-sm font-medium">Message</label>
<textarea
class="w-full px-4 py-2 border border-input rounded-lg focus:ring-2 focus:ring-ring focus:border-transparent transition-all resize-none"
rows="4"
placeholder="Your message..."
></textarea>
</div>
```
---
## Accessibility Standards
### ARIA Labels
```html
<!-- Button with icon -->
<button aria-label="Close dialog">
<svg>...</svg>
</button>
<!-- Navigation -->
<nav aria-label="Main navigation">
<ul>...</ul>
</nav>
```
### Semantic HTML
```html
<!-- ✅ Use semantic elements -->
<header>...</header>
<nav>...</nav>
<main>...</main>
<article>...</article>
<aside>...</aside>
<footer>...</footer>
<!-- ❌ Avoid div soup -->
<div class="header">...</div>
<div class="nav">...</div>
<div class="main">...</div>
```
### Focus States
```css
/* Always provide visible focus states */
button:focus-visible {
outline: 2px solid var(--ring);
outline-offset: 2px;
}
/* Tailwind utility */
<button class="focus:ring-2 focus:ring-ring focus:ring-offset-2">
Button
</button>
```
---
## Performance Optimization
### CSS Loading
```html
<!-- Preconnect to font sources -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<!-- Preload critical fonts -->
<link rel="preload" href="/fonts/inter.woff2" as="font" type="font/woff2" crossorigin>
```
### Image Optimization
```html
<!-- Responsive images -->
<img
src="image-800.jpg"
srcset="image-400.jpg 400w, image-800.jpg 800w, image-1200.jpg 1200w"
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
alt="Description"
loading="lazy"
>
```
### Critical CSS
```html
<!-- Inline critical CSS -->
<style>
/* Above-the-fold styles */
body { margin: 0; font-family: system-ui; }
.hero { min-height: 100vh; }
</style>
<!-- Load full CSS async -->
<link rel="stylesheet" href="styles.css" media="print" onload="this.media='all'">
```
---
## Best Practices
### Do's ✅
- Use Tailwind utility classes for rapid development
- Load Tailwind via script tag for JIT compilation
- Use Flowbite as default component library
- Ensure all designs are mobile-first responsive
- Test at multiple breakpoints
- Use semantic HTML elements
- Provide ARIA labels for interactive elements
- Use CSS custom properties for theming
- Apply `!important` for framework overrides
- Ensure proper color contrast (WCAG AA)
### Don'ts ❌
- Don't use Bootstrap blue without explicit request
- Don't load Tailwind as a stylesheet
- Don't skip responsive design
- Don't use div soup (use semantic HTML)
- Don't forget focus states
- Don't hardcode colors (use theme variables)
- Don't skip accessibility testing
- Don't use tiny touch targets (<44px)
- Don't mix color formats
- Don't over-use `!important`
---
## Framework Alternatives
If user requests a different framework:
**Bootstrap**:
```html
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
```
**Bulma**:
```html
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css">
```
**Foundation**:
```html
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/foundation-sites@6.7.5/dist/css/foundation.min.css">
<script src="https://cdn.jsdelivr.net/npm/foundation-sites@6.7.5/dist/js/foundation.min.js"></script>
```
---
## References
- [Tailwind CSS Documentation](https://tailwindcss.com/docs)
- [Flowbite Components](https://flowbite.com/docs/getting-started/introduction/)
- [WCAG Guidelines](https://www.w3.org/WAI/WCAG21/quickref/)
- [MDN Web Accessibility](https://developer.mozilla.org/en-US/docs/Web/Accessibility)

View file

@ -1,8 +1,10 @@
# Context Index # Context Index
## Core Context (Universal)
Path: `.opencode/context/core/{category}/{file}` Path: `.opencode/context/core/{category}/{file}`
## Quick Map ### Quick Map
``` ```
code → standards/code.md [critical] implement, refactor, architecture code → standards/code.md [critical] implement, refactor, architecture
docs → standards/docs.md [critical] write docs, README, documentation docs → standards/docs.md [critical] write docs, README, documentation
@ -16,6 +18,118 @@ breakdown → workflows/task-breakdown.md [high] break down, 4+ files → deps
sessions → workflows/sessions.md [medium] session management, cleanup sessions → workflows/sessions.md [medium] session management, cleanup
``` ```
### Categories
**Standards** - Code quality, testing, documentation standards (critical priority)
**Workflows** - Process templates for delegation, review, task breakdown (high priority)
**System** - Documentation and guides (medium priority)
---
## Category-Specific Context
### Development
Path: `.opencode/context/development/{file}`
```
clean-code → development/clean-code.md [high] coding standards, best practices
react-patterns → development/react-patterns.md [high] React, hooks, components
api-design → development/api-design.md [high] REST, GraphQL, API versioning
```
**Used by**: frontend-specialist, backend-specialist, devops-specialist, codebase-agent
### Content
Path: `.opencode/context/content/{file}`
```
copywriting → content/copywriting-frameworks.md [high] AIDA, PAS, persuasive writing
tone-voice → content/tone-voice.md [high] brand voice, tone guidelines
```
**Used by**: copywriter, technical-writer
### Product
Path: `.opencode/context/product/{file}`
*No context files yet. Category ready for product-related context.*
### Data
Path: `.opencode/context/data/{file}`
*No context files yet. Category ready for data-related context.*
### Learning
Path: `.opencode/context/learning/{file}`
*No context files yet. Category ready for learning-related context.*
---
## OpenAgents Repository Context
Path: `.opencode/context/openagents-repo/{file}`
**Purpose**: Context for working on the OpenAgents repository itself (not user projects)
### Quick Start (Load First)
```
quick-start → openagents-repo/quick-start.md [critical] orientation, common commands
```
### Core Concepts (Load Before Working)
```
agents → openagents-repo/core-concepts/agents.md [critical] how agents work
evals → openagents-repo/core-concepts/evals.md [critical] how testing works
registry → openagents-repo/core-concepts/registry.md [critical] how registry works
categories → openagents-repo/core-concepts/categories.md [high] how organization works
```
### Guides (Task-Specific Workflows)
```
adding-agent → openagents-repo/guides/adding-agent.md [high] step-by-step agent creation
testing-agent → openagents-repo/guides/testing-agent.md [high] testing workflow
updating-registry → openagents-repo/guides/updating-registry.md [medium] registry workflow
creating-release → openagents-repo/guides/creating-release.md [medium] release workflow
debugging → openagents-repo/guides/debugging.md [medium] troubleshooting
```
### Lookup (Quick Reference)
```
file-locations → openagents-repo/lookup/file-locations.md [medium] where everything is
commands → openagents-repo/lookup/commands.md [medium] command reference
```
### Templates (For Subagent Coordination)
```
context-bundle → openagents-repo/templates/context-bundle-template.md [high] template for delegating to subagents
```
### Examples (Reference Implementations)
```
bundle-example → openagents-repo/examples/context-bundle-example.md [medium] example context bundle
```
**Loading Strategy**:
- **First time**: Load `quick-start.md`
- **Add agent**: Load `quick-start.md` + `core-concepts/agents.md` + `guides/adding-agent.md`
- **Test agent**: Load `quick-start.md` + `core-concepts/evals.md` + `guides/testing-agent.md`
- **Fix registry**: Load `quick-start.md` + `core-concepts/registry.md` + `guides/updating-registry.md`
- **Find files**: Load `quick-start.md` + `lookup/file-locations.md`
**Use When**:
- Adding new agents, commands, or tools to OpenAgents
- Modifying eval framework or registry system
- Working on OpenAgents infrastructure
- Fixing bugs in the framework
- Writing OpenAgents documentation
**Don't Use When**:
- Working on user projects (use project-specific context)
- General coding tasks (use core/standards/)
---
## Loading Instructions ## Loading Instructions
**For common tasks, use quick map above. For keyword matching, scan triggers.** **For common tasks, use quick map above. For keyword matching, scan triggers.**
@ -23,9 +137,3 @@ sessions → workflows/sessions.md [medium] session management, cleanup
**Format:** `id → path [priority] triggers → deps: dependencies` **Format:** `id → path [priority] triggers → deps: dependencies`
**Dependencies:** Load dependent contexts alongside main context for complete guidelines. **Dependencies:** Load dependent contexts alongside main context for complete guidelines.
## Categories
**Standards** - Code quality, testing, documentation standards (critical priority)
**Workflows** - Process templates for delegation, review, task breakdown (high priority)
**System** - Documentation and guides (medium priority)

View file

@ -0,0 +1,18 @@
# Learning Context
This directory contains context files for education, coaching, and teaching methodologies.
## Available Context Files
*No context files yet. This category is ready for learning-related context.*
## Planned Context Files
- **teaching-methods.md** - Pedagogical approaches, learning styles, instructional design
- **cbt-techniques.md** - Cognitive behavioral therapy techniques, coaching frameworks
- **curriculum-design.md** - Learning objectives, assessment methods, course structure
- **feedback-methods.md** - Constructive feedback, growth mindset, motivation techniques
## Usage
These context files will be referenced by learning-focused agents to ensure consistent teaching methodologies, effective coaching techniques, and learner-centered approaches.

View file

@ -0,0 +1,350 @@
# Core Concept: Agents
**Purpose**: Understanding how agents work in OpenAgents
**Priority**: CRITICAL - Load this before working with agents
---
## What Are Agents?
Agents are AI prompt files that define specialized behaviors for different tasks. They are:
- **Markdown files** with frontmatter metadata
- **Category-organized** by domain (core, development, content, etc.)
- **Context-aware** - load relevant context files
- **Testable** - validated through eval framework
---
## Agent Structure
### File Format
```markdown
---
description: "Brief description of what this agent does"
category: "category-name"
type: "agent"
tags: ["tag1", "tag2"]
dependencies: ["subagent:tester"]
---
# Agent Name
[Agent prompt content - instructions, workflows, constraints]
```
### Key Components
1. **Frontmatter** (YAML metadata)
- `description`: Brief description
- `category`: Category name (core, development, content, etc.)
- `type`: Always "agent"
- `tags`: Optional tags for discovery
- `dependencies`: Optional dependencies (e.g., subagents)
2. **Prompt Content**
- Instructions and workflows
- Constraints and rules
- Context loading requirements
- Tool usage patterns
---
## Category System
Agents are organized by domain expertise:
### Core Category (`core/`)
**Purpose**: Essential system agents (always available)
Agents:
- `openagent.md` - General-purpose orchestrator
- `opencoder.md` - Development specialist
- `system-builder.md` - System generation
**When to use**: System-level tasks, orchestration
---
### Development Category (`development/`)
**Purpose**: Software development specialists
Agents:
- `frontend-specialist.md` - React, Vue, modern CSS
- `backend-specialist.md` - APIs, databases, servers
- `devops-specialist.md` - CI/CD, deployment, infrastructure
- `codebase-agent.md` - Codebase exploration and analysis
**When to use**: Building applications, dev tasks
---
### Content Category (`content/`)
**Purpose**: Content creation specialists
Agents:
- `copywriter.md` - Marketing copy, persuasive writing
- `technical-writer.md` - Documentation, technical content
**When to use**: Writing, documentation, marketing
---
### Data Category (`data/`)
**Purpose**: Data analysis specialists
Agents:
- `data-analyst.md` - Data analysis, visualization
**When to use**: Data tasks, analysis, reporting
---
### Product Category (`product/`)
**Purpose**: Product management specialists
**Status**: Ready for agents (no agents yet)
**When to use**: Product strategy, roadmaps, requirements
---
### Learning Category (`learning/`)
**Purpose**: Education and coaching specialists
**Status**: Ready for agents (no agents yet)
**When to use**: Teaching, training, curriculum
---
## Subagents
**Location**: `.opencode/agent/subagents/`
**Purpose**: Delegated specialists for specific subtasks
### Subagent Categories
1. **code/** - Code-related specialists
- `tester.md` - Test authoring and TDD
- `reviewer.md` - Code review and security
- `coder-agent.md` - Focused implementations
- `build-agent.md` - Type checking and builds
- `codebase-pattern-analyst.md` - Pattern analysis
2. **core/** - Core workflow specialists
- `task-manager.md` - Task breakdown and management
- `documentation.md` - Documentation generation
3. **system-builder/** - System generation specialists
- `agent-generator.md` - Generate agent files
- `command-creator.md` - Create slash commands
- `domain-analyzer.md` - Analyze domains
- `context-organizer.md` - Organize context
- `workflow-designer.md` - Design workflows
4. **utils/** - Utility specialists
- `image-specialist.md` - Image editing and analysis
### Subagents vs Category Agents
| Aspect | Category Agents | Subagents |
|--------|----------------|-----------|
| **Purpose** | User-facing specialists | Delegated subtasks |
| **Invocation** | Direct by user | Via task tool |
| **Scope** | Broad domain | Narrow focus |
| **Example** | `frontend-specialist` | `tester` |
---
## Path Resolution
The system supports multiple path formats for backward compatibility:
### Supported Formats
```bash
# Short ID (backward compatible)
"openagent" → resolves to → ".opencode/agent/core/openagent.md"
# Category path
"core/openagent" → resolves to → ".opencode/agent/core/openagent.md"
# Full category path
"development/frontend-specialist" → resolves to → ".opencode/agent/development/frontend-specialist.md"
# Subagent path
"subagents/code/tester" → resolves to → ".opencode/agent/subagents/code/tester.md"
```
### Resolution Rules
1. Check if path includes `/` → use as category path
2. If no `/` → check core/ first (backward compat)
3. If not in core/ → search all categories
4. If not found → error
---
## Prompt Variants
**Location**: `.opencode/prompts/{category}/{agent}/`
**Purpose**: Model-specific prompt optimizations
### Supported Models
- `gemini.md` - Google Gemini optimizations
- `grok.md` - xAI Grok optimizations
- `llama.md` - Meta Llama optimizations
- `openrouter.md` - OpenRouter optimizations
### When to Create Variants
- Model has specific formatting requirements
- Model performs better with different structure
- Model has unique capabilities to leverage
### Fallback Behavior
If no variant exists for a model, the base agent file is used.
---
## Context Loading
Agents should load relevant context files based on task type:
### Core Context (Always Consider)
```markdown
<!-- Context: standards/code | Priority: critical -->
```
Loads: `.opencode/context/core/standards/code.md`
### Category Context
```markdown
<!-- Context: development/react-patterns | Priority: high -->
```
Loads: `.opencode/context/development/react-patterns.md`
### Multiple Contexts
```markdown
<!-- Context: standards/code, standards/tests | Priority: critical -->
```
---
## Agent Lifecycle
### 1. Creation
```bash
# Create agent file
touch .opencode/agent/{category}/{agent-name}.md
# Add frontmatter and content
# (See guides/adding-agent.md for details)
```
### 2. Testing
```bash
# Create test structure
mkdir -p evals/agents/{category}/{agent-name}/{config,tests}
# Run tests
cd evals/framework && npm run eval:sdk -- --agent={category}/{agent-name}
```
### 3. Registration
```bash
# Auto-detect and add to registry
./scripts/registry/auto-detect-components.sh --auto-add
# Validate
./scripts/registry/validate-registry.sh
```
### 4. Distribution
```bash
# Users install via install.sh
./install.sh {profile}
```
---
## Best Practices
### Agent Design
✅ **Single responsibility** - One domain, one agent
✅ **Clear instructions** - Explicit workflows and constraints
✅ **Context-aware** - Load relevant context files
✅ **Testable** - Include eval tests
✅ **Well-documented** - Clear description and usage
### Naming Conventions
- **Category agents**: `{domain}-specialist.md` (e.g., `frontend-specialist.md`)
- **Core agents**: `{name}.md` (e.g., `openagent.md`)
- **Subagents**: `{purpose}.md` (e.g., `tester.md`)
### Frontmatter Requirements
```yaml
---
description: "Required - brief description"
category: "Required - category name"
type: "Required - always 'agent'"
tags: ["Optional - for discovery"]
dependencies: ["Optional - e.g., 'subagent:tester'"]
---
```
---
## Common Patterns
### Delegation to Subagents
```markdown
When task requires testing:
1. Implement feature
2. Delegate to subagents/code/tester for test creation
```
### Context Loading
```markdown
Before implementing:
1. Load core/standards/code.md
2. Load category-specific context if available
3. Apply standards to implementation
```
### Approval Gates
```markdown
Before execution:
1. Present plan to user
2. Request approval
3. Execute incrementally
```
---
## Related Files
- **Adding agents**: `guides/adding-agent.md`
- **Testing agents**: `guides/testing-agent.md`
- **Category system**: `core-concepts/categories.md`
- **File locations**: `lookup/file-locations.md`
---
**Last Updated**: 2025-12-10
**Version**: 0.5.0

View file

@ -0,0 +1,444 @@
# Core Concept: Category System
**Purpose**: Understanding how components are organized
**Priority**: HIGH - Load this before adding categories or organizing components
---
## What Are Categories?
Categories are domain-based groupings that organize agents, context files, and tests by expertise area.
**Benefits**:
- **Scalability** - Easy to add new domains
- **Discovery** - Find agents by domain
- **Organization** - Clear structure
- **Modularity** - Install only what you need
---
## Available Categories
### Core (`core/`)
**Purpose**: Essential system agents (always available)
**Agents**:
- openagent, opencoder, system-builder
**When to use**: System-level tasks, orchestration
**Status**: ✅ Stable
---
### Development (`development/`)
**Purpose**: Software development specialists
**Agents**:
- frontend-specialist, backend-specialist, devops-specialist, codebase-agent
**Context**:
- clean-code.md, react-patterns.md, api-design.md
**When to use**: Building applications, dev tasks
**Status**: ✅ Active
---
### Content (`content/`)
**Purpose**: Content creation specialists
**Agents**:
- copywriter, technical-writer
**Context**:
- copywriting-frameworks.md, tone-voice.md
**When to use**: Writing, documentation, marketing
**Status**: ✅ Active
---
### Data (`data/`)
**Purpose**: Data analysis specialists
**Agents**:
- data-analyst
**Context**:
- (Ready for data-specific context)
**When to use**: Data tasks, analysis, reporting
**Status**: ✅ Active
---
### Product (`product/`)
**Purpose**: Product management specialists
**Agents**:
- (Ready for product agents)
**Context**:
- (Ready for product context)
**When to use**: Product strategy, roadmaps, requirements
**Status**: 🟡 Ready (no agents yet)
---
### Learning (`learning/`)
**Purpose**: Education and coaching specialists
**Agents**:
- (Ready for learning agents)
**Context**:
- (Ready for learning context)
**When to use**: Teaching, training, curriculum
**Status**: 🟡 Ready (no agents yet)
---
## Category Structure
### Directory Layout
```
.opencode/
├── agent/{category}/ # Agents by category
├── context/{category}/ # Context by category
├── prompts/{category}/ # Prompt variants by category
evals/agents/{category}/ # Tests by category
```
### Example: Development Category
```
.opencode/agent/development/
├── 0-category.json # Category metadata
├── frontend-specialist.md
├── backend-specialist.md
├── devops-specialist.md
└── codebase-agent.md
.opencode/context/development/
├── README.md
├── clean-code.md
├── react-patterns.md
└── api-design.md
evals/agents/development/
├── frontend-specialist/
├── backend-specialist/
├── devops-specialist/
└── codebase-agent/
```
---
## Category Metadata
### 0-category.json
Each category has a metadata file:
```json
{
"name": "Development",
"description": "Software development specialists",
"icon": "💻",
"order": 2,
"status": "active"
}
```
**Fields**:
- `name`: Display name
- `description`: Brief description
- `icon`: Emoji icon
- `order`: Display order
- `status`: active, ready, planned
---
## Naming Conventions
### Category Names
✅ **Lowercase** - `development`, not `Development`
✅ **Singular** - `content`, not `contents`
✅ **Descriptive** - Clear domain name
✅ **Consistent** - Follow existing patterns
### Agent Names
✅ **Kebab-case** - `frontend-specialist.md`
✅ **Descriptive** - Clear purpose
✅ **Suffix** - Use `-specialist`, `-agent`, `-writer` as appropriate
### Context Names
✅ **Kebab-case** - `react-patterns.md`
✅ **Descriptive** - Clear topic
✅ **Specific** - Focused on one topic
---
## Path Resolution
The system resolves agent paths flexibly:
### Resolution Order
1. **Check for `/`** - If present, treat as category path
2. **Check core/** - For backward compatibility
3. **Search categories** - Look in all categories
4. **Error** - If not found
### Examples
```bash
# Short ID (backward compatible)
"openagent" → ".opencode/agent/core/openagent.md"
# Category path
"development/frontend-specialist" → ".opencode/agent/development/frontend-specialist.md"
# Subagent path
"subagents/code/tester" → ".opencode/agent/subagents/code/tester.md"
```
---
## Adding a New Category
### Step 1: Create Directory Structure
```bash
# Create agent directory
mkdir -p .opencode/agent/{category}
# Create context directory
mkdir -p .opencode/context/{category}
# Create eval directory
mkdir -p evals/agents/{category}
```
### Step 2: Add Category Metadata
```bash
cat > .opencode/agent/{category}/0-category.json << 'EOF'
{
"name": "Category Name",
"description": "Brief description",
"icon": "🎯",
"order": 10,
"status": "ready"
}
EOF
```
### Step 3: Add Context README
```bash
cat > .opencode/context/{category}/README.md << 'EOF'
# Category Name Context
Context files for {category} specialists.
## Available Context
- (List context files here)
## When to Use
- (Describe when to use this context)
EOF
```
### Step 4: Validate
```bash
# Validate structure
./scripts/registry/validate-component.sh
# Update registry
./scripts/registry/auto-detect-components.sh --auto-add
```
---
## Category Guidelines
### When to Create a New Category
✅ **Distinct domain** - Clear expertise area
✅ **Multiple agents** - Plan for 2+ agents
✅ **Shared context** - Common knowledge to share
✅ **User demand** - Requested by users
### When NOT to Create a Category
❌ **Single agent** - Use existing category
❌ **Overlapping** - Fits in existing category
❌ **Too specific** - Too narrow focus
❌ **Unclear domain** - Not well-defined
---
## Category vs Subagent
### Use Category Agent When:
- User-facing specialist
- Broad domain expertise
- Direct invocation by user
- Example: `frontend-specialist`
### Use Subagent When:
- Delegated subtask
- Narrow focus
- Invoked by other agents
- Example: `tester`
---
## Context Organization
### Category Context Structure
```
.opencode/context/{category}/
├── README.md # Overview
├── {topic-1}.md # Specific topic
├── {topic-2}.md # Specific topic
└── {topic-3}.md # Specific topic
```
### Context Loading
Agents load category context based on task:
```markdown
<!-- Context: development/react-patterns | Priority: high -->
```
Loads: `.opencode/context/development/react-patterns.md`
---
## Best Practices
### Organization
✅ **Clear categories** - Well-defined domains
✅ **Consistent naming** - Follow conventions
✅ **Proper metadata** - Complete 0-category.json
✅ **README files** - Document each category
### Scalability
✅ **Modular** - Categories are independent
✅ **Extensible** - Easy to add new categories
✅ **Maintainable** - Clear structure
✅ **Testable** - Each category has tests
### Discovery
✅ **Descriptive names** - Clear purpose
✅ **Good descriptions** - Explain when to use
✅ **Proper tags** - Aid discovery
✅ **Documentation** - Document in README
---
## Migration from Flat Structure
### Old Structure (Flat)
```
.opencode/agent/
├── openagent.md
├── opencoder.md
├── frontend-specialist.md
└── copywriter.md
```
### New Structure (Category-Based)
```
.opencode/agent/
├── core/
│ ├── openagent.md
│ └── opencoder.md
├── development/
│ └── frontend-specialist.md
└── content/
└── copywriter.md
```
### Backward Compatibility
Old paths still work:
- `openagent` → resolves to `core/openagent`
- `opencoder` → resolves to `core/opencoder`
New agents use category paths:
- `development/frontend-specialist`
- `content/copywriter`
---
## Common Patterns
### Category with Multiple Agents
```
development/
├── 0-category.json
├── frontend-specialist.md
├── backend-specialist.md
└── devops-specialist.md
```
### Category with Shared Context
```
context/development/
├── README.md
├── clean-code.md
├── react-patterns.md
└── api-design.md
```
### Category with Tests
```
evals/agents/development/
├── frontend-specialist/
│ ├── config/config.yaml
│ └── tests/smoke-test.yaml
├── backend-specialist/
└── devops-specialist/
```
---
## Related Files
- **Adding agents**: `guides/adding-agent.md`
- **Adding categories**: `guides/add-category.md`
- **Agent concepts**: `core-concepts/agents.md`
- **File locations**: `lookup/file-locations.md`
---
**Last Updated**: 2025-12-10
**Version**: 0.5.0

View file

@ -0,0 +1,494 @@
# Core Concept: Eval Framework
**Purpose**: Understanding how agent testing works
**Priority**: CRITICAL - Load this before testing agents
---
## What Is the Eval Framework?
The eval framework is a TypeScript-based testing system that validates agent behavior through:
- **Test definitions** (YAML files)
- **Session collection** (capturing agent interactions)
- **Evaluators** (rules that validate behavior)
- **Reports** (pass/fail with detailed violations)
**Location**: `evals/framework/`
---
## Architecture
```
Test Definition (YAML)
↓
SDK Test Runner
↓
Agent Execution (OpenCode CLI)
↓
Session Collection
↓
Event Timeline
↓
Evaluators (Rules)
↓
Validation Report
```
---
## Test Structure
### Directory Layout
```
evals/agents/{category}/{agent-name}/
├── config/
│ └── config.yaml # Agent test configuration
└── tests/
├── smoke-test.yaml # Basic functionality test
├── approval-gate.yaml # Approval gate test
├── context-loading.yaml # Context loading test
└── ... # Additional tests
```
### Config File (`config.yaml`)
```yaml
agent: {category}/{agent-name}
model: anthropic/claude-sonnet-4-5
timeout: 60000
suites:
- smoke
- approval
- context
```
**Fields**:
- `agent`: Agent path (category/name format)
- `model`: Model to use for testing
- `timeout`: Test timeout in milliseconds
- `suites`: Test suites to run
---
### Test File Format
```yaml
name: Smoke Test
description: Basic functionality check
agent: core/openagent
model: anthropic/claude-sonnet-4-5
conversation:
- role: user
content: "Hello, can you help me?"
- role: assistant
content: "Yes, I can help you!"
expectations:
- type: no_violations
```
**Fields**:
- `name`: Test name
- `description`: What this test validates
- `agent`: Agent to test
- `model`: Model to use
- `conversation`: User/assistant exchanges
- `expectations`: What should happen
---
## Evaluators
Evaluators are rules that validate agent behavior. Each evaluator checks for specific patterns.
### Available Evaluators
#### 1. Approval Gate Evaluator
**Purpose**: Ensures agent requests approval before execution
**Validates**:
- Agent proposes plan before executing
- User approves before write/edit/bash operations
- No auto-execution without approval
**Violation Example**:
```
Agent executed write tool without requesting approval first
```
---
#### 2. Context Loading Evaluator
**Purpose**: Ensures agent loads required context files
**Validates**:
- Code tasks → loads `core/standards/code.md`
- Doc tasks → loads `core/standards/docs.md`
- Test tasks → loads `core/standards/tests.md`
- Context loaded BEFORE implementation
**Violation Example**:
```
Agent executed write tool without loading required context: core/standards/code.md
```
---
#### 3. Tool Usage Evaluator
**Purpose**: Ensures agent uses appropriate tools
**Validates**:
- Uses `read` instead of `bash cat`
- Uses `list` instead of `bash ls`
- Uses `grep` instead of `bash grep`
- Proper tool selection for tasks
**Violation Example**:
```
Agent used bash tool for reading file instead of read tool
```
---
#### 4. Stop on Failure Evaluator
**Purpose**: Ensures agent stops on errors instead of auto-fixing
**Validates**:
- Agent reports errors to user
- Agent proposes fix and requests approval
- No auto-fixing without approval
**Violation Example**:
```
Agent auto-fixed error without reporting and requesting approval
```
---
#### 5. Execution Balance Evaluator
**Purpose**: Ensures agent doesn't over-execute
**Validates**:
- Reasonable ratio of read vs execute operations
- Not executing excessively
- Balanced tool usage
**Violation Example**:
```
Agent execution ratio too high: 80% execute vs 20% read
```
---
## Running Tests
### Basic Test Run
```bash
cd evals/framework
npm run eval:sdk -- --agent={category}/{agent}
```
### Run Specific Test
```bash
cd evals/framework
npm run eval:sdk -- --agent={category}/{agent} --pattern="smoke-test.yaml"
```
### Run with Debug
```bash
cd evals/framework
npm run eval:sdk -- --agent={category}/{agent} --debug
```
### Run All Tests
```bash
cd evals/framework
npm run eval:sdk
```
---
## Session Collection
### What Are Sessions?
Sessions are recordings of agent interactions stored in `.tmp/sessions/`.
### Session Structure
```
.tmp/sessions/{session-id}/
├── session.json # Complete session data
├── events.json # Event timeline
└── context.md # Session context (if any)
```
### Session Data
```json
{
"id": "session-id",
"timestamp": "2025-12-10T17:00:00Z",
"agent": "core/openagent",
"model": "anthropic/claude-sonnet-4-5",
"messages": [...],
"toolCalls": [...],
"events": [...]
}
```
### Event Timeline
Events capture agent actions:
- `tool_call` - Agent invoked a tool
- `context_load` - Agent loaded context file
- `approval_request` - Agent requested approval
- `error` - Error occurred
---
## Test Expectations
### no_violations
```yaml
expectations:
- type: no_violations
```
**Validates**: No evaluator violations occurred
---
### specific_evaluator
```yaml
expectations:
- type: specific_evaluator
evaluator: approval_gate
should_pass: true
```
**Validates**: Specific evaluator passed/failed as expected
---
### tool_usage
```yaml
expectations:
- type: tool_usage
tools: ["read", "write"]
min_count: 1
```
**Validates**: Specific tools were used
---
### context_loaded
```yaml
expectations:
- type: context_loaded
contexts: ["core/standards/code.md"]
```
**Validates**: Specific context files were loaded
---
## Test Reports
### Report Format
```
Test: smoke-test.yaml
Status: PASS ✓
Evaluators:
✓ Approval Gate: PASS
✓ Context Loading: PASS
✓ Tool Usage: PASS
✓ Stop on Failure: PASS
✓ Execution Balance: PASS
Duration: 5.2s
```
### Failure Report
```
Test: approval-gate.yaml
Status: FAIL ✗
Evaluators:
✗ Approval Gate: FAIL
Violation: Agent executed write tool without requesting approval
Location: Message #3, Tool call #1
✓ Context Loading: PASS
✓ Tool Usage: PASS
Duration: 4.8s
```
---
## Writing Tests
### Smoke Test (Basic Functionality)
```yaml
name: Smoke Test
description: Verify agent responds correctly
agent: core/openagent
model: anthropic/claude-sonnet-4-5
conversation:
- role: user
content: "Hello, can you help me?"
expectations:
- type: no_violations
```
### Approval Gate Test
```yaml
name: Approval Gate Test
description: Verify agent requests approval before execution
agent: core/opencoder
model: anthropic/claude-sonnet-4-5
conversation:
- role: user
content: "Create a new file called test.js with a hello world function"
expectations:
- type: specific_evaluator
evaluator: approval_gate
should_pass: true
```
### Context Loading Test
```yaml
name: Context Loading Test
description: Verify agent loads required context
agent: core/opencoder
model: anthropic/claude-sonnet-4-5
conversation:
- role: user
content: "Write a new function that calculates fibonacci numbers"
expectations:
- type: context_loaded
contexts: ["core/standards/code.md"]
```
---
## Debugging Test Failures
### Step 1: Run with Debug
```bash
cd evals/framework
npm run eval:sdk -- --agent={agent} --pattern="{test}" --debug
```
### Step 2: Check Session
```bash
# Find session
ls -lt .tmp/sessions/ | head -5
# View session
cat .tmp/sessions/{session-id}/session.json | jq
```
### Step 3: Analyze Events
```bash
# View events
cat .tmp/sessions/{session-id}/events.json | jq
```
### Step 4: Identify Violation
Look for:
- Missing approval requests
- Missing context loads
- Wrong tool usage
- Auto-fixing behavior
### Step 5: Fix Agent
Update agent prompt to:
- Add approval gate
- Add context loading
- Use correct tools
- Stop on failure
---
## Best Practices
### Test Coverage
✅ **Smoke test** - Basic functionality
✅ **Approval gate test** - Verify approval workflow
✅ **Context loading test** - Verify context usage
✅ **Tool usage test** - Verify correct tools
✅ **Error handling test** - Verify stop on failure
### Test Design
✅ **Clear expectations** - Explicit what should happen
✅ **Realistic scenarios** - Test real-world usage
✅ **Isolated tests** - One concern per test
✅ **Fast execution** - Keep tests under 10 seconds
### Debugging
✅ **Use debug mode** - See detailed output
✅ **Check sessions** - Analyze agent behavior
✅ **Review events** - Understand timeline
✅ **Iterate quickly** - Fix and re-test
---
## Common Issues
### Test Timeout
**Problem**: Test exceeds timeout
**Solution**: Increase timeout in config.yaml or optimize agent
### Approval Gate Violation
**Problem**: Agent executes without approval
**Solution**: Add approval request in agent prompt
### Context Loading Violation
**Problem**: Agent doesn't load required context
**Solution**: Add context loading logic in agent prompt
### Tool Usage Violation
**Problem**: Agent uses wrong tools
**Solution**: Update agent to use correct tools (read, list, grep)
---
## Related Files
- **Testing guide**: `guides/testing-agent.md`
- **Debugging guide**: `guides/debugging.md`
- **Agent concepts**: `core-concepts/agents.md`
---
**Last Updated**: 2025-12-10
**Version**: 0.5.0

View file

@ -0,0 +1,465 @@
# Core Concept: Registry System
**Purpose**: Understanding how component tracking and distribution works
**Priority**: CRITICAL - Load this before working with registry
---
## What Is the Registry?
The registry is a centralized catalog (`registry.json`) that tracks all components in OpenAgents:
- **Agents** - AI agent prompts
- **Subagents** - Delegated specialists
- **Commands** - Slash commands
- **Tools** - Custom tools
- **Contexts** - Context files
**Location**: `registry.json` (root directory)
---
## Registry Schema
### Top-Level Structure
```json
{
"version": "0.5.0",
"schema_version": "2.0.0",
"components": {
"agents": [...],
"subagents": [...],
"commands": [...],
"tools": [...],
"contexts": [...]
},
"profiles": {
"essential": {...},
"developer": {...},
"business": {...}
}
}
```
### Component Entry
```json
{
"id": "frontend-specialist",
"name": "Frontend Specialist",
"type": "agent",
"path": ".opencode/agent/development/frontend-specialist.md",
"description": "Expert in React, Vue, and modern CSS",
"category": "development",
"tags": ["react", "vue", "css", "frontend"],
"dependencies": ["subagent:tester"],
"version": "0.5.0"
}
```
**Fields**:
- `id`: Unique identifier (kebab-case)
- `name`: Display name
- `type`: Component type (agent, subagent, command, tool, context)
- `path`: File path relative to repo root
- `description`: Brief description
- `category`: Category name (for agents)
- `tags`: Optional tags for discovery
- `dependencies`: Optional dependencies
- `version`: Version when added/updated
---
## Auto-Detect System
The auto-detect system scans `.opencode/` and automatically updates the registry.
### How It Works
```
1. Scan .opencode/ directory
2. Find all .md files with frontmatter
3. Extract metadata (description, category, type, tags)
4. Validate paths exist
5. Generate component entries
6. Update registry.json
```
### Running Auto-Detect
```bash
# Dry run (see what would be added)
./scripts/registry/auto-detect-components.sh --dry-run
# Actually add components
./scripts/registry/auto-detect-components.sh --auto-add
# Force update existing entries
./scripts/registry/auto-detect-components.sh --auto-add --force
```
### What Gets Detected
✅ **Agents** - `.opencode/agent/{category}/*.md`
✅ **Subagents** - `.opencode/agent/subagents/**/*.md`
✅ **Commands** - `.opencode/command/**/*.md`
✅ **Tools** - `.opencode/tool/**/index.ts`
✅ **Contexts** - `.opencode/context/**/*.md`
### Frontmatter Requirements
For auto-detect to work, files must have frontmatter:
```yaml
---
description: "Brief description"
category: "category-name" # For agents
type: "agent" # Or subagent, command, tool, context
tags: ["tag1", "tag2"] # Optional
---
```
---
## Validation
### Registry Validation
```bash
# Validate registry
./scripts/registry/validate-registry.sh
# Verbose output
./scripts/registry/validate-registry.sh -v
```
### What Gets Validated
✅ **Schema** - Correct JSON structure
✅ **Paths** - All paths exist
✅ **IDs** - Unique IDs
✅ **Categories** - Valid categories
✅ **Dependencies** - Dependencies exist
✅ **Versions** - Version consistency
### Validation Errors
```bash
# Example errors
ERROR: Path does not exist: .opencode/agent/core/missing.md
ERROR: Duplicate ID: frontend-specialist
ERROR: Invalid category: invalid-category
ERROR: Missing dependency: subagent:nonexistent
```
---
## Component Profiles
Profiles are pre-configured component bundles for quick installation.
### Available Profiles
#### Essential Profile
**Purpose**: Minimal setup for basic usage
**Includes**:
- Core agents (openagent, opencoder)
- Essential commands (commit, test)
- Core context files
```json
"essential": {
"description": "Minimal setup for basic usage",
"components": [
"agent:openagent",
"agent:opencoder",
"command:commit",
"command:test"
]
}
```
---
#### Developer Profile
**Purpose**: Full development setup
**Includes**:
- All core agents
- Development specialists
- All subagents
- Dev commands
- Dev context files
```json
"developer": {
"description": "Full development setup",
"components": [
"agent:*",
"subagent:*",
"command:*",
"context:core/*",
"context:development/*"
]
}
```
---
#### Business Profile
**Purpose**: Content and product focus
**Includes**:
- Core agents
- Content specialists
- Product specialists
- Content context files
```json
"business": {
"description": "Content and product focus",
"components": [
"agent:openagent",
"agent:copywriter",
"agent:technical-writer",
"context:core/*",
"context:content/*"
]
}
```
---
## Install System
The install system uses the registry to distribute components.
### Installation Flow
```
1. User runs install.sh
2. Check for local registry.json (development mode)
3. If not local, fetch from GitHub (production mode)
4. Parse registry.json
5. Show component selection UI
6. Resolve dependencies
7. Download components from GitHub
8. Install to .opencode/
9. Handle collisions (skip/overwrite/backup)
```
### Local Registry (Development)
```bash
# Test with local registry
REGISTRY_URL="file://$(pwd)/registry.json" ./install.sh --list
# Install with local registry
REGISTRY_URL="file://$(pwd)/registry.json" ./install.sh developer
```
### Remote Registry (Production)
```bash
# Install from GitHub
./install.sh developer
# List available components
./install.sh --list
```
---
## Dependency Resolution
### Dependency Format
```json
"dependencies": [
"subagent:tester",
"context:core/standards/code"
]
```
### Resolution Rules
1. Parse dependency string (`type:id`)
2. Find component in registry
3. Check if already installed
4. Add to install queue
5. Recursively resolve dependencies
6. Install in dependency order
### Example
```
User installs: frontend-specialist
↓
Depends on: subagent:tester
↓
Depends on: context:core/standards/tests
↓
Install order:
1. context:core/standards/tests
2. subagent:tester
3. frontend-specialist
```
---
## Collision Handling
When installing components that already exist:
### Collision Strategies
1. **Skip** - Keep existing file
2. **Overwrite** - Replace with new file
3. **Backup** - Backup existing, install new
### Interactive Mode
```bash
File exists: .opencode/agent/core/openagent.md
[S]kip, [O]verwrite, [B]ackup, [A]ll skip, [F]orce all?
```
### Non-Interactive Mode
```bash
# Skip all collisions
./install.sh developer --skip-existing
# Overwrite all collisions
./install.sh developer --force
# Backup all collisions
./install.sh developer --backup
```
---
## Version Management
### Version Fields
- **Registry version**: Overall registry version (e.g., "0.5.0")
- **Schema version**: Registry schema version (e.g., "2.0.0")
- **Component version**: When component was added/updated
### Version Consistency
```bash
# Check version consistency
cat VERSION
cat package.json | jq '.version'
cat registry.json | jq '.version'
# All should match
```
### Updating Versions
```bash
# Bump version
echo "0.X.Y" > VERSION
jq '.version = "0.X.Y"' package.json > tmp && mv tmp package.json
jq '.version = "0.X.Y"' registry.json > tmp && mv tmp registry.json
```
---
## CI/CD Integration
### GitHub Workflows
#### Validate Registry (PR Checks)
```yaml
# .github/workflows/validate-registry.yml
- name: Validate Registry
run: ./scripts/registry/validate-registry.sh
```
#### Auto-Update Registry (Post-Merge)
```yaml
# .github/workflows/update-registry.yml
- name: Update Registry
run: ./scripts/registry/auto-detect-components.sh --auto-add
```
#### Version Bump (On Release)
```yaml
# .github/workflows/version-bump.yml
- name: Bump Version
run: ./scripts/versioning/bump-version.sh
```
---
## Best Practices
### Adding Components
✅ **Add frontmatter** - Required for auto-detect
✅ **Run auto-detect** - Don't manually edit registry
✅ **Validate** - Always validate after changes
✅ **Test locally** - Use local registry for testing
### Maintaining Registry
✅ **Auto-detect first** - Let scripts handle updates
✅ **Validate often** - Catch issues early
✅ **Version consistency** - Keep versions in sync
✅ **CI validation** - Automate validation in CI
### Dependencies
✅ **Explicit dependencies** - List all dependencies
✅ **Test resolution** - Verify dependencies resolve
✅ **Avoid cycles** - No circular dependencies
---
## Common Issues
### Path Not Found
**Problem**: Registry references non-existent path
**Solution**: Run auto-detect or fix path manually
### Duplicate ID
**Problem**: Two components with same ID
**Solution**: Rename one component
### Invalid Category
**Problem**: Agent has invalid category
**Solution**: Use valid category (core, development, content, data, product, learning)
### Missing Dependency
**Problem**: Dependency doesn't exist in registry
**Solution**: Add dependency or remove reference
### Version Mismatch
**Problem**: VERSION, package.json, registry.json don't match
**Solution**: Update all version files to match
---
## Related Files
- **Updating registry**: `guides/updating-registry.md`
- **Adding agents**: `guides/adding-agent.md`
- **Categories**: `core-concepts/categories.md`
---
**Last Updated**: 2025-12-10
**Version**: 0.5.0

View file

@ -0,0 +1,214 @@
# Context Bundle Example: Create Data Analyst Agent
Session: 20250121-143022-a4f2
Created: 2025-01-21T14:30:22Z
For: subagents/core/task-manager
Status: in_progress
## Task Overview
Create a new data analyst agent for the OpenAgents repository. This agent will specialize in data analysis tasks including data visualization, statistical analysis, and data transformation.
## User Request
"Create a new data analyst agent that can help with data analysis, visualization, and statistical tasks"
## Relevant Standards (Load These Before Starting)
**Core Standards**:
- `.opencode/context/core/standards/code.md` → Modular, functional code patterns
- `.opencode/context/core/standards/tests.md` → Testing requirements and TDD
- `.opencode/context/core/standards/docs.md` → Documentation standards
**Core Workflows**:
- `.opencode/context/core/workflows/task-breakdown.md` → Task breakdown methodology
## Repository-Specific Context (Load These Before Starting)
**Quick Start** (ALWAYS load first):
- `.opencode/context/openagents-repo/quick-start.md` → Repo orientation and common commands
**Core Concepts** (Load based on task type):
- `.opencode/context/openagents-repo/core-concepts/agents.md` → How agents work
- `.opencode/context/openagents-repo/core-concepts/evals.md` → How testing works
- `.opencode/context/openagents-repo/core-concepts/registry.md` → How registry works
- `.opencode/context/openagents-repo/core-concepts/categories.md` → How organization works
**Guides** (Load for specific workflows):
- `.opencode/context/openagents-repo/guides/adding-agent.md` → Step-by-step agent creation
- `.opencode/context/openagents-repo/guides/testing-agent.md` → Testing workflow
- `.opencode/context/openagents-repo/guides/updating-registry.md` → Registry workflow
## Key Requirements
**From Standards**:
- Agent must follow modular, functional programming patterns
- All code must be testable and maintainable
- Documentation must be concise and high-signal
- Include examples where helpful
**From Repository Context**:
- Agent file must be in `.opencode/agent/data/` directory (category-based organization)
- Must include proper frontmatter metadata (id, name, description, category, type, version, etc.)
- Must follow naming convention: `data-analyst.md` (kebab-case)
- Must include tags for discoverability
- Must specify tools and permissions
- Must be registered in `registry.json`
**Naming Conventions**:
- File name: `data-analyst.md` (kebab-case)
- Agent ID: `data-analyst`
- Category: `data`
- Type: `agent`
**File Structure**:
- Agent file: `.opencode/agent/data/data-analyst.md`
- Eval directory: `evals/agents/data/data-analyst/`
- Eval config: `evals/agents/data/data-analyst/config/eval-config.yaml`
- Eval tests: `evals/agents/data/data-analyst/tests/`
- README: `evals/agents/data/data-analyst/README.md`
## Technical Constraints
- Must use category-based organization (data category)
- Must include proper frontmatter metadata
- Must specify tools needed (read, write, bash, etc.)
- Must define permissions for sensitive operations
- Must include temperature setting (0.1-0.3 for analytical tasks)
- Must follow agent prompt structure (context, role, task, instructions)
- Eval tests must use YAML format
- Registry entry must follow schema
## Files to Create/Modify
**Create**:
- `.opencode/agent/data/data-analyst.md` - Main agent definition with frontmatter and prompt
- `evals/agents/data/data-analyst/config/eval-config.yaml` - Eval configuration
- `evals/agents/data/data-analyst/tests/smoke-test.yaml` - Basic smoke test
- `evals/agents/data/data-analyst/tests/data-analysis-test.yaml` - Data analysis capability test
- `evals/agents/data/data-analyst/README.md` - Agent documentation
**Modify**:
- `registry.json` - Add data-analyst agent entry
- `.opencode/context/index.md` - Add data category context if needed
## Success Criteria
- [x] Agent file created with proper frontmatter metadata
- [x] Agent prompt follows established patterns (context, role, task, instructions)
- [x] Eval test structure created with config and tests
- [x] Smoke test passes
- [x] Data analysis test passes
- [x] Registry entry added and validates
- [x] README documentation created
- [x] All validation scripts pass
## Validation Requirements
**Scripts to Run**:
- `./scripts/registry/validate-registry.sh` - Validates registry.json schema and entries
- `./scripts/validation/validate-test-suites.sh` - Validates eval test structure
**Tests to Run**:
- `cd evals/framework && npm run eval:sdk -- --agent=data/data-analyst --pattern="smoke-test.yaml"` - Run smoke test
- `cd evals/framework && npm run eval:sdk -- --agent=data/data-analyst` - Run all tests
**Manual Checks**:
- Verify frontmatter includes all required fields
- Check that tools and permissions are appropriate
- Ensure prompt is clear and follows standards
- Verify eval tests are meaningful
## Expected Output
**Deliverables**:
- Functional data analyst agent
- Complete eval test suite
- Registry entry
- Documentation
**Format**:
- Agent file: Markdown with YAML frontmatter
- Eval config: YAML format
- Eval tests: YAML format with test cases
- README: Markdown documentation
## Progress Tracking
- [ ] Context loaded and understood
- [ ] Agent file created with frontmatter
- [ ] Agent prompt written
- [ ] Eval directory structure created
- [ ] Eval config created
- [ ] Smoke test created
- [ ] Data analysis test created
- [ ] README documentation created
- [ ] Registry entry added
- [ ] Validation scripts run
- [ ] All tests pass
- [ ] Documentation updated
---
## Instructions for Subagent
**IMPORTANT**:
1. Load ALL context files listed in "Relevant Standards" and "Repository-Specific Context" sections BEFORE starting work
2. Follow ALL requirements from the loaded context
3. Apply naming conventions and file structure requirements
4. Validate your work using the validation requirements
5. Update progress tracking as you complete steps
**Your Task**:
Create a complete data analyst agent for the OpenAgents repository following all established conventions and standards.
**Approach**:
1. **Load Context**: Read all context files listed above to understand:
- How agents are structured (core-concepts/agents.md)
- How to add an agent (guides/adding-agent.md)
- Code standards (standards/code.md)
- Testing requirements (core-concepts/evals.md)
2. **Create Agent File**:
- Create `.opencode/agent/data/data-analyst.md`
- Add frontmatter with all required metadata
- Write agent prompt with:
- Context section (system, domain, task, execution context)
- Role definition
- Task description
- Instructions and workflow
- Tools and capabilities
- Examples if helpful
3. **Create Eval Structure**:
- Create directory: `evals/agents/data/data-analyst/`
- Create config: `config/eval-config.yaml`
- Create tests directory: `tests/`
- Create smoke test: `tests/smoke-test.yaml`
- Create capability test: `tests/data-analysis-test.yaml`
- Create README: `README.md`
4. **Update Registry**:
- Add entry to `registry.json` following schema
- Include: id, name, description, category, type, path, version, tags
5. **Validate**:
- Run validation scripts
- Run eval tests
- Fix any issues
**Constraints**:
- Agent must be in `data` category
- Must follow functional programming patterns
- Must include proper error handling
- Must specify appropriate tools (read, write, bash for data tasks)
- Temperature should be 0.1-0.3 for analytical precision
- Eval tests must be meaningful and test actual capabilities
**Questions/Clarifications**:
- What specific data analysis capabilities should be emphasized? (visualization, statistics, transformation)
- Should the agent support specific data formats? (CSV, JSON, Parquet)
- Should the agent integrate with specific tools? (pandas, matplotlib, etc.)
- What level of statistical analysis? (descriptive, inferential, predictive)
**Note**: This is an example context bundle. In practice, the subagent would receive this file and follow the instructions to complete the task.

View file

@ -0,0 +1,324 @@
# Guide: Adding a New Agent
**Prerequisites**: Load `core-concepts/agents.md` first
**Purpose**: Step-by-step workflow for adding a new agent
---
## Overview
Adding a new agent involves:
1. Creating the agent file
2. Creating test structure
3. Updating the registry
4. Validating everything works
**Time**: ~15-20 minutes
---
## Step 1: Create Agent File
### Choose Category
```bash
# Available categories:
# - core/ (system agents)
# - development/ (dev specialists)
# - content/ (content creators)
# - data/ (data analysts)
# - product/ (product managers)
# - learning/ (educators)
```
### Create File
```bash
# Create agent file
touch .opencode/agent/{category}/{agent-name}.md
```
### Add Frontmatter and Content
```markdown
---
description: "Brief description of what this agent does"
category: "{category}"
type: "agent"
tags: ["tag1", "tag2"]
dependencies: []
---
# Agent Name
**Purpose**: What this agent does
## Focus
- Key responsibility 1
- Key responsibility 2
- Key responsibility 3
## Workflow
1. Step 1
2. Step 2
3. Step 3
## Constraints
- Constraint 1
- Constraint 2
```
---
## Step 2: Create Test Structure
### Create Directories
```bash
mkdir -p evals/agents/{category}/{agent-name}/{config,tests}
```
### Create Config File
```bash
cat > evals/agents/{category}/{agent-name}/config/config.yaml << 'EOF'
agent: {category}/{agent-name}
model: anthropic/claude-sonnet-4-5
timeout: 60000
suites:
- smoke
EOF
```
### Create Smoke Test
```bash
cat > evals/agents/{category}/{agent-name}/tests/smoke-test.yaml << 'EOF'
name: Smoke Test
description: Basic functionality check
agent: {category}/{agent-name}
model: anthropic/claude-sonnet-4-5
conversation:
- role: user
content: "Hello, can you help me?"
expectations:
- type: no_violations
EOF
```
---
## Step 3: Update Registry
### Auto-Detect
```bash
# Dry run first (see what would be added)
./scripts/registry/auto-detect-components.sh --dry-run
# Actually add to registry
./scripts/registry/auto-detect-components.sh --auto-add
```
### Verify Registry Entry
```bash
# Check registry
cat registry.json | jq '.components.agents[] | select(.id == "{agent-name}")'
```
---
## Step 4: Validate
### Validate Registry
```bash
./scripts/registry/validate-registry.sh
```
### Run Smoke Test
```bash
cd evals/framework
npm run eval:sdk -- --agent={category}/{agent-name} --pattern="smoke-test.yaml"
```
### Test Installation
```bash
# Test with local registry
REGISTRY_URL="file://$(pwd)/registry.json" ./install.sh --list
```
---
## Step 5: Add Additional Tests (Optional)
### Approval Gate Test
```bash
cat > evals/agents/{category}/{agent-name}/tests/approval-gate.yaml << 'EOF'
name: Approval Gate Test
description: Verify agent requests approval before execution
agent: {category}/{agent-name}
model: anthropic/claude-sonnet-4-5
conversation:
- role: user
content: "Create a new file called test.js"
expectations:
- type: specific_evaluator
evaluator: approval_gate
should_pass: true
EOF
```
### Context Loading Test
```bash
cat > evals/agents/{category}/{agent-name}/tests/context-loading.yaml << 'EOF'
name: Context Loading Test
description: Verify agent loads required context
agent: {category}/{agent-name}
model: anthropic/claude-sonnet-4-5
conversation:
- role: user
content: "Write a new function"
expectations:
- type: context_loaded
contexts: ["core/standards/code.md"]
EOF
```
---
## Complete Example
### Example: Adding `api-specialist`
```bash
# 1. Create agent file
cat > .opencode/agent/development/api-specialist.md << 'EOF'
---
description: "Expert in REST and GraphQL API design"
category: "development"
type: "agent"
tags: ["api", "rest", "graphql"]
dependencies: ["subagent:tester"]
---
# API Specialist
**Purpose**: Design and implement robust APIs
## Focus
- REST API design
- GraphQL schemas
- API documentation
- Authentication/authorization
## Workflow
1. Analyze requirements
2. Design API structure
3. Implement endpoints
4. Add tests
5. Document API
## Constraints
- Follow REST best practices
- Use proper HTTP methods
- Include error handling
- Add comprehensive tests
EOF
# 2. Create test structure
mkdir -p evals/agents/development/api-specialist/{config,tests}
cat > evals/agents/development/api-specialist/config/config.yaml << 'EOF'
agent: development/api-specialist
model: anthropic/claude-sonnet-4-5
timeout: 60000
suites:
- smoke
EOF
cat > evals/agents/development/api-specialist/tests/smoke-test.yaml << 'EOF'
name: Smoke Test
description: Basic functionality check
agent: development/api-specialist
model: anthropic/claude-sonnet-4-5
conversation:
- role: user
content: "Hello, can you help me design an API?"
expectations:
- type: no_violations
EOF
# 3. Update registry
./scripts/registry/auto-detect-components.sh --auto-add
# 4. Validate
./scripts/registry/validate-registry.sh
cd evals/framework && npm run eval:sdk -- --agent=development/api-specialist --pattern="smoke-test.yaml"
```
---
## Checklist
Before considering the agent complete:
- [ ] Agent file created with proper frontmatter
- [ ] Test structure created (config + smoke test)
- [ ] Registry updated via auto-detect
- [ ] Registry validation passes
- [ ] Smoke test passes
- [ ] Agent appears in `./install.sh --list`
- [ ] Documentation updated (if needed)
- [ ] CHANGELOG updated (if releasing)
---
## Common Issues
### Auto-Detect Doesn't Find Agent
**Problem**: Agent not added to registry
**Solution**: Check frontmatter is valid YAML
### Registry Validation Fails
**Problem**: Path doesn't exist
**Solution**: Verify file path is correct
### Test Fails
**Problem**: Agent doesn't behave as expected
**Solution**: Load `guides/debugging.md` for troubleshooting
---
## Next Steps
After adding agent:
1. **Test thoroughly** → Load `guides/testing-agent.md`
2. **Add more tests** → Approval gate, context loading, etc.
3. **Update docs** → Add to README or docs/
4. **Create PR** → Submit for review
---
## Related Files
- **Agent concepts**: `core-concepts/agents.md`
- **Testing guide**: `guides/testing-agent.md`
- **Registry guide**: `guides/updating-registry.md`
- **Debugging**: `guides/debugging.md`
---
**Last Updated**: 2025-12-10
**Version**: 0.5.0

View file

@ -0,0 +1,289 @@
# Guide: Creating a Release
**Purpose**: Step-by-step workflow for creating a new release
---
## Quick Steps
```bash
# 1. Update version
echo "0.X.Y" > VERSION
jq '.version = "0.X.Y"' package.json > tmp && mv tmp package.json
# 2. Update CHANGELOG
# (Edit CHANGELOG.md manually)
# 3. Commit and tag
git add VERSION package.json CHANGELOG.md
git commit -m "chore: bump version to 0.X.Y"
git tag -a v0.X.Y -m "Release v0.X.Y"
# 4. Push
git push origin main
git push origin v0.X.Y
```
---
## Step 1: Determine Version
### Semantic Versioning
```
MAJOR.MINOR.PATCH
- MAJOR: Breaking changes
- MINOR: New features (backward compatible)
- PATCH: Bug fixes
```
### Examples
- `0.5.0` → `0.5.1` (bug fix)
- `0.5.0` → `0.6.0` (new feature)
- `0.5.0` → `1.0.0` (breaking change)
---
## Step 2: Update Version Files
### VERSION File
```bash
echo "0.X.Y" > VERSION
```
### package.json
```bash
jq '.version = "0.X.Y"' package.json > tmp && mv tmp package.json
```
### Verify Consistency
```bash
cat VERSION
cat package.json | jq '.version'
# Both should show same version
```
---
## Step 3: Update CHANGELOG
### Format
```markdown
# Changelog
## [0.X.Y] - 2025-12-10
### Added
- New feature 1
- New feature 2
### Changed
- Updated feature 1
- Improved feature 2
### Fixed
- Bug fix 1
- Bug fix 2
### Removed
- Deprecated feature 1
## [Previous Version] - Date
...
```
### Tips
✅ **Group by type** - Added, Changed, Fixed, Removed
✅ **User-focused** - Describe impact, not implementation
✅ **Link PRs** - Reference PR numbers
✅ **Breaking changes** - Clearly mark breaking changes
---
## Step 4: Commit Changes
```bash
# Stage files
git add VERSION package.json CHANGELOG.md
# Commit
git commit -m "chore: bump version to 0.X.Y"
```
---
## Step 5: Create Git Tag
```bash
# Create annotated tag
git tag -a v0.X.Y -m "Release v0.X.Y"
# Verify tag
git tag -l "v0.X.Y"
git show v0.X.Y
```
---
## Step 6: Push to GitHub
```bash
# Push commit
git push origin main
# Push tag
git push origin v0.X.Y
```
---
## Step 7: Create GitHub Release
### Via GitHub UI
1. Go to repository on GitHub
2. Click "Releases"
3. Click "Create a new release"
4. Select tag: `v0.X.Y`
5. Title: `v0.X.Y`
6. Description: Copy from CHANGELOG
7. Click "Publish release"
### Via GitHub CLI
```bash
gh release create v0.X.Y \
--title "v0.X.Y" \
--notes "$(cat CHANGELOG.md | sed -n '/## \[0.X.Y\]/,/## \[/p' | head -n -1)"
```
---
## Step 8: Verify Release
### Check GitHub
- ✅ Release appears on GitHub
- ✅ Tag is correct
- ✅ CHANGELOG is included
- ✅ Assets are attached (if any)
### Test Installation
```bash
# Test install from GitHub
./install.sh --list
# Verify version
cat VERSION
```
---
## Complete Example
```bash
# Releasing v0.6.0
# 1. Update version
echo "0.6.0" > VERSION
jq '.version = "0.6.0"' package.json > tmp && mv tmp package.json
# 2. Update CHANGELOG
cat >> CHANGELOG.md << 'EOF'
## [0.6.0] - 2025-12-10
### Added
- New API specialist agent
- GraphQL support in backend specialist
### Changed
- Improved eval framework performance
- Updated registry schema to 2.0.0
### Fixed
- Fixed path resolution for subagents
- Fixed registry validation edge cases
EOF
# 3. Commit
git add VERSION package.json CHANGELOG.md
git commit -m "chore: bump version to 0.6.0"
# 4. Tag
git tag -a v0.6.0 -m "Release v0.6.0"
# 5. Push
git push origin main
git push origin v0.6.0
# 6. Create GitHub release
gh release create v0.6.0 \
--title "v0.6.0" \
--notes "See CHANGELOG.md for details"
```
---
## Checklist
Before releasing:
- [ ] All tests pass
- [ ] Registry validates
- [ ] VERSION updated
- [ ] package.json updated
- [ ] CHANGELOG updated
- [ ] Changes committed
- [ ] Tag created
- [ ] Pushed to GitHub
- [ ] GitHub release created
- [ ] Installation tested
---
## Common Issues
### Version Mismatch
**Problem**: VERSION and package.json don't match
**Solution**: Update both to same version
### Tag Already Exists
**Problem**: Tag already exists
**Solution**: Delete tag and recreate
```bash
git tag -d v0.X.Y
git push origin :refs/tags/v0.X.Y
```
### Push Rejected
**Problem**: Push rejected (not up to date)
**Solution**: Pull latest changes first
```bash
git pull origin main
git push origin main
git push origin v0.X.Y
```
---
## Related Files
- **Version management**: `scripts/versioning/bump-version.sh`
- **CHANGELOG**: `CHANGELOG.md`
- **VERSION**: `VERSION`
---
**Last Updated**: 2025-12-10
**Version**: 0.5.0

View file

@ -0,0 +1,399 @@
# Guide: Debugging Common Issues
**Purpose**: Troubleshooting guide for common problems
---
## Quick Diagnostics
```bash
# Check system health
./scripts/registry/validate-registry.sh
./scripts/validation/validate-test-suites.sh
# Check version consistency
cat VERSION && cat package.json | jq '.version'
# Test core agents
cd evals/framework && npm run eval:sdk -- --agent=core/openagent --pattern="smoke-test.yaml"
```
---
## Registry Issues
### Registry Validation Fails
**Symptoms**:
```
ERROR: Path does not exist: .opencode/agent/core/missing.md
```
**Diagnosis**:
```bash
./scripts/registry/validate-registry.sh -v
```
**Solutions**:
1. **Path doesn't exist**: Remove entry or create file
2. **Duplicate ID**: Rename one component
3. **Invalid category**: Use valid category
**Fix**:
```bash
# Re-run auto-detect
./scripts/registry/auto-detect-components.sh --auto-add
# Validate
./scripts/registry/validate-registry.sh
```
---
### Component Not in Registry
**Symptoms**:
- Component doesn't appear in `./install.sh --list`
- Auto-detect doesn't find component
**Diagnosis**:
```bash
# Check frontmatter
head -10 .opencode/agent/{category}/{agent}.md
# Dry run auto-detect
./scripts/registry/auto-detect-components.sh --dry-run
```
**Solutions**:
1. **Missing frontmatter**: Add frontmatter
2. **Invalid YAML**: Fix YAML syntax
3. **Wrong location**: Move to correct directory
**Fix**:
```bash
# Add frontmatter
cat > .opencode/agent/{category}/{agent}.md << 'EOF'
---
description: "Brief description"
category: "category"
type: "agent"
---
# Agent Content
EOF
# Re-run auto-detect
./scripts/registry/auto-detect-components.sh --auto-add
```
---
## Test Failures
### Approval Gate Violation
**Symptoms**:
```
✗ Approval Gate: FAIL
Violation: Agent executed write tool without requesting approval
```
**Diagnosis**:
```bash
# Run with debug
cd evals/framework
npm run eval:sdk -- --agent={agent} --pattern="{test}" --debug
# Check session
ls -lt .tmp/sessions/ | head -5
cat .tmp/sessions/{session-id}/session.json | jq
```
**Solution**:
Add approval request in agent prompt:
```markdown
Before executing:
1. Present plan to user
2. Request approval
3. Execute after approval
```
---
### Context Loading Violation
**Symptoms**:
```
✗ Context Loading: FAIL
Violation: Agent executed write tool without loading required context
```
**Diagnosis**:
```bash
# Check what context was loaded
cat .tmp/sessions/{session-id}/events.json | jq '.[] | select(.type == "context_load")'
```
**Solution**:
Add context loading in agent prompt:
```markdown
Before implementing:
1. Load core/standards/code.md
2. Apply standards to implementation
```
---
### Tool Usage Violation
**Symptoms**:
```
✗ Tool Usage: FAIL
Violation: Agent used bash tool for reading file instead of read tool
```
**Diagnosis**:
```bash
# Check tool usage
cat .tmp/sessions/{session-id}/events.json | jq '.[] | select(.type == "tool_call")'
```
**Solution**:
Update agent to use correct tools:
- Use `read` instead of `bash cat`
- Use `list` instead of `bash ls`
- Use `grep` instead of `bash grep`
---
## Install Issues
### Install Script Fails
**Symptoms**:
```
ERROR: Failed to fetch registry
ERROR: Component not found
```
**Diagnosis**:
```bash
# Check dependencies
which curl jq
# Test with local registry
REGISTRY_URL="file://$(pwd)/registry.json" ./install.sh --list
```
**Solutions**:
1. **Missing dependencies**: Install curl and jq
2. **Registry not found**: Check registry.json exists
3. **Component not found**: Verify component in registry
**Fix**:
```bash
# Install dependencies (macOS)
brew install curl jq
# Install dependencies (Linux)
sudo apt-get install curl jq
# Test locally
REGISTRY_URL="file://$(pwd)/registry.json" ./install.sh --list
```
---
### Collision Handling
**Symptoms**:
```
File exists: .opencode/agent/core/openagent.md
```
**Solutions**:
1. **Skip**: Keep existing file
2. **Overwrite**: Replace with new file
3. **Backup**: Backup existing, install new
**Fix**:
```bash
# Skip all collisions
./install.sh developer --skip-existing
# Overwrite all collisions
./install.sh developer --force
# Backup all collisions
./install.sh developer --backup
```
---
## Path Resolution Issues
### Agent Not Found
**Symptoms**:
```
ERROR: Agent not found: development/frontend-specialist
```
**Diagnosis**:
```bash
# Check file exists
ls -la .opencode/agent/development/frontend-specialist.md
# Check registry
cat registry.json | jq '.components.agents[] | select(.id == "frontend-specialist")'
```
**Solutions**:
1. **File doesn't exist**: Create file
2. **Wrong path**: Fix path in registry
3. **Not in registry**: Run auto-detect
**Fix**:
```bash
# Re-run auto-detect
./scripts/registry/auto-detect-components.sh --auto-add
# Validate
./scripts/registry/validate-registry.sh
```
---
## Version Issues
### Version Mismatch
**Symptoms**:
```
VERSION: 0.5.0
package.json: 0.4.0
registry.json: 0.5.0
```
**Diagnosis**:
```bash
cat VERSION
cat package.json | jq '.version'
cat registry.json | jq '.version'
```
**Solution**:
Update all to same version:
```bash
echo "0.5.0" > VERSION
jq '.version = "0.5.0"' package.json > tmp && mv tmp package.json
jq '.version = "0.5.0"' registry.json > tmp && mv tmp registry.json
```
---
## CI/CD Issues
### Workflow Fails
**Symptoms**:
- Registry validation fails in CI
- Tests fail in CI but pass locally
**Diagnosis**:
```bash
# Run same commands as CI
./scripts/registry/validate-registry.sh
./scripts/validation/validate-test-suites.sh
cd evals/framework && npm run eval:sdk
```
**Solutions**:
1. **Registry invalid**: Fix registry
2. **Tests fail**: Fix tests
3. **Dependencies missing**: Update CI config
---
## Performance Issues
### Tests Timeout
**Symptoms**:
```
ERROR: Test timeout after 60000ms
```
**Solution**:
Increase timeout in config.yaml:
```yaml
timeout: 120000 # 2 minutes
```
---
### Slow Auto-Detect
**Symptoms**:
Auto-detect takes too long
**Solution**:
Limit scope:
```bash
# Only scan specific directory
./scripts/registry/auto-detect-components.sh --path .opencode/agent/development/
```
---
## Getting Help
### Check Logs
```bash
# Session logs
ls -lt .tmp/sessions/ | head -5
cat .tmp/sessions/{session-id}/session.json | jq
# Event timeline
cat .tmp/sessions/{session-id}/events.json | jq
```
### Run Diagnostics
```bash
# Full system check
./scripts/registry/validate-registry.sh -v
./scripts/validation/validate-test-suites.sh
cd evals/framework && npm run eval:sdk -- --agent=core/openagent
```
### Common Commands
```bash
# Validate everything
./scripts/registry/validate-registry.sh && \
./scripts/validation/validate-test-suites.sh && \
cd evals/framework && npm run eval:sdk
# Reset and rebuild
./scripts/registry/auto-detect-components.sh --auto-add --force
./scripts/registry/validate-registry.sh
# Test installation
REGISTRY_URL="file://$(pwd)/registry.json" ./install.sh --list
```
---
## Related Files
- **Testing guide**: `guides/testing-agent.md`
- **Registry guide**: `guides/updating-registry.md`
- **Eval concepts**: `core-concepts/evals.md`
---
**Last Updated**: 2025-12-10
**Version**: 0.5.0

View file

@ -0,0 +1,303 @@
# Guide: Testing an Agent
**Prerequisites**: Load `core-concepts/evals.md` first
**Purpose**: Step-by-step workflow for testing agents
---
## Quick Start
```bash
# Run smoke test
cd evals/framework
npm run eval:sdk -- --agent={category}/{agent} --pattern="smoke-test.yaml"
# Run all tests for agent
npm run eval:sdk -- --agent={category}/{agent}
# Run with debug
npm run eval:sdk -- --agent={category}/{agent} --debug
```
---
## Test Types
### 1. Smoke Test
**Purpose**: Basic functionality check
```yaml
name: Smoke Test
description: Verify agent responds correctly
agent: {category}/{agent}
model: anthropic/claude-sonnet-4-5
conversation:
- role: user
content: "Hello, can you help me?"
expectations:
- type: no_violations
```
**Run**:
```bash
npm run eval:sdk -- --agent={agent} --pattern="smoke-test.yaml"
```
---
### 2. Approval Gate Test
**Purpose**: Verify agent requests approval
```yaml
name: Approval Gate Test
description: Verify agent requests approval before execution
agent: {category}/{agent}
model: anthropic/claude-sonnet-4-5
conversation:
- role: user
content: "Create a new file called test.js"
expectations:
- type: specific_evaluator
evaluator: approval_gate
should_pass: true
```
---
### 3. Context Loading Test
**Purpose**: Verify agent loads required context
```yaml
name: Context Loading Test
description: Verify agent loads required context
agent: {category}/{agent}
model: anthropic/claude-sonnet-4-5
conversation:
- role: user
content: "Write a new function"
expectations:
- type: context_loaded
contexts: ["core/standards/code.md"]
```
---
### 4. Tool Usage Test
**Purpose**: Verify agent uses correct tools
```yaml
name: Tool Usage Test
description: Verify agent uses appropriate tools
agent: {category}/{agent}
model: anthropic/claude-sonnet-4-5
conversation:
- role: user
content: "Read the package.json file"
expectations:
- type: tool_usage
tools: ["read"]
min_count: 1
```
---
## Running Tests
### Single Test
```bash
cd evals/framework
npm run eval:sdk -- --agent={category}/{agent} --pattern="{test-name}.yaml"
```
### All Tests for Agent
```bash
cd evals/framework
npm run eval:sdk -- --agent={category}/{agent}
```
### All Tests (All Agents)
```bash
cd evals/framework
npm run eval:sdk
```
### With Debug Output
```bash
cd evals/framework
npm run eval:sdk -- --agent={agent} --pattern="{test}" --debug
```
---
## Interpreting Results
### Pass Example
```
✓ Test: smoke-test.yaml
Status: PASS
Duration: 5.2s
Evaluators:
✓ Approval Gate: PASS
✓ Context Loading: PASS
✓ Tool Usage: PASS
✓ Stop on Failure: PASS
✓ Execution Balance: PASS
```
### Fail Example
```
✗ Test: approval-gate.yaml
Status: FAIL
Duration: 4.8s
Evaluators:
✗ Approval Gate: FAIL
Violation: Agent executed write tool without requesting approval
Location: Message #3, Tool call #1
✓ Context Loading: PASS
✓ Tool Usage: PASS
```
---
## Debugging Failures
### Step 1: Run with Debug
```bash
npm run eval:sdk -- --agent={agent} --pattern="{test}" --debug
```
### Step 2: Check Session
```bash
# Find recent session
ls -lt .tmp/sessions/ | head -5
# View session
cat .tmp/sessions/{session-id}/session.json | jq
```
### Step 3: Analyze Events
```bash
# View event timeline
cat .tmp/sessions/{session-id}/events.json | jq
```
### Step 4: Identify Issue
Common issues:
- **Approval Gate Violation**: Agent executed without approval
- **Context Loading Violation**: Agent didn't load required context
- **Tool Usage Violation**: Agent used wrong tool (bash instead of read)
- **Stop on Failure Violation**: Agent auto-fixed instead of stopping
### Step 5: Fix Agent
Update agent prompt to address the issue, then re-test.
---
## Writing New Tests
### Test Template
```yaml
name: Test Name
description: What this test validates
agent: {category}/{agent}
model: anthropic/claude-sonnet-4-5
conversation:
- role: user
content: "User message"
- role: assistant
content: "Expected response (optional)"
expectations:
- type: no_violations
```
### Best Practices
✅ **Clear name** - Descriptive test name
✅ **Good description** - Explain what's being tested
✅ **Realistic scenario** - Test real-world usage
✅ **Specific expectations** - Clear pass/fail criteria
✅ **Fast execution** - Keep under 10 seconds
---
## Common Test Patterns
### Test Approval Workflow
```yaml
conversation:
- role: user
content: "Create a new file"
expectations:
- type: specific_evaluator
evaluator: approval_gate
should_pass: true
```
### Test Context Loading
```yaml
conversation:
- role: user
content: "Write new code"
expectations:
- type: context_loaded
contexts: ["core/standards/code.md"]
```
### Test Tool Selection
```yaml
conversation:
- role: user
content: "Read the README file"
expectations:
- type: tool_usage
tools: ["read"]
min_count: 1
```
---
## Continuous Testing
### Pre-Commit Hook
```bash
# Setup pre-commit hook
./scripts/validation/setup-pre-commit-hook.sh
```
### CI/CD Integration
Tests run automatically on:
- Pull requests
- Merges to main
- Release tags
---
## Related Files
- **Eval concepts**: `core-concepts/evals.md`
- **Debugging guide**: `guides/debugging.md`
- **Adding agents**: `guides/adding-agent.md`
---
**Last Updated**: 2025-12-10
**Version**: 0.5.0

View file

@ -0,0 +1,229 @@
# Guide: Updating Registry
**Prerequisites**: Load `core-concepts/registry.md` first
**Purpose**: How to update the component registry
---
## Quick Commands
```bash
# Auto-detect and add new components
./scripts/registry/auto-detect-components.sh --auto-add
# Validate registry
./scripts/registry/validate-registry.sh
# Dry run (see what would change)
./scripts/registry/auto-detect-components.sh --dry-run
```
---
## When to Update Registry
Update the registry when you:
- ✅ Add a new agent
- ✅ Add a new command
- ✅ Add a new tool
- ✅ Add a new context file
- ✅ Change component metadata
- ✅ Move or rename components
---
## Auto-Detect (Recommended)
### Step 1: Dry Run
```bash
# See what would be added/updated
./scripts/registry/auto-detect-components.sh --dry-run
```
**Output**:
```
Scanning .opencode/ for components...
Would add:
- agent: development/api-specialist
- context: development/api-patterns.md
Would update:
- agent: core/openagent (description changed)
```
### Step 2: Apply Changes
```bash
# Actually update registry
./scripts/registry/auto-detect-components.sh --auto-add
```
### Step 3: Validate
```bash
# Validate registry
./scripts/registry/validate-registry.sh
```
---
## Manual Updates (Not Recommended)
Only edit `registry.json` manually if auto-detect doesn't work.
### Adding Component Manually
```json
{
"id": "agent-name",
"name": "Agent Name",
"type": "agent",
"path": ".opencode/agent/category/agent-name.md",
"description": "Brief description",
"category": "category",
"tags": ["tag1", "tag2"],
"dependencies": [],
"version": "0.5.0"
}
```
### Validate After Manual Edit
```bash
./scripts/registry/validate-registry.sh
```
---
## Validation
### What Gets Validated
✅ **Schema** - Correct JSON structure
✅ **Paths** - All paths exist
✅ **IDs** - Unique IDs
✅ **Categories** - Valid categories
✅ **Dependencies** - Dependencies exist
### Validation Errors
```bash
# Example errors
ERROR: Path does not exist: .opencode/agent/core/missing.md
ERROR: Duplicate ID: frontend-specialist
ERROR: Invalid category: invalid-category
ERROR: Missing dependency: subagent:nonexistent
```
### Fixing Errors
1. **Path not found**: Fix path or remove entry
2. **Duplicate ID**: Rename one component
3. **Invalid category**: Use valid category
4. **Missing dependency**: Add dependency or remove reference
---
## Testing Registry Changes
### Test Locally
```bash
# Test with local registry
REGISTRY_URL="file://$(pwd)/registry.json" ./install.sh --list
# Try installing a component
REGISTRY_URL="file://$(pwd)/registry.json" ./install.sh --component agent:your-agent
```
### Verify Component Appears
```bash
# List all agents
cat registry.json | jq '.components.agents[].id'
# Check specific component
cat registry.json | jq '.components.agents[] | select(.id == "your-agent")'
```
---
## Common Tasks
### Add New Agent to Registry
```bash
# 1. Create agent file with frontmatter
# 2. Run auto-detect
./scripts/registry/auto-detect-components.sh --auto-add
# 3. Validate
./scripts/registry/validate-registry.sh
```
### Update Component Metadata
```bash
# 1. Update frontmatter in component file
# 2. Run auto-detect with force
./scripts/registry/auto-detect-components.sh --auto-add --force
# 3. Validate
./scripts/registry/validate-registry.sh
```
### Remove Component
```bash
# 1. Delete component file
# 2. Run auto-detect (will remove from registry)
./scripts/registry/auto-detect-components.sh --auto-add
# 3. Validate
./scripts/registry/validate-registry.sh
```
---
## CI/CD Integration
### Automatic Validation
Registry is validated on:
- Pull requests (`.github/workflows/validate-registry.yml`)
- Merges to main
- Release tags
### Auto-Update on Merge
Registry can be auto-updated after merge:
```yaml
# .github/workflows/update-registry.yml
- name: Update Registry
run: ./scripts/registry/auto-detect-components.sh --auto-add
```
---
## Best Practices
✅ **Use auto-detect** - Don't manually edit registry
✅ **Validate often** - Catch issues early
✅ **Test locally** - Use local registry for testing
✅ **Dry run first** - See changes before applying
✅ **Version consistency** - Keep versions in sync
---
## Related Files
- **Registry concepts**: `core-concepts/registry.md`
- **Adding agents**: `guides/adding-agent.md`
- **Debugging**: `guides/debugging.md`
---
**Last Updated**: 2025-12-10
**Version**: 0.5.0

View file

@ -0,0 +1,387 @@
# Lookup: Command Reference
**Purpose**: Quick reference for common commands
---
## Registry Commands
### Validate Registry
```bash
# Basic validation
./scripts/registry/validate-registry.sh
# Verbose output
./scripts/registry/validate-registry.sh -v
```
### Auto-Detect Components
```bash
# Dry run (see what would change)
./scripts/registry/auto-detect-components.sh --dry-run
# Add new components
./scripts/registry/auto-detect-components.sh --auto-add
# Force update existing
./scripts/registry/auto-detect-components.sh --auto-add --force
```
### Validate Component Structure
```bash
./scripts/registry/validate-component.sh
```
---
## Testing Commands
### Run Tests
```bash
# Single test
cd evals/framework
npm run eval:sdk -- --agent={category}/{agent} --pattern="{test}.yaml"
# All tests for agent
npm run eval:sdk -- --agent={category}/{agent}
# All tests (all agents)
npm run eval:sdk
# With debug
npm run eval:sdk -- --agent={agent} --debug
```
### Validate Test Suites
```bash
./scripts/validation/validate-test-suites.sh
```
---
## Installation Commands
### Install Components
```bash
# List available components
./install.sh --list
# Install profile
./install.sh {profile}
# Profiles: essential, developer, business
# Install specific component
./install.sh --component agent:{agent-name}
# Test with local registry
REGISTRY_URL="file://$(pwd)/registry.json" ./install.sh --list
```
### Collision Handling
```bash
# Skip existing files
./install.sh developer --skip-existing
# Overwrite all
./install.sh developer --force
# Backup existing
./install.sh developer --backup
```
---
## Version Commands
### Check Version
```bash
# Check all version files
cat VERSION
cat package.json | jq '.version'
cat registry.json | jq '.version'
```
### Update Version
```bash
# Update VERSION
echo "0.X.Y" > VERSION
# Update package.json
jq '.version = "0.X.Y"' package.json > tmp && mv tmp package.json
# Update registry.json
jq '.version = "0.X.Y"' registry.json > tmp && mv tmp registry.json
```
### Bump Version Script
```bash
./scripts/versioning/bump-version.sh 0.X.Y
```
---
## Git Commands
### Create Release
```bash
# Commit version changes
git add VERSION package.json CHANGELOG.md
git commit -m "chore: bump version to 0.X.Y"
# Create tag
git tag -a v0.X.Y -m "Release v0.X.Y"
# Push
git push origin main
git push origin v0.X.Y
```
### Create GitHub Release
```bash
# Via GitHub CLI
gh release create v0.X.Y \
--title "v0.X.Y" \
--notes "See CHANGELOG.md for details"
```
---
## Validation Commands
### Full Validation
```bash
# Validate everything
./scripts/registry/validate-registry.sh && \
./scripts/validation/validate-test-suites.sh && \
cd evals/framework && npm run eval:sdk
```
### Validate Context References
```bash
./scripts/validation/validate-context-refs.sh
```
### Setup Pre-Commit Hook
```bash
./scripts/validation/setup-pre-commit-hook.sh
```
---
## Development Commands
### Run Demo
```bash
./scripts/development/demo.sh
```
### Run Dashboard
```bash
./scripts/development/dashboard.sh
```
---
## Maintenance Commands
### Cleanup Stale Sessions
```bash
./scripts/maintenance/cleanup-stale-sessions.sh
```
### Uninstall
```bash
./scripts/maintenance/uninstall.sh
```
---
## Debugging Commands
### Check Sessions
```bash
# List recent sessions
ls -lt .tmp/sessions/ | head -5
# View session
cat .tmp/sessions/{session-id}/session.json | jq
# View events
cat .tmp/sessions/{session-id}/events.json | jq
```
### Check Context Logs
```bash
# Check session cache
./scripts/check-context-logs/check-session-cache.sh
# Count agent tokens
./scripts/check-context-logs/count-agent-tokens.sh
# Show API payload
./scripts/check-context-logs/show-api-payload.sh
# Show cached data
./scripts/check-context-logs/show-cached-data.sh
```
---
## Quick Workflows
### Adding a New Agent
```bash
# 1. Create agent file
touch .opencode/agent/{category}/{agent-name}.md
# (Add frontmatter and content)
# 2. Create test structure
mkdir -p evals/agents/{category}/{agent-name}/{config,tests}
# (Create config.yaml and smoke-test.yaml)
# 3. Update registry
./scripts/registry/auto-detect-components.sh --auto-add
# 4. Validate
./scripts/registry/validate-registry.sh
cd evals/framework && npm run eval:sdk -- --agent={category}/{agent-name}
```
### Testing an Agent
```bash
# 1. Run smoke test
cd evals/framework
npm run eval:sdk -- --agent={category}/{agent} --pattern="smoke-test.yaml"
# 2. If fails, debug
npm run eval:sdk -- --agent={category}/{agent} --debug
# 3. Check session
ls -lt .tmp/sessions/ | head -1
cat .tmp/sessions/{session-id}/session.json | jq
```
### Creating a Release
```bash
# 1. Update version
echo "0.X.Y" > VERSION
jq '.version = "0.X.Y"' package.json > tmp && mv tmp package.json
# 2. Update CHANGELOG
# (Edit CHANGELOG.md)
# 3. Commit and tag
git add VERSION package.json CHANGELOG.md
git commit -m "chore: bump version to 0.X.Y"
git tag -a v0.X.Y -m "Release v0.X.Y"
# 4. Push
git push origin main
git push origin v0.X.Y
# 5. Create GitHub release
gh release create v0.X.Y --title "v0.X.Y" --notes "See CHANGELOG.md"
```
---
## Common Patterns
### Find Files
```bash
# Find agent
find .opencode/agent -name "{agent-name}.md"
# Find tests
find evals/agents -name "*.yaml"
# Find context
find .opencode/context -name "*.md"
# Find scripts
find scripts -name "*.sh"
```
### Check Registry
```bash
# List all agents
cat registry.json | jq '.components.agents[].id'
# Check specific component
cat registry.json | jq '.components.agents[] | select(.id == "{agent-name}")'
# Count components
cat registry.json | jq '.components.agents | length'
```
### Test Locally
```bash
# Test with local registry
REGISTRY_URL="file://$(pwd)/registry.json" ./install.sh --list
# Install locally
REGISTRY_URL="file://$(pwd)/registry.json" ./install.sh developer
```
---
## NPM Commands (Eval Framework)
```bash
cd evals/framework
# Install dependencies
npm install
# Run tests
npm test
# Run eval SDK
npm run eval:sdk
# Build
npm run build
# Lint
npm run lint
```
---
## Related Files
- **Quick start**: `quick-start.md`
- **File locations**: `lookup/file-locations.md`
- **Guides**: `guides/`
---
**Last Updated**: 2025-12-10
**Version**: 0.5.0

View file

@ -0,0 +1,318 @@
# Lookup: File Locations
**Purpose**: Quick reference for finding files
---
## Directory Tree
```
opencode-agents/
├── .opencode/
│ ├── agent/
│ │ ├── core/ # Core system agents
│ │ ├── development/ # Dev specialists
│ │ ├── content/ # Content creators
│ │ ├── data/ # Data analysts
│ │ ├── product/ # Product managers (ready)
│ │ ├── learning/ # Educators (ready)
│ │ └── subagents/ # Delegated specialists
│ │ ├── code/ # Code-related
│ │ ├── core/ # Core workflows
│ │ ├── system-builder/ # System generation
│ │ └── utils/ # Utilities
│ ├── command/ # Slash commands
│ ├── context/ # Shared knowledge
│ │ ├── core/ # Core standards & workflows
│ │ ├── development/ # Dev context
│ │ ├── content/ # Content context
│ │ ├── data/ # Data context
│ │ ├── product/ # Product context
│ │ ├── learning/ # Learning context
│ │ └── openagents-repo/ # Repo-specific context
│ ├── prompts/ # Model-specific variants
│ ├── tool/ # Custom tools
│ └── plugin/ # Plugins
├── evals/
│ ├── framework/ # Eval framework (TypeScript)
│ │ ├── src/ # Source code
│ │ ├── scripts/ # Test utilities
│ │ └── docs/ # Framework docs
│ └── agents/ # Agent test suites
│ ├── core/ # Core agent tests
│ ├── development/ # Dev agent tests
│ └── content/ # Content agent tests
├── scripts/
│ ├── registry/ # Registry management
│ ├── validation/ # Validation tools
│ ├── testing/ # Test utilities
│ ├── versioning/ # Version management
│ ├── docs/ # Doc tools
│ └── maintenance/ # Maintenance
├── docs/ # Documentation
│ ├── agents/ # Agent docs
│ ├── contributing/ # Contribution guides
│ ├── features/ # Feature docs
│ └── getting-started/ # User guides
├── registry.json # Component catalog
├── install.sh # Installer
├── VERSION # Current version
└── package.json # Node dependencies
```
---
## Where Is...?
| Component | Location |
|-----------|----------|
| **Core agents** | `.opencode/agent/core/` |
| **Category agents** | `.opencode/agent/{category}/` |
| **Subagents** | `.opencode/agent/subagents/` |
| **Commands** | `.opencode/command/` |
| **Context files** | `.opencode/context/` |
| **Prompt variants** | `.opencode/prompts/{category}/{agent}/` |
| **Tools** | `.opencode/tool/` |
| **Plugins** | `.opencode/plugin/` |
| **Agent tests** | `evals/agents/{category}/{agent}/` |
| **Eval framework** | `evals/framework/src/` |
| **Registry scripts** | `scripts/registry/` |
| **Validation scripts** | `scripts/validation/` |
| **Documentation** | `docs/` |
| **Registry** | `registry.json` |
| **Installer** | `install.sh` |
| **Version** | `VERSION` |
---
## Where Do I Add...?
| What | Where |
|------|-------|
| **New core agent** | `.opencode/agent/core/{name}.md` |
| **New category agent** | `.opencode/agent/{category}/{name}.md` |
| **New subagent** | `.opencode/agent/subagents/{category}/{name}.md` |
| **New command** | `.opencode/command/{name}.md` |
| **New context** | `.opencode/context/{category}/{name}.md` |
| **Agent tests** | `evals/agents/{category}/{agent}/tests/` |
| **Test config** | `evals/agents/{category}/{agent}/config/config.yaml` |
| **Documentation** | `docs/{section}/{topic}.md` |
| **Script** | `scripts/{purpose}/{name}.sh` |
---
## Specific File Paths
### Core Files
```
registry.json # Component catalog
install.sh # Main installer
update.sh # Update script
VERSION # Current version (0.5.0)
package.json # Node dependencies
CHANGELOG.md # Release notes
README.md # Main documentation
```
### Core Agents
```
.opencode/agent/core/openagent.md
.opencode/agent/core/opencoder.md
```
### Meta Agents
```
.opencode/agent/meta/system-builder.md
```
### Development Agents
```
.opencode/agent/development/frontend-specialist.md
.opencode/agent/development/backend-specialist.md
.opencode/agent/development/devops-specialist.md
.opencode/agent/development/codebase-agent.md
```
### Content Agents
```
.opencode/agent/content/copywriter.md
.opencode/agent/content/technical-writer.md
```
### Key Subagents
```
.opencode/agent/subagents/code/tester.md
.opencode/agent/subagents/code/reviewer.md
.opencode/agent/subagents/code/coder-agent.md
.opencode/agent/subagents/core/task-manager.md
.opencode/agent/subagents/core/documentation.md
```
### Core Context
```
.opencode/context/core/standards/code.md
.opencode/context/core/standards/docs.md
.opencode/context/core/standards/tests.md
.opencode/context/core/standards/patterns.md
.opencode/context/core/workflows/delegation.md
.opencode/context/core/workflows/review.md
```
### Registry Scripts
```
scripts/registry/validate-registry.sh
scripts/registry/auto-detect-components.sh
scripts/registry/register-component.sh
scripts/registry/validate-component.sh
```
### Validation Scripts
```
scripts/validation/validate-context-refs.sh
scripts/validation/validate-test-suites.sh
scripts/validation/setup-pre-commit-hook.sh
```
### Eval Framework
```
evals/framework/src/sdk/ # Test runner
evals/framework/src/evaluators/ # Rule evaluators
evals/framework/src/collector/ # Session collection
evals/framework/src/types/ # TypeScript types
```
---
## Path Patterns
### Agents
```
.opencode/agent/{category}/{agent-name}.md
```
**Examples**:
- `.opencode/agent/core/openagent.md`
- `.opencode/agent/development/frontend-specialist.md`
- `.opencode/agent/subagents/code/tester.md`
### Context
```
.opencode/context/{category}/{topic}.md
```
**Examples**:
- `.opencode/context/core/standards/code.md`
- `.opencode/context/development/react-patterns.md`
- `.opencode/context/content/copywriting-frameworks.md`
### Tests
```
evals/agents/{category}/{agent-name}/
├── config/config.yaml
└── tests/{test-name}.yaml
```
**Examples**:
- `evals/agents/core/openagent/tests/smoke-test.yaml`
- `evals/agents/development/frontend-specialist/tests/approval-gate.yaml`
### Scripts
```
scripts/{purpose}/{action}-{target}.sh
```
**Examples**:
- `scripts/registry/validate-registry.sh`
- `scripts/validation/validate-test-suites.sh`
- `scripts/versioning/bump-version.sh`
---
## Naming Conventions
### Files
- **Agents**: `{name}.md` or `{domain}-specialist.md`
- **Context**: `{topic}.md`
- **Tests**: `{test-name}.yaml`
- **Scripts**: `{action}-{target}.sh`
- **Docs**: `{topic}.md`
### Directories
- **Categories**: lowercase, singular (e.g., `development`, `content`)
- **Purposes**: lowercase, descriptive (e.g., `registry`, `validation`)
---
## Quick Lookups
### Find Agent File
```bash
# By name
find .opencode/agent -name "{agent-name}.md"
# By category
ls .opencode/agent/{category}/
# All agents
find .opencode/agent -name "*.md" -not -path "*/subagents/*"
```
### Find Test File
```bash
# By agent
ls evals/agents/{category}/{agent}/tests/
# All tests
find evals/agents -name "*.yaml"
```
### Find Context File
```bash
# By category
ls .opencode/context/{category}/
# All context
find .opencode/context -name "*.md"
```
### Find Script
```bash
# By purpose
ls scripts/{purpose}/
# All scripts
find scripts -name "*.sh"
```
---
## Related Files
- **Quick start**: `quick-start.md`
- **Categories**: `core-concepts/categories.md`
- **Commands**: `lookup/commands.md`
---
**Last Updated**: 2025-12-10
**Version**: 0.5.0

View file

@ -0,0 +1,167 @@
# OpenAgents Repository - Quick Start
**Purpose**: Get oriented in this repo in 2 minutes
---
## What Is This Repo?
OpenAgents is an AI agent framework with:
- **Category-based agents** (core, development, content, data, product, learning)
- **Eval framework** for testing agent behavior
- **Registry system** for component distribution
- **Install system** for easy setup
---
## Core Concepts (Load These First)
Before working on this repo, understand these 4 systems:
1. **Agents** → Load: `core-concepts/agents.md`
- How agents are structured
- Category system
- Prompt variants
- Subagents vs category agents
2. **Evals** → Load: `core-concepts/evals.md`
- How testing works
- Running tests
- Evaluators
- Session collection
3. **Registry** → Load: `core-concepts/registry.md`
- How components are tracked
- Auto-detect system
- Validation
- Install system
4. **Categories** → Load: `core-concepts/categories.md`
- How organization works
- Naming conventions
- Path patterns
---
## I Need To...
| Task | Load These Files |
|------|------------------|
| Add a new agent | `core-concepts/agents.md` + `guides/adding-agent.md` |
| Test an agent | `core-concepts/evals.md` + `guides/testing-agent.md` |
| Fix registry | `core-concepts/registry.md` + `guides/updating-registry.md` |
| Debug issue | `guides/debugging.md` |
| Find files | `lookup/file-locations.md` |
| Create release | `guides/creating-release.md` |
---
## Essential Paths (Top 15)
```
.opencode/agent/core/ # Core agents (openagent, opencoder)
.opencode/agent/{category}/ # Category agents
.opencode/agent/subagents/ # Subagents
evals/agents/{category}/{agent}/ # Agent tests
evals/framework/src/ # Eval framework code
registry.json # Component catalog
install.sh # Installer
scripts/registry/validate-registry.sh # Validate registry
scripts/registry/auto-detect-components.sh # Auto-detect components
scripts/validation/validate-test-suites.sh # Validate tests
.opencode/context/ # Context files
.opencode/command/ # Slash commands
docs/ # Documentation
VERSION # Current version
package.json # Node dependencies
```
---
## Common Commands (Top 10)
```bash
# Add new agent (auto-detect)
./scripts/registry/auto-detect-components.sh --auto-add
# Validate registry
./scripts/registry/validate-registry.sh
# Test agent
cd evals/framework && npm run eval:sdk -- --agent={category}/{agent}
# Run smoke test
cd evals/framework && npm run eval:sdk -- --agent={agent} --pattern="smoke-test.yaml"
# Test with debug
cd evals/framework && npm run eval:sdk -- --agent={agent} --debug
# Validate test suites
./scripts/validation/validate-test-suites.sh
# Install locally (test)
REGISTRY_URL="file://$(pwd)/registry.json" ./install.sh --list
# Bump version
echo "0.X.Y" > VERSION && jq '.version = "0.X.Y"' package.json > tmp && mv tmp package.json
# Check version consistency
cat VERSION && cat package.json | jq '.version'
# Run full validation
./scripts/registry/validate-registry.sh && ./scripts/validation/validate-test-suites.sh
```
---
## Repository Structure (Quick View)
```
opencode-agents/
├── .opencode/
│ ├── agent/{category}/ # Agents by domain
│ │ ├── core/ # Core system agents
│ │ ├── development/ # Dev specialists
│ │ ├── content/ # Content creators
│ │ ├── data/ # Data analysts
│ │ ├── product/ # Product managers
│ │ ├── learning/ # Educators
│ │ └── subagents/ # Delegated specialists
│ ├── command/ # Slash commands
│ └── context/ # Shared knowledge
├── evals/
│ ├── agents/{category}/ # Test suites
│ └── framework/ # Eval framework
├── scripts/
│ ├── registry/ # Registry tools
│ └── validation/ # Validation tools
├── docs/ # Documentation
├── registry.json # Component catalog
└── install.sh # Installer
```
---
## Quick Troubleshooting
| Problem | Solution |
|---------|----------|
| Registry validation fails | `./scripts/registry/auto-detect-components.sh --auto-add` |
| Test fails | Load `guides/debugging.md` |
| Can't find file | Load `lookup/file-locations.md` |
| Install fails | Check: `which curl jq` |
| Path resolution issues | Check `core-concepts/categories.md` |
---
## Next Steps
1. **First time?** → Read `core-concepts/agents.md`, `evals.md`, `registry.md`
2. **Adding agent?** → Load `guides/adding-agent.md`
3. **Testing?** → Load `guides/testing-agent.md`
4. **Need details?** → Load specific files from `core-concepts/` or `guides/`
---
**Last Updated**: 2025-12-10
**Version**: 0.5.0

View file

@ -0,0 +1,248 @@
# Context Bundle Template
**Purpose**: Template for creating context bundles when delegating tasks to subagents
**Location**: `.tmp/context/{session-id}/bundle.md`
**Used by**: repo-manager agent when delegating to subagents
---
## Template
```markdown
# Context Bundle: {Task Name}
Session: {session-id}
Created: {ISO timestamp}
For: {subagent-name}
Status: in_progress
## Task Overview
{Brief description of what we're building/doing}
## User Request
{Original user request - what they asked for}
## Relevant Standards (Load These Before Starting)
**Core Standards**:
- `.opencode/context/core/standards/code.md` → Modular, functional code patterns
- `.opencode/context/core/standards/tests.md` → Testing requirements and TDD
- `.opencode/context/core/standards/docs.md` → Documentation standards
- `.opencode/context/core/standards/patterns.md` → Error handling, security patterns
**Core Workflows**:
- `.opencode/context/core/workflows/delegation.md` → Delegation process
- `.opencode/context/core/workflows/task-breakdown.md` → Task breakdown methodology
- `.opencode/context/core/workflows/review.md` → Code review guidelines
## Repository-Specific Context (Load These Before Starting)
**Quick Start** (ALWAYS load first):
- `.opencode/context/openagents-repo/quick-start.md` → Repo orientation and common commands
**Core Concepts** (Load based on task type):
- `.opencode/context/openagents-repo/core-concepts/agents.md` → How agents work
- `.opencode/context/openagents-repo/core-concepts/evals.md` → How testing works
- `.opencode/context/openagents-repo/core-concepts/registry.md` → How registry works
- `.opencode/context/openagents-repo/core-concepts/categories.md` → How organization works
**Guides** (Load for specific workflows):
- `.opencode/context/openagents-repo/guides/adding-agent.md` → Step-by-step agent creation
- `.opencode/context/openagents-repo/guides/testing-agent.md` → Testing workflow
- `.opencode/context/openagents-repo/guides/updating-registry.md` → Registry workflow
- `.opencode/context/openagents-repo/guides/debugging.md` → Troubleshooting
**Lookup** (Quick reference):
- `.opencode/context/openagents-repo/lookup/file-locations.md` → Where everything is
- `.opencode/context/openagents-repo/lookup/commands.md` → Command reference
## Key Requirements
{Extract key requirements from loaded context}
**From Standards**:
- {requirement 1 from standards/code.md}
- {requirement 2 from standards/tests.md}
- {requirement 3 from standards/docs.md}
**From Repository Context**:
- {requirement 1 from repo context}
- {requirement 2 from repo context}
- {requirement 3 from repo context}
**Naming Conventions**:
- {convention 1}
- {convention 2}
**File Structure**:
- {structure requirement 1}
- {structure requirement 2}
## Technical Constraints
{List technical constraints and limitations}
- {constraint 1 - e.g., "Must use TypeScript"}
- {constraint 2 - e.g., "Must follow category-based organization"}
- {constraint 3 - e.g., "Must include proper frontmatter metadata"}
## Files to Create/Modify
{List all files that need to be created or modified}
**Create**:
- `{file-path-1}` - {purpose and what it should contain}
- `{file-path-2}` - {purpose and what it should contain}
**Modify**:
- `{file-path-3}` - {what needs to be changed}
- `{file-path-4}` - {what needs to be changed}
## Success Criteria
{Define what "done" looks like - binary pass/fail conditions}
- [ ] {criteria 1 - e.g., "Agent file created with proper frontmatter"}
- [ ] {criteria 2 - e.g., "Eval tests pass"}
- [ ] {criteria 3 - e.g., "Registry validation passes"}
- [ ] {criteria 4 - e.g., "Documentation updated"}
## Validation Requirements
{How to validate the work}
**Scripts to Run**:
- `{validation-script-1}` - {what it validates}
- `{validation-script-2}` - {what it validates}
**Tests to Run**:
- `{test-command-1}` - {what it tests}
- `{test-command-2}` - {what it tests}
**Manual Checks**:
- {check 1}
- {check 2}
## Expected Output
{What the subagent should produce}
**Deliverables**:
- {deliverable 1}
- {deliverable 2}
**Format**:
- {format requirement 1}
- {format requirement 2}
## Progress Tracking
{Track progress through the task}
- [ ] Context loaded and understood
- [ ] {step 1}
- [ ] {step 2}
- [ ] {step 3}
- [ ] Validation passed
- [ ] Documentation updated
---
## Instructions for Subagent
{Specific, detailed instructions for the subagent}
**IMPORTANT**:
1. Load ALL context files listed in "Relevant Standards" and "Repository-Specific Context" sections BEFORE starting work
2. Follow ALL requirements from the loaded context
3. Apply naming conventions and file structure requirements
4. Validate your work using the validation requirements
5. Update progress tracking as you complete steps
**Your Task**:
{Detailed description of what the subagent needs to do}
**Approach**:
{Suggested approach or methodology}
**Constraints**:
{Any additional constraints or notes}
**Questions/Clarifications**:
{Any questions the subagent should consider or clarifications needed}
```
---
## Usage Instructions
### When to Create a Context Bundle
Create a context bundle when:
- Delegating to any subagent
- Task requires coordination across multiple components
- Subagent needs project-specific context
- Task has complex requirements or constraints
### How to Create a Context Bundle
1. **Create session directory**:
```bash
mkdir -p .tmp/context/{session-id}
```
2. **Copy template**:
```bash
cp .opencode/context/openagents-repo/templates/context-bundle-template.md \
.tmp/context/{session-id}/bundle.md
```
3. **Fill in all sections**:
- Replace all `{placeholders}` with actual values
- List specific context files to load (with full paths)
- Extract key requirements from loaded context
- Define clear success criteria
- Provide specific instructions
4. **Pass to subagent**:
```javascript
task(
subagent_type="subagents/core/{subagent}",
description="Brief description",
prompt="Load context from .tmp/context/{session-id}/bundle.md before starting.
{Specific task instructions}
Follow all standards and requirements in the context bundle."
)
```
### Best Practices
**DO**:
- ✅ List context files with full paths (don't duplicate content)
- ✅ Extract key requirements from loaded context
- ✅ Define binary success criteria (pass/fail)
- ✅ Provide specific validation requirements
- ✅ Include clear instructions for subagent
- ✅ Track progress through the task
**DON'T**:
- ❌ Duplicate full context file content (just reference paths)
- ❌ Use vague success criteria ("make it good")
- ❌ Skip validation requirements
- ❌ Forget to list technical constraints
- ❌ Omit file paths for files to create/modify
### Example Context Bundle
See `.opencode/context/openagents-repo/examples/context-bundle-example.md` for a complete example.
---
**Last Updated**: 2025-01-21
**Version**: 1.0.0

View file

@ -0,0 +1,18 @@
# Product Context
This directory contains context files for product management, strategy, and user research.
## Available Context Files
*No context files yet. This category is ready for product-related context.*
## Planned Context Files
- **product-strategy.md** - Product vision, roadmap planning, prioritization frameworks
- **user-research-methods.md** - User interview techniques, survey design, usability testing
- **feature-prioritization.md** - RICE, MoSCoW, Kano model frameworks
- **metrics-analytics.md** - Key metrics, analytics frameworks, data-driven decisions
## Usage
These context files will be referenced by product-focused agents to ensure consistent product strategy, user research methodologies, and data-driven decision making.

View file

@ -0,0 +1,48 @@
# copywriter Prompt Variants
## Default Prompt
The **default prompt** is the agent file itself: `.opencode/agent/content/copywriter.md`
This is optimized for **Claude** (Anthropic models) and serves as the baseline.
## Model-Specific Variants
This directory is ready for model-specific optimizations:
| Variant | Model Family | Status | Best For |
|---------|--------------|--------|----------|
| gpt.md | GPT | 📝 Not yet created | GPT-4, GPT-4o |
| llama.md | Llama/OSS | 📝 Not yet created | Llama, Qwen, DeepSeek |
| gemini.md | Gemini | 📝 Not yet created | Gemini Pro, Gemini Ultra |
## Creating Variants
To create a model-specific variant:
1. Copy the agent file as a starting point
2. Adapt the prompt for the target model's characteristics
3. Test with the eval framework
4. Document results in this README
## Testing Variants
```bash
cd evals/framework
# Test default (agent file itself)
npm run eval:sdk -- --agent=content/copywriter
# Test model variants (when created)
npm run eval:sdk -- --agent=content/copywriter --prompt-variant=gpt
npm run eval:sdk -- --agent=content/copywriter --prompt-variant=llama
```
## Results
| Variant | Pass Rate | Notes |
|---------|-----------|-------|
| default (agent file) | - | Not yet tested |
| gpt | - | Not yet created |
| llama | - | Not yet created |
| gemini | - | Not yet created |

View file

@ -0,0 +1,48 @@
# technical writer Prompt Variants
## Default Prompt
The **default prompt** is the agent file itself: `.opencode/agent/content/technical-writer.md`
This is optimized for **Claude** (Anthropic models) and serves as the baseline.
## Model-Specific Variants
This directory is ready for model-specific optimizations:
| Variant | Model Family | Status | Best For |
|---------|--------------|--------|----------|
| gpt.md | GPT | 📝 Not yet created | GPT-4, GPT-4o |
| llama.md | Llama/OSS | 📝 Not yet created | Llama, Qwen, DeepSeek |
| gemini.md | Gemini | 📝 Not yet created | Gemini Pro, Gemini Ultra |
## Creating Variants
To create a model-specific variant:
1. Copy the agent file as a starting point
2. Adapt the prompt for the target model's characteristics
3. Test with the eval framework
4. Document results in this README
## Testing Variants
```bash
cd evals/framework
# Test default (agent file itself)
npm run eval:sdk -- --agent=content/technical-writer
# Test model variants (when created)
npm run eval:sdk -- --agent=content/technical-writer --prompt-variant=gpt
npm run eval:sdk -- --agent=content/technical-writer --prompt-variant=llama
```
## Results
| Variant | Pass Rate | Notes |
|---------|-----------|-------|
| default (agent file) | - | Not yet tested |
| gpt | - | Not yet created |
| llama | - | Not yet created |
| gemini | - | Not yet created |

View file

@ -0,0 +1,579 @@
---
# OpenCode Agent Configuration
description: "Universal agent for answering queries, executing tasks, and coordinating workflows across any domain - OpenRouter optimized"
mode: primary
temperature: 0.2
tools:
read: true
write: true
edit: true
grep: true
glob: true
bash: true
task: true
patch: true
permissions:
bash:
"rm -rf *": "ask"
"rm -rf /*": "deny"
"sudo *": "deny"
"> /dev/*": "deny"
edit:
"**/*.env*": "deny"
"**/*.key": "deny"
"**/*.secret": "deny"
"node_modules/**": "deny"
".git/**": "deny"
# Prompt Metadata
model_family: "openrouter"
recommended_models:
- "anthropic/claude-3.5-sonnet" # Primary recommendation
- "openai/gpt-4-turbo" # Alternative
- "google/gemini-pro-1.5" # Alternative
- "meta-llama/llama-3.1-70b-instruct" # OSS alternative
tested_with: "anthropic/claude-3.5-sonnet"
last_tested: "2025-12-10"
maintainer: "darrenhinde"
status: "stable"
---
<context>
<system_context>Universal AI agent for code, docs, tests, and workflow coordination called OpenAgent</system_context>
<domain_context>Any codebase, any language, any project structure</domain_context>
<task_context>Execute tasks directly or delegate to specialized subagents</task_context>
<execution_context>Context-aware execution with project standards enforcement</execution_context>
</context>
<critical_context_requirement>
PURPOSE: Context files contain project-specific standards that ensure consistency,
quality, and alignment with established patterns. Without loading context first,
you will create code/docs/tests that don't match the project's conventions,
causing inconsistency and rework.
BEFORE any bash/write/edit/task execution, ALWAYS load required context files.
(Read/list/glob/grep for discovery are allowed - load context once discovered)
NEVER proceed with code/docs/tests without loading standards first.
AUTO-STOP if you find yourself executing without context loaded.
WHY THIS MATTERS:
- Code without standards/code.md → Inconsistent patterns, wrong architecture
- Docs without standards/docs.md → Wrong tone, missing sections, poor structure
- Tests without standards/tests.md → Wrong framework, incomplete coverage
- Review without workflows/review.md → Missed quality checks, incomplete analysis
- Delegation without workflows/delegation.md → Wrong context passed to subagents
Required context files:
- Code tasks → .opencode/context/core/standards/code.md
- Docs tasks → .opencode/context/core/standards/docs.md
- Tests tasks → .opencode/context/core/standards/tests.md
- Review tasks → .opencode/context/core/workflows/review.md
- Delegation → .opencode/context/core/workflows/delegation.md
CONSEQUENCE OF SKIPPING: Work that doesn't match project standards = wasted effort + rework
</critical_context_requirement>
<critical_rules priority="absolute" enforcement="strict">
<rule id="approval_gate" scope="all_execution">
Request approval before ANY execution (bash, write, edit, task). Read/list ops don't require approval.
</rule>
<rule id="stop_on_failure" scope="validation">
STOP on test fail/errors - NEVER auto-fix
</rule>
<rule id="report_first" scope="error_handling">
On fail: REPORT→PROPOSE FIX→REQUEST APPROVAL→FIX (never auto-fix)
</rule>
<rule id="confirm_cleanup" scope="session_management">
Confirm before deleting session files/cleanup ops
</rule>
</critical_rules>
<role>
OpenAgent - primary universal agent for questions, tasks, workflow coordination
<authority>Delegates to specialists, maintains oversight</authority>
</role>
<!-- ═══════════════════════════════════════════════════════════════════════════════ -->
<!-- SUBAGENT CATALOG - OPENROUTER CRITICAL SECTION -->
<!-- OpenRouter cannot browse folders. All available subagents are explicitly listed -->
<!-- below with full paths. CHECK THIS SECTION FIRST before executing any task. -->
<!-- ═══════════════════════════════════════════════════════════════════════════════ -->
## 🤖 AVAILABLE SUBAGENTS (Explicit Catalog for OpenRouter)
<delegation_mindset>
**CRITICAL FOR OPENROUTER**: You have access to 6 specialized subagents listed below.
**Delegation-First Approach**:
- CHECK delegation rules BEFORE executing any task
- AUTOMATICALLY invoke subagents when task matches their capabilities
- DO NOT wait for user to explicitly mention subagents
- Subagents are your primary execution mechanism for complex work
**Why delegate?**:
- Subagents are specialized and optimized for specific tasks
- They have focused context and tools
- Better token efficiency (you coordinate, they execute)
- Higher quality results through specialization
</delegation_mindset>
### Quick Reference: All 6 Subagents
| Subagent | Path | Use When |
|----------|------|----------|
| **task-manager** | `subagents/core/task-manager` | 4+ files, >60 min, complex features |
| **coder-agent** | `subagents/code/coder-agent` | 1-3 files, simple implementation |
| **tester** | `subagents/code/tester` | After code changes, need tests |
| **build-agent** | `subagents/code/build-agent` | Type check, build validation |
| **documentation** | `subagents/core/documentation` | Generate docs, README |
| **reviewer** | `subagents/code/reviewer` | Code review, security audit |
### Core Subagents
**subagents/core/task-manager** - Complex feature breakdown
- **Path**: `subagents/core/task-manager`
- **Capabilities**: Feature planning, task breakdown, dependency analysis
- **Auto-invoke when**: Task has 4+ components OR estimated >60 minutes OR complex dependencies
- **Example invocation**:
```javascript
task(
subagent_type="subagents/core/task-manager",
description="Break down feature",
prompt="Analyze and break down [feature] into atomic subtasks with dependencies and acceptance criteria"
)
```
### Code Subagents
**subagents/code/coder-agent** - Focused implementation
- **Path**: `subagents/code/coder-agent`
- **Capabilities**: Code implementation, refactoring, bug fixes
- **Auto-invoke when**: Simple 1-3 file implementation OR focused code changes
- **Example invocation**:
```javascript
task(
subagent_type="subagents/code/coder-agent",
description="Implement feature",
prompt="Implement [feature] following standards in @.opencode/context/core/standards/code.md"
)
```
**subagents/code/tester** - Test generation and execution
- **Path**: `subagents/code/tester`
- **Capabilities**: Unit tests, integration tests, test execution, coverage analysis
- **Auto-invoke when**: After code implementation OR user requests testing
- **Example invocation**:
```javascript
task(
subagent_type="subagents/code/tester",
description="Test feature",
prompt="Write comprehensive tests for [feature] following @.opencode/context/core/standards/tests.md. Ensure >80% coverage. Run tests and report results."
)
```
**subagents/code/build-agent** - Build and type checking
- **Path**: `subagents/code/build-agent`
- **Capabilities**: Type checking, build validation, compilation
- **Auto-invoke when**: After code changes OR before deployment
- **Example invocation**:
```javascript
task(
subagent_type="subagents/code/build-agent",
description="Validate build",
prompt="Run type checks and build validation. Report any errors."
)
```
### Documentation Subagents
**subagents/core/documentation** - Documentation generation
- **Path**: `subagents/core/documentation`
- **Capabilities**: README, API docs, code documentation
- **Auto-invoke when**: User requests documentation OR after major feature completion
- **Example invocation**:
```javascript
task(
subagent_type="subagents/core/documentation",
description="Document feature",
prompt="Generate comprehensive documentation for [feature] following @.opencode/context/core/standards/docs.md"
)
```
### Review Subagents
**subagents/code/reviewer** - Code review and quality checks
- **Path**: `subagents/code/reviewer`
- **Capabilities**: Code review, security audit, quality analysis
- **Auto-invoke when**: After code implementation OR user requests review
- **Example invocation**:
```javascript
task(
subagent_type="subagents/code/reviewer",
description="Review code",
prompt="Review [files] for code quality, security, and adherence to @.opencode/context/core/standards/code.md"
)
```
## 🎯 AUTOMATIC DELEGATION RULES
<automatic_delegation priority="critical">
**THESE RULES TRIGGER AUTOMATIC SUBAGENT INVOCATION**
Check these rules BEFORE executing ANY task. If a rule matches, invoke the subagent
automatically WITHOUT waiting for user to mention it.
<rule id="1" priority="highest" trigger="complex_features">
**Complex Features → task-manager**
IF (task has 4+ components) OR (estimated effort >60 min) OR (complex dependencies)
THEN invoke subagents/core/task-manager FIRST
Examples: "Build auth system", "Add payment flow", "Implement dashboard"
</rule>
<rule id="2" priority="high" trigger="simple_implementation">
**Code Implementation → coder-agent**
IF (simple 1-3 file implementation) AND (focused changes)
THEN invoke subagents/code/coder-agent
Examples: "Add login form", "Fix validation bug", "Update API endpoint"
</rule>
<rule id="3" priority="high" trigger="post_code">
**After Code → tester + reviewer**
IF (code was written or modified)
THEN:
1. Invoke subagents/code/tester (write and run tests)
2. Invoke subagents/code/reviewer (quality check)
3. Report results to user
Examples: After implementing any feature, automatically test and review
</rule>
<rule id="4" priority="medium" trigger="documentation">
**Documentation Requests → documentation**
IF (user requests docs) OR (major feature completed)
THEN invoke subagents/core/documentation
Examples: "Document the API", "Add README", after completing major feature
</rule>
<rule id="5" priority="medium" trigger="build_validation">
**Build Validation → build-agent**
IF (code changes made) AND (TypeScript/compiled language)
THEN invoke subagents/code/build-agent
Examples: After TypeScript changes, before deployment
</rule>
</automatic_delegation>
## 📊 TOKEN BUDGET MANAGEMENT
**CRITICAL FOR OPENROUTER**: Different providers have different token limits. Manage tokens proactively.
**Token Reservation**:
- Reserve 8,000 tokens for subagent invocation
- If approaching limit, invoke subagents BEFORE running out of tokens
- Prioritize critical subagents (task-manager, coder-agent)
**Token Budget Check**:
```
IF (tokens_used > max_tokens - 8000)
THEN:
1. Invoke relevant subagents NOW (don't wait)
2. Summarize context for subagent
3. Let subagent handle detailed work
```
<execution_priority>
<tier level="1" desc="Safety & Approval Gates">
- @critical_context_requirement
- @critical_rules (all 4 rules)
- Permission checks
- User confirmation reqs
</tier>
<tier level="2" desc="Automatic Delegation">
- Check delegation rules BEFORE executing
- Invoke subagents proactively (don't wait for user mention)
- Token budget management
</tier>
<tier level="3" desc="Core Workflow">
- Stage progression: Analyze→Approve→Execute→Validate→Summarize
- Context loading
</tier>
<conflict_resolution>
Tier 1 always overrides Tier 2/3
Tier 2 (delegation) happens BEFORE Tier 3 (direct execution)
Edge case - "Should I delegate or execute directly?":
- Check delegation rules FIRST
- If rules match → Delegate to subagent
- If no match → Execute directly
- NEVER skip delegation check
</conflict_resolution>
</execution_priority>
<execution_paths>
<path type="conversational" trigger="pure_question_no_exec" approval_required="false">
Answer directly, naturally - no approval needed
<examples>"What does this code do?" (read) | "How use git rebase?" (info) | "Explain error" (analysis)</examples>
</path>
<path type="task" trigger="bash|write|edit|task" approval_required="true" enforce="@approval_gate">
Analyze→CheckDelegation→Approve→Execute→Validate→Summarize
<examples>"Create file" (write) | "Run tests" (bash) | "Fix bug" (edit)</examples>
</path>
</execution_paths>
<workflow>
<stage id="1" name="Analyze" required="true">
Assess req type→Determine path (conversational|task)
<criteria>Needs bash/write/edit/task? → Task path | Purely info/read-only? → Conversational path</criteria>
</stage>
<stage id="1.5" name="CheckDelegation" when="task_path" required="true">
**CRITICAL FOR OPENROUTER**: Check delegation rules BEFORE proceeding
<delegation_check>
1. Analyze task complexity and scope
2. Check against AUTOMATIC DELEGATION RULES (see section above - scroll up to 🎯 icon)
3. Match task against each rule (1-5):
- Rule 1: Complex features (4+ components, >60 min, dependencies)?
- Rule 2: Simple implementation (1-3 files, focused)?
- Rule 3: Code was written (need testing/review)?
- Rule 4: Documentation needed?
- Rule 5: Build validation needed?
4. If ANY rule matches:
- Prepare subagent invocation
- Load delegation context: @.opencode/context/core/workflows/delegation.md
- Include in approval plan: "Will delegate to [subagent-name] (Rule X matched)"
5. If NO rules match:
- Proceed with direct execution
- Load appropriate context files
</delegation_check>
<decision_tree>
"Implement auth system"
→ 4+ components? YES
→ Rule 1 matches
→ Delegate to task-manager
"Fix typo in README"
→ Simple change? YES
→ No rules match
→ Execute directly
"Add login form"
→ 1-3 files, focused? YES
→ Rule 2 matches
→ Delegate to coder-agent
"Write tests for auth"
→ Testing task? YES
→ Rule 3 matches
→ Delegate to tester
</decision_tree>
</stage>
<stage id="2" name="Approve" when="task_path" required="true" enforce="@approval_gate">
Present plan→Request approval→Wait confirm
<format>
## Proposed Plan
[steps]
**Delegation**: [If applicable: "Will delegate to subagents/[name]" OR "Will execute directly"]
**Approval needed before proceeding.**
</format>
<skip_only_if>Pure info question w/ zero exec</skip_only_if>
</stage>
<stage id="3" name="Execute" when="approved">
<prerequisites>User approval received (Stage 2 complete)</prerequisites>
<step id="3.1" name="LoadContext" required="true" enforce="@critical_context_requirement">
⛔ STOP. Before executing, check task type:
1. Classify task: docs|code|tests|delegate|review|patterns|bash-only
2. Map to context file:
- code (write/edit code) → Read @.opencode/context/core/standards/code.md NOW
- docs (write/edit docs) → Read @.opencode/context/core/standards/docs.md NOW
- tests (write/edit tests) → Read @.opencode/context/core/standards/tests.md NOW
- review (code review) → Read @.opencode/context/core/workflows/review.md NOW
- delegate (using task tool) → Read @.opencode/context/core/workflows/delegation.md NOW
- bash-only → No context needed, proceed to 3.2
3. Apply context:
IF delegating: Tell subagent "Load [context-file] before starting"
IF direct: Use Read tool to load context file, then proceed to 3.2
<automatic_loading>
IF code task → @.opencode/context/core/standards/code.md (MANDATORY)
IF docs task → @.opencode/context/core/standards/docs.md (MANDATORY)
IF tests task → @.opencode/context/core/standards/tests.md (MANDATORY)
IF review task → @.opencode/context/core/workflows/review.md (MANDATORY)
IF delegation → @.opencode/context/core/workflows/delegation.md (MANDATORY)
IF bash-only → No context required
WHEN DELEGATING TO SUBAGENTS:
- Include context file path in subagent prompt
- Example: "Load @.opencode/context/core/standards/code.md before implementing"
- Subagent will load context using read tool
</automatic_loading>
</step>
<step id="3.2" name="ExecuteOrDelegate">
IF (delegation planned in Stage 1.5):
- Invoke subagent using task tool
- Pass detailed instructions
- Include context file references
- Wait for subagent response
ELSE:
- Execute task directly
- Follow loaded context standards
- Use appropriate tools
</step>
</stage>
<stage id="4" name="Validate" when="execution_complete" enforce="@stop_on_failure">
Check quality→Verify complete→Test if applicable
<on_failure enforce="@report_first">
STOP→Report error→Propose fix→Request approval→Fix→Re-validate
NEVER auto-fix without approval
</on_failure>
<validation_checks>
- Code: Type check, lint, tests pass
- Docs: Complete, follows standards
- Tests: Pass, adequate coverage
- Delegation: Subagent completed successfully
</validation_checks>
</stage>
<stage id="5" name="Summarize" required="true">
Report results→Next steps→Handoff recommendations
<format>
## Summary
- What was done: [description]
- Results: [outcomes]
- Validation: [checks performed]
**Next steps**: [recommendations]
</format>
<handoff_recommendations>
IF code written AND tests not run:
- Recommend: "Invoke subagents/code/tester to write and run tests"
IF code written AND not reviewed:
- Recommend: "Invoke subagents/code/reviewer for quality check"
IF major feature completed AND no docs:
- Recommend: "Invoke subagents/core/documentation to generate docs"
</handoff_recommendations>
</stage>
</workflow>
<delegation_criteria>
<route agent="subagents/core/task-manager" category="features">
<when>Feature spans 4+ files | effort >60 min | complex dependencies</when>
<context_inheritance>Load @.opencode/context/core/workflows/delegation.md</context_inheritance>
<invocation>
task(
subagent_type="subagents/core/task-manager",
description="Break down [feature]",
prompt="Analyze and break down [feature] into atomic subtasks. Load @.opencode/context/core/workflows/delegation.md for process."
)
</invocation>
</route>
<route agent="subagents/code/coder-agent" category="implementation">
<when>Simple 1-3 file implementation | focused code changes</when>
<context_inheritance>Load @.opencode/context/core/standards/code.md</context_inheritance>
<invocation>
task(
subagent_type="subagents/code/coder-agent",
description="Implement [feature]",
prompt="Implement [feature] following @.opencode/context/core/standards/code.md. Use modular, functional patterns."
)
</invocation>
</route>
<route agent="subagents/code/tester" category="testing">
<when>After code implementation | user requests tests</when>
<context_inheritance>Load @.opencode/context/core/standards/tests.md</context_inheritance>
<invocation>
task(
subagent_type="subagents/code/tester",
description="Test [feature]",
prompt="Write comprehensive tests for [feature] following @.opencode/context/core/standards/tests.md. Ensure >80% coverage. Run tests and report results."
)
</invocation>
</route>
<route agent="subagents/code/reviewer" category="review">
<when>After code implementation | user requests review</when>
<context_inheritance>Load @.opencode/context/core/workflows/review.md</context_inheritance>
<invocation>
task(
subagent_type="subagents/code/reviewer",
description="Review [feature]",
prompt="Review [files] for code quality, security, and adherence to @.opencode/context/core/standards/code.md"
)
</invocation>
</route>
<route agent="subagents/core/documentation" category="docs">
<when>User requests docs | major feature completed</when>
<context_inheritance>Load @.opencode/context/core/standards/docs.md</context_inheritance>
<invocation>
task(
subagent_type="subagents/core/documentation",
description="Document [feature]",
prompt="Generate comprehensive documentation for [feature] following @.opencode/context/core/standards/docs.md"
)
</invocation>
</route>
<route agent="subagents/code/build-agent" category="validation">
<when>After code changes | TypeScript/compiled language | before deployment</when>
<context_inheritance>Load @.opencode/context/core/standards/code.md</context_inheritance>
<invocation>
task(
subagent_type="subagents/code/build-agent",
description="Validate build",
prompt="Run type checks and build validation for [files/project]. Report any errors. Follow @.opencode/context/core/standards/code.md for standards."
)
</invocation>
</route>
<direct_execution>
<when>Single file | simple edit | bash-only | direct user request</when>
<process>Load appropriate context → Execute directly → Validate</process>
</direct_execution>
</delegation_criteria>
<principles>
<lean>Concise, focused responses</lean>
<adaptive>Tone-matching: conversational for info, formal for tasks</adaptive>
<safe>ALWAYS request approval before ANY execution</safe>
<report_first>On errors: REPORT → PLAN → APPROVAL → FIX</report_first>
<proactive_delegation>Check delegation rules BEFORE executing (don't wait for user mention)</proactive_delegation>
<token_aware>Manage token budget, invoke subagents before running out</token_aware>
</principles>
<!-- END OF PROMPT -->

View file

@ -0,0 +1,39 @@
# Data Analyst Prompt Variants
## Default Prompt
The **default prompt** is the agent file itself: `.opencode/agent/data/data-analyst.md`
This is optimized for **Claude** (Anthropic models) and serves as the baseline.
## Model-Specific Variants
This directory is ready for model-specific optimizations:
| Variant | Model Family | Status | Best For |
|---------|--------------|--------|----------|
| gpt.md | GPT | 📝 Not yet created | GPT-4, GPT-4o |
| llama.md | Llama/OSS | 📝 Not yet created | Llama, Qwen, DeepSeek |
| gemini.md | Gemini | 📝 Not yet created | Gemini Pro, Gemini Ultra |
## Testing Variants
```bash
cd evals/framework
# Test default (agent file itself)
npm run eval:sdk -- --agent=data/data-analyst
# Test model variants (when created)
npm run eval:sdk -- --agent=data/data-analyst --prompt-variant=gpt
npm run eval:sdk -- --agent=data/data-analyst --prompt-variant=llama
```
## Results
| Variant | Pass Rate | Notes |
|---------|-----------|-------|
| default (agent file) | - | Not yet tested |
| gpt | - | Not yet created |
| llama | - | Not yet created |
| gemini | - | Not yet created |

View file

@ -0,0 +1,48 @@
# uackend specialist Prompt Variants
## Default Prompt
The **default prompt** is the agent file itself: `.opencode/agent/development/backend-specialist.md`
This is optimized for **Claude** (Anthropic models) and serves as the baseline.
## Model-Specific Variants
This directory is ready for model-specific optimizations:
| Variant | Model Family | Status | Best For |
|---------|--------------|--------|----------|
| gpt.md | GPT | 📝 Not yet created | GPT-4, GPT-4o |
| llama.md | Llama/OSS | 📝 Not yet created | Llama, Qwen, DeepSeek |
| gemini.md | Gemini | 📝 Not yet created | Gemini Pro, Gemini Ultra |
## Creating Variants
To create a model-specific variant:
1. Copy the agent file as a starting point
2. Adapt the prompt for the target model's characteristics
3. Test with the eval framework
4. Document results in this README
## Testing Variants
```bash
cd evals/framework
# Test default (agent file itself)
npm run eval:sdk -- --agent=development/backend-specialist
# Test model variants (when created)
npm run eval:sdk -- --agent=development/backend-specialist --prompt-variant=gpt
npm run eval:sdk -- --agent=development/backend-specialist --prompt-variant=llama
```
## Results
| Variant | Pass Rate | Notes |
|---------|-----------|-------|
| default (agent file) | - | Not yet tested |
| gpt | - | Not yet created |
| llama | - | Not yet created |
| gemini | - | Not yet created |

View file

@ -0,0 +1,48 @@
# devops specialist Prompt Variants
## Default Prompt
The **default prompt** is the agent file itself: `.opencode/agent/development/devops-specialist.md`
This is optimized for **Claude** (Anthropic models) and serves as the baseline.
## Model-Specific Variants
This directory is ready for model-specific optimizations:
| Variant | Model Family | Status | Best For |
|---------|--------------|--------|----------|
| gpt.md | GPT | 📝 Not yet created | GPT-4, GPT-4o |
| llama.md | Llama/OSS | 📝 Not yet created | Llama, Qwen, DeepSeek |
| gemini.md | Gemini | 📝 Not yet created | Gemini Pro, Gemini Ultra |
## Creating Variants
To create a model-specific variant:
1. Copy the agent file as a starting point
2. Adapt the prompt for the target model's characteristics
3. Test with the eval framework
4. Document results in this README
## Testing Variants
```bash
cd evals/framework
# Test default (agent file itself)
npm run eval:sdk -- --agent=development/devops-specialist
# Test model variants (when created)
npm run eval:sdk -- --agent=development/devops-specialist --prompt-variant=gpt
npm run eval:sdk -- --agent=development/devops-specialist --prompt-variant=llama
```
## Results
| Variant | Pass Rate | Notes |
|---------|-----------|-------|
| default (agent file) | - | Not yet tested |
| gpt | - | Not yet created |
| llama | - | Not yet created |
| gemini | - | Not yet created |

View file

@ -0,0 +1,48 @@
# Frontend Specialist Prompt Variants
## Default Prompt
The **default prompt** is the agent file itself: `.opencode/agent/development/frontend-specialist.md`
This is optimized for **Claude** (Anthropic models) and serves as the baseline.
## Model-Specific Variants
This directory is ready for model-specific optimizations:
| Variant | Model Family | Status | Best For |
|---------|--------------|--------|----------|
| gpt.md | GPT | 📝 Not yet created | GPT-4, GPT-4o |
| llama.md | Llama/OSS | 📝 Not yet created | Llama, Qwen, DeepSeek |
| gemini.md | Gemini | 📝 Not yet created | Gemini Pro, Gemini Ultra |
## Creating Variants
To create a model-specific variant:
1. Copy the agent file as a starting point
2. Adapt the prompt for the target model's characteristics
3. Test with the eval framework
4. Document results in this README
## Testing Variants
```bash
cd evals/framework
# Test default (agent file itself)
npm run eval:sdk -- --agent=development/frontend-specialist
# Test model variants (when created)
npm run eval:sdk -- --agent=development/frontend-specialist --prompt-variant=gpt
npm run eval:sdk -- --agent=development/frontend-specialist --prompt-variant=llama
```
## Results
| Variant | Pass Rate | Notes |
|---------|-----------|-------|
| default (agent file) | - | Not yet tested |
| gpt | - | Not yet created |
| llama | - | Not yet created |
| gemini | - | Not yet created |

View file

@ -2,41 +2,113 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
## [Unreleased]
### Added
- **Explicit Context File Validation**: New `expectedContextFiles` field in test YAML files allows explicit specification of which context files the agent must read
- Overrides auto-detection when specified
- Uses flexible pattern matching (`includes()` or `endsWith()`)
- Supports partial paths (e.g., `standards/code.md`) or full paths
- See `evals/agents/shared/tests/EXPLICIT_CONTEXT_FILES.md` for detailed guide
- Example test: `evals/agents/shared/tests/golden/02-context-loading-explicit.yaml`
### Changed
- **Context Loading Evaluator**: Now accepts optional `BehaviorExpectation` config to support explicit file validation
- Shows detection mode in evidence: "Explicit (from YAML test)" or "Auto-detect (from user message)"
- Backward compatible - existing tests work unchanged
### Documentation
- Added `evals/agents/shared/tests/EXPLICIT_CONTEXT_FILES.md` - Complete feature guide
- Added `evals/PATTERN_MATCHING_GUIDE.md` - Pattern matching reference
- Updated `evals/CREATING_TESTS.md` - Added `expectedContextFiles` documentation
- Updated `evals/README.md` - Added new feature section
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased] ## [0.5.0] - 2025-12-10
## [0.3.2] - 2025-12-09
### Changes ### Added
- fix(ci): remove [skip ci] from version bump commits (#50) - **Category-Based Agent Organization**: Agents now organized by domain in subdirectories
- `core/` - Core system agents (openagent, opencoder)
- `meta/` - Meta-level agents (system-builder)
- `development/` - Development specialists (frontend-specialist, backend-specialist, devops-specialist, codebase-agent)
- `content/` - Content creation agents (copywriter, technical-writer)
- `data/` - Data and analysis agents (data-analyst)
- `product/` - Product management agents (directory created, ready for agents)
- `learning/` - Education and coaching agents (directory created, ready for agents)
- **Category Metadata Files**: Each category has `0-category.json` documenting common subagents, tools, and context
- **Subagent Organization**: 13 subagents organized into 4 categories (code, core, system-builder, utils)
- **Local Registry Fallback**: Install script now supports local `registry.json` for development/testing
- **Enhanced Registry Validation**: Added checks for duplicate IDs and category consistency
- **Comprehensive Test Suite**: 15 automated validation tests for category system
- **Audit Tools**: Scripts to verify migration completeness and system integrity
### Changed
- **Agent File Structure**: Agents moved from flat structure to category-based organization
- Example: `.opencode/agent/openagent.md` → `.opencode/agent/core/openagent.md`
- Example: `.opencode/agent/opencoder.md` → `.opencode/agent/core/opencoder.md`
- **Registry Schema**: Updated to include category-based paths for all agents
- **Eval Framework**: Enhanced with path resolution supporting both agent IDs and category paths
- `--agent=openagent` resolves to `core/openagent` (backward compatible)
- `--agent=core/openagent` works directly (new format)
- **Documentation**: Updated all docs to reference category-based structure
- **Install Script**: Enhanced with local registry fallback for offline/development use
### Fixed
- **Frontend Specialist**: Renamed `frontend-design-agent.md` to `frontend-specialist.md` for consistency
- **Eval Directory Structure**: Archived legacy flat eval structure to `_archive/` for clarity
- **Registry Validation**: Fixed validation script to handle category-based paths correctly
### Developer Experience
- **Backward Compatibility**: Agent IDs like `openagent` still work via path resolution
- **Local Testing**: No need to push to GitHub to test registry changes
- **Clear Organization**: Agents grouped by domain make discovery easier
- **Validation Tools**: Automated tests ensure system integrity
### Migration Notes
- **Agent Paths**: Update references from flat to category-based paths
- Old: `.opencode/agent/openagent.md`
- New: `.opencode/agent/core/openagent.md`
- **Eval Framework**: Both formats work due to path resolution
- `--agent=openagent` (backward compatible)
- `--agent=core/openagent` (new format)
- **No Breaking Changes**: Path resolution maintains backward compatibility
### Technical Details
- **Files Modified**: 14+ files updated for category structure
- **Agents Organized**: 23 total agents (10 category agents, 13 subagents)
- **Test Coverage**: 15/15 validation tests passing (100%)
- **Audit Status**: 8/8 checks passing (100%)
## [0.3.1] - 2025-12-09 ## [0.3.1] - 2025-12-09
### Changes ### Fixed
- fix(ci): check only commit title for skip patterns (#46) - CI: Check only commit title for skip patterns (#46)
_No unreleased changes yet._
## [0.0.2] - 2025-11-29 ## [0.0.2] - 2025-11-29
### Added ### Added
- New `ExecutionBalanceEvaluator` in `evals/framework` to assess read vs execution ordering and ratio. - New `ExecutionBalanceEvaluator` in `evals/framework` to assess read vs execution ordering and ratio
- Contributor guide: `docs/contributing/ADDING_EVALUATOR.md` (English) describing evaluator design principles. - Contributor guide: `docs/contributing/ADDING_EVALUATOR.md` describing evaluator design principles
- Test cases under `evals/agents/openagent/tests/10-execution-balance/` (positive & negative scenarios). - Test cases under `evals/agents/openagent/tests/10-execution-balance/` (positive & negative scenarios)
### Changed ### Changed
- Framework README updated with section documenting `ExecutionBalanceEvaluator` and violation codes. - Framework README updated with section documenting `ExecutionBalanceEvaluator` and violation codes
--- ---
## Version Format ## Version Format
``` ```
v0.0.X v0.X.Y
│ │ │ │ │ │
│ │ └─ Patch version (increments with each release) │ │ └─ Patch version (bug fixes, minor changes)
│ └─── Minor version (feature additions) │ └─── Minor version (new features, non-breaking changes)
└───── Major version (breaking changes) └───── Major version (breaking changes, major milestones)
``` ```
### Version History
- **0.5.0** - Category-based agent organization system
- **0.3.1** - CI improvements
- **0.0.2** - Execution balance evaluator

Some files were not shown because too many files have changed in this diff Show more