fix: overhaul Claude Code plugin for correctness and spec compliance (#225)

- Fix critical bugs: coder-agent name (CoderAgent→coder-agent), manifest
  path in session-start.sh, /oac:setup ghost command replaced with /install-context
- Fix hooks.json: add timeout/async, add description, restore matcher
- Fix session-start.sh: dual-format output (Claude Code + Cursor/OpenCode),
  remove invalid JSON escapes for $ and backtick
- Fix agent spec compliance: disallowedTools on read-only agents, WebFetch
  on external-scout, haiku model on context-scout, example blocks on 3 agents
- Fix skill descriptions: triggering conditions only (no workflow summaries)
  per superpowers empirical testing — prevents Claude shortcutting skill content
- Add Red Flags + Rationalization tables to 4 discipline skills
- Add install-context skill + command replacing oac-setup/oac-plan/oac-add-context
- Add cleanup-tmp.sh (was missing, broke /oac:cleanup)
- Add TypeScript installer (install-context.ts/js) with profile-based download
- Update plugin.json: keywords, homepage for marketplace discoverability
- Update README: correct skill count, fix structure diagram, remove stale refs
- Remove obsolete files: FIRST-TIME-SETUP.md, INSTALL.md, QUICK-START.md,
  download-context.sh, verify-context.sh, load-config.sh, context-manager skill,
  oac-setup/oac-plan/oac-add-context commands
This commit is contained in:
Darren Hinde 2026-02-19 20:16:17 +00:00 committed by GitHub
parent 6efa2dc910
commit f84f32b7b3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
41 changed files with 2836 additions and 6739 deletions

View file

@ -7,5 +7,7 @@
"url": "https://github.com/darrenhinde"
},
"license": "MIT",
"repository": "https://github.com/darrenhinde/OpenAgentsControl"
"repository": "https://github.com/darrenhinde/OpenAgentsControl",
"homepage": "https://github.com/darrenhinde/OpenAgentsControl#readme",
"keywords": ["code-review", "tdd", "multi-agent", "context-aware", "task-management", "parallel-execution", "workflow"]
}

View file

@ -1,589 +0,0 @@
# OAC Plugin - First-Time Setup Guide
**Version**: 1.0.0
**Date**: 2026-02-16
**Audience**: First-time users
**Time**: 5-10 minutes
---
## 🎯 What You'll Accomplish
By the end of this guide, you'll have:
- ✅ OAC plugin installed and verified
- ✅ Context files downloaded
- ✅ Working development workflow
- ✅ Understanding of the 6-stage process
**No prior experience needed** — just follow the steps in order.
---
## 📋 Prerequisites
Before starting, ensure you have:
- [ ] Claude Code installed and working
- [ ] Internet connection (for downloading context files)
- [ ] A project directory to work in
---
## 🚀 Step-by-Step Setup
### Step 1: Install the Plugin
**Choose ONE method:**
#### Option A: From GitHub Marketplace (Recommended)
```bash
# Add the marketplace
/plugin marketplace add darrenhinde/OpenAgentsControl
# Install the plugin
/plugin install oac
```
**Expected output**:
```
✓ Marketplace added: darrenhinde/OpenAgentsControl
✓ Plugin installed: oac
✓ Location: ~/.claude/plugins/cache/oac/
```
#### Option B: Local Development
```bash
# Navigate to the repo
cd /path/to/OpenAgentsControl
# Start Claude with the plugin
claude --plugin-dir ./plugins/claude-code
```
**Expected output**:
```
✓ Loading plugin from: ./plugins/claude-code
✓ Plugin loaded: oac
```
---
### Step 2: Verify Installation
Run the status command to check everything is working:
```bash
/oac:status
```
**Expected output**:
```
OAC Plugin Status
=================
Plugin Version: 1.0.0
Status: ✅ Installed
Components:
- Subagents: 6 available
✓ task-manager
✓ context-scout
✓ external-scout
✓ coder-agent
✓ test-engineer
✓ code-reviewer
- Skills: 9 available
✓ using-oac
✓ context-discovery
✓ external-scout
✓ task-breakdown
✓ code-execution
✓ test-generation
✓ code-review
✓ context-manager
✓ parallel-execution
- Commands: 4 available
✓ /oac:setup
✓ /oac:help
✓ /oac:status
✓ /oac:cleanup
Context Files: ⚠️ Not installed yet
```
**✅ Success indicator**: You should see "Plugin Version: 1.0.0" and all components listed.
**❌ If you see errors**: See [Troubleshooting](#troubleshooting) section below.
---
### Step 3: Download Context Files
Context files contain coding standards, security patterns, and workflow guides that OAC uses to ensure high-quality code.
**Choose ONE option:**
#### Option A: Core Context Only (Recommended for First-Time Users)
```bash
/oac:setup --core
```
**What this downloads**: ~50 essential files (standards, workflows, patterns)
**Download time**: 30-60 seconds
**Disk space**: ~2 MB
**Expected output**:
```
Downloading OAC Context Files
==============================
Category: core
Source: https://github.com/darrenhinde/OpenAgentsControl
Downloading files...
✓ .opencode/context/core/standards/code-quality.md
✓ .opencode/context/core/standards/security-patterns.md
✓ .opencode/context/core/standards/typescript.md
✓ .opencode/context/core/workflows/6-stage-workflow.md
... (46 more files)
Summary:
========
✓ Downloaded: 50 files
✓ Location: .opencode/context/
✓ Manifest: plugins/claude-code/.context-manifest.json
Next steps:
- Run /oac:status to verify
- Start coding with /using-oac
```
#### Option B: All Context (For Advanced Users)
```bash
/oac:setup --all
```
**What this downloads**: ~200 files (includes examples, guides, plugin docs)
**Download time**: 2-3 minutes
**Disk space**: ~8 MB
---
### Step 4: Verify Context Installation
Check that context files were downloaded successfully:
```bash
/oac:status
```
**Expected output**:
```
OAC Plugin Status
=================
Plugin Version: 1.0.0
Status: ✅ Installed
Context Files: ✅ Installed
- Version: 1.0.0
- Location: .opencode/context/
- Files: 50 (core)
- Last updated: 2026-02-16
Components:
... (same as before)
```
**✅ Success indicator**: "Context Files: ✅ Installed"
**You can also verify manually**:
```bash
# Check that context directory exists
ls .opencode/context/
# Should show:
# core/ openagents-repo/ navigation.md
```
---
### Step 5: View Available Features
Get an overview of what OAC can do:
```bash
/oac:help
```
**Expected output**: A comprehensive guide showing:
- 6-stage workflow overview
- Available skills and when to use them
- Available subagents and their purposes
- Available commands
- Quick start examples
**Take 2 minutes to skim this output** — it's your reference guide.
---
### Step 6: Test the Workflow
Let's test OAC with a simple task to ensure everything works.
**Type this into Claude Code**:
```
Add a hello world function to a new file called utils.ts
```
**What should happen**:
1. **Stage 1: Analyze & Discover**
```
I'll help you add a hello world function. Let me discover relevant context first.
Invoking /context-discovery to find coding standards...
```
2. **Stage 2: Plan & Approve**
```
Plan:
- Create src/utils.ts
- Add helloWorld() function
- Follow TypeScript standards from context
Files to create:
- src/utils.ts
May I proceed with this plan? (yes/no)
```
**Type**: `yes`
3. **Stage 3: LoadContext**
```
Loading context files...
✓ Read .opencode/context/core/standards/typescript.md
✓ Read .opencode/context/core/standards/code-quality.md
```
4. **Stage 4: Execute**
```
Creating src/utils.ts...
✓ File created with helloWorld() function
```
5. **Stage 5: Validate**
```
Validating implementation...
✓ TypeScript syntax valid
✓ Follows coding standards
✓ No anti-patterns detected
```
6. **Stage 6: Complete**
```
✅ Task completed successfully!
Summary:
- Created src/utils.ts
- Added helloWorld() function
- Follows TypeScript standards
```
**✅ Success indicator**: You should see all 6 stages complete without errors.
---
## 🎓 Understanding the 6-Stage Workflow
Every task in OAC follows this workflow:
```
┌─────────────────────────────────────────────────────────────┐
│ Stage 1: Analyze & Discover │
│ - Understand what you're asking for │
│ - Find relevant context files (standards, patterns) │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Stage 2: Plan & Approve │
│ - Present implementation plan │
│ - REQUEST APPROVAL before proceeding │
│ - Confirm approach with you │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Stage 3: LoadContext │
│ - Read all discovered context files │
│ - Load coding standards, security patterns │
│ - Pre-load everything needed for execution │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Stage 4: Execute │
│ - Simple tasks (1-3 files): Direct implementation │
│ - Complex tasks (4+ files): Break down into subtasks │
│ - Follow loaded standards and patterns │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Stage 5: Validate │
│ - Run tests and validation │
│ - STOP on failure — fix before proceeding │
│ - Verify acceptance criteria met │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Stage 6: Complete │
│ - Update documentation │
│ - Summarize changes │
│ - Return results │
└─────────────────────────────────────────────────────────────┘
```
**Key points**:
- **Approval gate at Stage 2** — You control what gets implemented
- **Context loaded upfront** — Ensures consistent, high-quality code
- **Validation before completion** — Catches issues early
- **Automatic for every task** — You don't need to invoke it manually
---
## 🎯 What's Next?
Now that OAC is set up, you can:
### 1. Start Building Features
Just describe what you want to build:
```
Build a user authentication system with JWT tokens
```
OAC will:
- Discover relevant security patterns
- Break down into subtasks (if complex)
- Implement following best practices
- Generate tests
- Review code quality
### 2. Explore Advanced Features
**Context Manager** — Set up project-specific configuration:
```
/context-manager
```
**Parallel Execution** — Speed up multi-component features:
```
# Automatically used when tasks are independent
# Example: Frontend + Backend + Tests run simultaneously
```
**External Scout** — Fetch current library documentation:
```
/external-scout drizzle schemas
/external-scout react hooks
```
### 3. Learn the Skills
Each skill has a specific purpose:
| Skill | When to Use |
|-------|-------------|
| `/using-oac` | Auto-invoked for every task |
| `/context-discovery` | Find relevant standards and patterns |
| `/external-scout` | Get current library documentation |
| `/task-breakdown` | Break down complex features |
| `/code-execution` | Implement features |
| `/test-generation` | Create comprehensive tests |
| `/code-review` | Review code quality |
| `/context-manager` | Set up projects and configuration |
| `/parallel-execution` | Execute independent tasks simultaneously |
### 4. Read the Documentation
- **Quick Start**: `QUICK-START.md` — Usage examples and workflows
- **Installation**: `INSTALL.md` — Detailed installation guide
- **Full README**: `README.md` — Complete system overview
---
## 🆘 Troubleshooting
### Issue: Plugin not found
**Symptom**: `/oac:status` returns "command not found"
**Solution**:
```bash
# Check plugin list
/plugin list
# Should show "oac" in the list
# If not, reinstall:
/plugin install oac
```
---
### Issue: Context files not downloading
**Symptom**: `/oac:setup --core` fails or times out
**Solution**:
```bash
# Check internet connection
ping github.com
# Try again with verbose output
/oac:setup --core --verbose
# If still failing, check GitHub access
curl https://raw.githubusercontent.com/darrenhinde/OpenAgentsControl/main/README.md
```
---
### Issue: Skills not working
**Symptom**: `/context-discovery` returns "skill not found"
**Solution**:
```bash
# Verify skill files exist
ls ~/.claude/plugins/cache/oac/skills/
# Should show 9 directories
# If missing, reinstall plugin
/plugin uninstall oac
/plugin install oac
```
---
### Issue: Subagents not available
**Symptom**: Error when trying to invoke subagent
**Solution**:
```bash
# Check status
/oac:status
# Should show 6 subagents
# If missing, verify agent files
ls ~/.claude/plugins/cache/oac/agents/
# Should show 6 .md files
# If missing, reinstall plugin
```
---
### Issue: Workflow not auto-starting
**Symptom**: Tasks don't automatically invoke `/using-oac`
**Solution**:
```bash
# Check hooks are installed
ls ~/.claude/plugins/cache/oac/hooks/
# Should show:
# - hooks.json
# - session-start.sh
# Restart Claude Code to reload hooks
```
---
### Issue: Context files exist but not being used
**Symptom**: OAC says "context not found" but files exist
**Solution**:
```bash
# Verify context location
ls .opencode/context/core/standards/
# Should show multiple .md files
# Check manifest
cat plugins/claude-code/.context-manifest.json
# Should show version and file list
# If manifest missing, re-run setup
/oac:setup --core --force
```
---
## ✅ Success Checklist
Before you finish, verify:
- [ ] `/oac:status` shows "Plugin Version: 1.0.0"
- [ ] `/oac:status` shows "Context Files: ✅ Installed"
- [ ] `/oac:status` shows 6 subagents, 9 skills, 4 commands
- [ ] `.opencode/context/` directory exists with files
- [ ] Test task completed successfully (hello world example)
- [ ] You understand the 6-stage workflow
- [ ] You know where to find help (`/oac:help`)
**All checked?** 🎉 **You're ready to build with OAC!**
---
## 📚 Additional Resources
### Quick Reference
| Command | Purpose |
|---------|---------|
| `/oac:status` | Check installation status |
| `/oac:help` | View comprehensive help |
| `/oac:setup --core` | Download context files |
| `/oac:cleanup` | Clean up old temporary files |
### Documentation
- **This guide**: First-time setup (you are here)
- **QUICK-START.md**: Usage examples and workflows
- **INSTALL.md**: Detailed installation guide
- **README.md**: Complete system overview
### Support
- **Issues**: https://github.com/darrenhinde/OpenAgentsControl/issues
- **Discussions**: https://github.com/darrenhinde/OpenAgentsControl/discussions
- **Status Check**: Run `/oac:status` for diagnostic information
---
## 🎉 Welcome to OAC!
You're now ready to build high-quality, context-aware code with OpenAgents Control.
**Remember**:
- OAC automatically guides you through the 6-stage workflow
- Approval gates keep you in control
- Context files ensure consistent, high-quality code
- Skills and subagents handle the complexity
**Happy coding!** 🚀
---
**Version**: 1.0.0
**Last Updated**: 2026-02-16
**Status**: Production Ready

View file

@ -1,239 +0,0 @@
# OAC Plugin - Installation Guide
Complete guide to install and configure the OAC (OpenAgents Control) plugin for Claude Code.
## 🚀 Quick Install
### Method 1: From GitHub (Recommended)
```bash
# Add the marketplace
/plugin marketplace add darrenhinde/OpenAgentsControl
# Install the plugin
/plugin install oac
```
### Method 2: Local Development
```bash
# Navigate to the repo
cd /path/to/OpenAgentsControl
# Start Claude with the plugin
claude --plugin-dir ./plugins/claude-code
```
## 📥 Setup Context Files
**IMPORTANT**: After installation, download context files to enable context-aware development.
### Option 1: Download Core Context (Recommended)
```bash
/oac:setup --core
```
Downloads essential standards and workflows (~50 files).
### Option 2: Download All Context
```bash
/oac:setup --all
```
Downloads all context including examples and guides (~200 files).
### Option 3: Download Specific Category
```bash
/oac:setup --category=standards
```
Available categories:
- `core` - Essential standards and workflows
- `openagents-repo` - OAC-specific guides and patterns
- `plugins` - Plugin development guides
- `skills` - Skill creation and usage
## ✅ Verification
After installation and setup, verify everything works:
### 1. Check Plugin Status
```bash
/oac:status
```
You should see:
- ✅ Plugin version
- ✅ Context installed
- ✅ Available subagents (6)
- ✅ Available skills (9)
- ✅ Available commands (4)
### 2. View Available Features
```bash
/oac:help
```
Shows the complete usage guide with all skills, subagents, and commands.
### 3. Test the Workflow
```bash
# Start a simple task to test the workflow
"Add a hello world function"
```
Claude should automatically invoke the `/using-oac` skill and guide you through the 6-stage workflow.
## 📦 What Gets Installed
When you install the plugin, Claude Code sets up:
```
~/.claude/plugins/cache/oac/
├── .claude-plugin/plugin.json # Plugin manifest
├── agents/ # 6 custom subagents
│ ├── task-manager.md
│ ├── context-scout.md
│ ├── external-scout.md
│ ├── coder-agent.md
│ ├── test-engineer.md
│ └── code-reviewer.md
├── skills/ # 9 workflow skills
│ ├── using-oac/SKILL.md
│ ├── context-discovery/SKILL.md
│ ├── external-scout/SKILL.md
│ ├── task-breakdown/SKILL.md
│ ├── code-execution/SKILL.md
│ ├── test-generation/SKILL.md
│ ├── code-review/SKILL.md
│ ├── context-manager/SKILL.md
│ └── parallel-execution/SKILL.md
├── commands/ # 4 user commands
│ ├── oac-setup.md
│ ├── oac-help.md
│ ├── oac-status.md
│ └── oac-cleanup.md
├── hooks/ # SessionStart automation
│ ├── hooks.json
│ └── session-start.sh
└── scripts/ # Utility scripts
├── download-context.sh
└── verify-context.sh
```
After running `/oac:setup`, context files are downloaded to your project:
```
your-project/
└── .opencode/
└── context/
├── core/ # Standards, workflows, patterns
├── openagents-repo/ # OAC-specific guides
├── plugins/ # Plugin development
└── skills/ # Skill creation
```
## 🏗️ Architecture Overview
OAC uses a **flattened delegation hierarchy** optimized for Claude Code:
### Traditional OAC (Nested)
```
Main Agent
└─> TaskManager
└─> CoderAgent
└─> ContextScout (❌ Not allowed in Claude Code)
```
### Claude Code OAC (Flattened)
```
Main Agent (orchestrated by /using-oac skill)
├─> task-manager subagent
├─> context-scout subagent
├─> coder-agent subagent
├─> test-engineer subagent
└─> code-reviewer subagent
```
**Key Difference**:
- Skills guide the main agent's workflow
- Main agent invokes subagents directly (no nesting)
- Context is pre-loaded in Stage 3 (no nested ContextScout calls)
## 🔧 Troubleshooting
### Plugin not found
```bash
# Check plugin list
/plugin list
# Verify installation directory
ls ~/.claude/plugins/cache/oac/
```
### Context not installed
```bash
# Check status
/oac:status
# If context missing, run setup
/oac:setup --core
```
### Skills not working
```bash
# Verify skill files exist
ls ~/.claude/plugins/cache/oac/skills/
# Restart Claude Code
# Try with verbose logging
claude --plugin-dir ./plugins/claude-code --verbose
```
### Subagents not available
```bash
# Check status
/oac:status
# Verify agent files
ls ~/.claude/plugins/cache/oac/agents/
# Should show 6 .md files
```
### Download fails
```bash
# Try core context first (smaller)
/oac:setup --core
# Check internet connection
# Verify GitHub access
# Manual fallback (see /oac:setup output for instructions)
```
## 🎯 Next Steps
After successful installation:
1. **Read the Quick Start**: See `QUICK-START.md` for usage examples
2. **Explore the help**: Run `/oac:help` for detailed workflow guide
3. **Start building**: Let the `/using-oac` skill guide your development
4. **Review context**: Explore `.opencode/context/` to understand available standards
## 🆘 Need Help?
- **Issues**: https://github.com/darrenhinde/OpenAgentsControl/issues
- **Discussions**: https://github.com/darrenhinde/OpenAgentsControl/discussions
- **Status Check**: Run `/oac:status` for diagnostic information
---
**Version**: 1.0.0
**Last Updated**: 2026-02-16

View file

@ -1,587 +0,0 @@
# OAC Plugin - Quick Start Guide
**Version**: 1.0.0
**Date**: 2026-02-16
**Status**: ✅ Production Ready
---
## 🚀 Getting Started (3 Steps)
### 1. Install the Plugin
```bash
# From GitHub marketplace
/plugin marketplace add darrenhinde/OpenAgentsControl
/plugin install oac
# OR for local development
claude --plugin-dir ./plugins/claude-code
```
### 2. Download Context Files
```bash
# Download core context (recommended)
/oac:setup --core
# OR download everything
/oac:setup --all
```
### 3. Verify Installation
```bash
# Check status
/oac:status
# View help
/oac:help
```
**You're ready!** Start any development task and the `/using-oac` skill will automatically guide you.
---
## 📋 Quick Reference: 9 Skills
### 1. `/using-oac` - Main Workflow Orchestrator
**Auto-invoked on every task** to ensure context-aware development.
**6-Stage Workflow**:
1. **Analyze & Discover** - Understand task, find context files
2. **Plan & Approve** - Present plan, REQUEST APPROVAL
3. **LoadContext** - Pre-load all context files (internal + external)
4. **Execute** - Implement (direct or via task breakdown)
5. **Validate** - Run tests, STOP on failure
6. **Complete** - Update docs, summarize
**When to use**: Automatically invoked (you don't need to call it manually).
---
### 2. `/context-discovery` - Find Relevant Context
Guides the main agent to use the `context-scout` subagent for discovering standards and patterns.
**Usage**:
```
/context-discovery authentication feature
```
**What it does**:
- Searches `.opencode/context/` for relevant files
- Prioritizes by relevance (Critical → High → Medium)
- Returns list of files to load
**Example output**:
```
Critical:
- .opencode/context/core/standards/security.md
- .opencode/context/core/patterns/authentication.md
High:
- .opencode/context/core/standards/typescript.md
```
---
### 3. `/external-scout` - Fetch External Library Docs
Guides the main agent to use the `external-scout` subagent for fetching current API documentation.
**Usage**:
```
/external-scout drizzle schemas
/external-scout react hooks
/external-scout express middleware
```
**What it does**:
- Fetches current documentation from Context7 and other sources
- Caches results in `.tmp/external-context/` (fresh for 7 days)
- Returns file paths to load
- Ensures you're using current API patterns (not outdated training data)
**Example output**:
```json
{
"status": "success",
"package": "drizzle",
"topic": "schemas",
"files": [".tmp/external-context/drizzle/schemas.md"],
"message": "Documentation cached. Load file to access current API patterns."
}
```
**Why it matters**: Training data is outdated. External libraries change their APIs, deprecate features, and introduce new patterns. ExternalScout ensures you're implementing with current, correct patterns.
---
### 4. `/task-breakdown` - Decompose Complex Features
Guides the main agent to use the `task-manager` subagent for breaking down complex tasks.
**Usage**:
```
/task-breakdown user authentication system
```
**What it does**:
- Breaks feature into atomic subtasks (1-2 hours each)
- Creates dependency graph
- Generates subtask JSON files in `.tmp/tasks/`
- Enables parallel execution where possible
**Example output**:
```
Subtasks created:
1. JWT service implementation
2. Auth middleware (depends on #1)
3. Login endpoint (depends on #1, #2)
4. Refresh token logic (depends on #1)
5. Integration tests (depends on all)
```
---
### 5. `/code-execution` - Implement Features
Guides the main agent to use the `coder-agent` subagent for implementing code.
**Usage**:
```
/code-execution implement JWT service
```
**What it does**:
- Implements features following loaded context
- Applies coding standards and patterns
- Runs self-review before completion
- Updates subtask status if part of task breakdown
**Self-Review Checks**:
- ✅ Type & import validation
- ✅ Anti-pattern scan (console.log, TODO, hardcoded secrets)
- ✅ Acceptance criteria verification
- ✅ External library verification
---
### 6. `/test-generation` - Create Comprehensive Tests
Guides the main agent to use the `test-engineer` subagent for generating tests.
**Usage**:
```
/test-generation authentication service
```
**What it does**:
- Generates tests following TDD principles
- Covers happy paths, edge cases, error handling
- Follows test standards from context
- Ensures test isolation and clarity
**Test Coverage**:
- Unit tests for individual functions
- Integration tests for workflows
- Edge cases and error scenarios
- Security validation tests
---
### 7. `/code-review` - Review Code Quality
Guides the main agent to use the `code-reviewer` subagent for reviewing code.
**Usage**:
```
/code-review src/auth/
```
**What it does**:
- Reviews code for quality and standards compliance
- Checks security patterns
- Identifies anti-patterns
- Suggests improvements
**Review Areas**:
- Code quality and readability
- Security vulnerabilities
- Performance issues
- Standards compliance
- Test coverage
---
### 8. `/context-manager` - Manage Context & Configuration
Manage context files, configuration, and project-specific settings.
**Usage**:
```
/context-manager
```
**What it does**:
- Set up new projects with OAC context files
- Configure context sources and download preferences
- Integrate external task systems (SpecKit, Linear, Jira, custom)
- Manage personal context files and templates
- Troubleshoot context loading or configuration issues
- Update or refresh downloaded context files
**Use when**:
- Setting up a new project
- Configuring .oac file
- Integrating with external task management
- Managing personal templates and preferences
---
### 9. `/parallel-execution` - Execute Tasks in Parallel
Execute multiple independent tasks simultaneously to reduce implementation time.
**Usage**:
```
# Automatically used when task-manager marks tasks with parallel:true
# Or invoke manually for independent work
```
**What it does**:
- Execute multiple independent tasks simultaneously
- Dramatically reduce implementation time for multi-component features
- Coordinate parallel work streams (frontend + backend + tests)
- Monitor progress and handle failures gracefully
**Use when**:
- Multiple independent tasks with no dependencies
- Multi-component features (frontend + backend + tests)
- Time-sensitive delivery
- Batch operations (converting files, running tests)
**Time savings**: 50-80% reduction for multi-component features
---
## 🎮 Quick Reference: 4 Commands
### 1. `/oac:setup` - Download Context Files
**Usage**:
```bash
/oac:setup # Interactive mode
/oac:setup --core # Core context only (~50 files)
/oac:setup --all # All context (~200 files)
/oac:setup --category=standards # Specific category
```
**What it downloads**:
- Coding standards and conventions
- Architecture patterns
- Security guidelines
- Workflow guides
- Domain-specific documentation
**Output**: Creates `.opencode/context/` and `.context-manifest.json`
---
### 2. `/oac:help` - Show Usage Guide
**Usage**:
```bash
/oac:help # General help
/oac:help context-discovery # Skill-specific help
```
**What it shows**:
- 6-stage workflow overview
- Available subagents and when to use them
- Available skills and usage examples
- Available commands
- Quick start examples
- Troubleshooting guide
---
### 3. `/oac:status` - Check Installation Status
**Usage**:
```bash
/oac:status
```
**What it shows**:
- Plugin version
- Context installation status
- Active sessions count
- Available subagents (6)
- Available skills (9)
- Available commands (4)
- Recommendations for cleanup or setup
---
### 4. `/oac:cleanup` - Clean Up Temporary Files
**Usage**:
```bash
/oac:cleanup # Interactive mode
/oac:cleanup --force # Skip confirmation
/oac:cleanup --session-days=3 # Clean sessions older than 3 days
/oac:cleanup --task-days=14 # Clean tasks older than 14 days
/oac:cleanup --external-days=3 # Clean external context older than 3 days
```
**What it cleans**:
- Old session files from `.tmp/sessions/`
- Completed task files from `.tmp/tasks/`
- Cached external documentation from `.tmp/external-context/`
**Default retention**:
- Sessions: 7 days
- Completed tasks: 30 days
- External context: 7 days
**Example**:
```bash
# Clean with defaults
/oac:cleanup
# Aggressive cleanup
/oac:cleanup --session-days=3 --task-days=14 --external-days=3 --force
```
---
## 💡 Example Workflows
### Example 1: Simple Feature (Direct Implementation)
**Task**: "Add a login endpoint"
**Workflow**:
```
1. Analyze & Discover
- Understand: Need POST /api/login endpoint
- Invoke /context-discovery → finds API standards, security patterns
2. Plan & Approve
- Plan: Create endpoint in src/api/auth.ts
- Files: auth.ts, auth.test.ts, api-docs.md
- REQUEST APPROVAL ← User approves
3. LoadContext
- Read API standards
- Read security patterns
- Read TypeScript conventions
- (If using external libs) Invoke /external-scout for current API docs
4. Execute
- Implement endpoint directly (simple task)
- Follow loaded standards
5. Validate
- Run tests
- Verify acceptance criteria
6. Complete
- Update API docs
- Summarize changes
```
**Time**: ~15-30 minutes
---
### Example 2: Complex Feature (Task Breakdown)
**Task**: "Build a complete authentication system"
**Workflow**:
```
1. Analyze & Discover
- Understand: Full auth system (JWT, refresh, middleware, endpoints)
- Invoke /context-discovery → finds security, API, TypeScript standards
2. Plan & Approve
- Plan: Multi-component system, suggest task breakdown
- Complexity: 4+ files, >30 min
- REQUEST APPROVAL ← User approves
3. LoadContext
- Read security patterns
- Read API standards
- Read TypeScript conventions
- Read test standards
- Invoke /external-scout for any external libraries (e.g., JWT library, database ORM)
4. Execute
- Invoke /task-breakdown → creates subtasks:
* Subtask 1: JWT service (core logic)
* Subtask 2: Auth middleware (depends on #1)
* Subtask 3: Login endpoint (depends on #1, #2)
* Subtask 4: Refresh endpoint (depends on #1)
* Subtask 5: Integration tests (depends on all)
- For each subtask:
* Invoke /code-execution
* Implement following loaded context
* Run self-review
* Mark subtask complete
5. Validate
- Run all integration tests
- Verify system works end-to-end
- STOP if any test fails
6. Complete
- Update API documentation
- Update security documentation
- Summarize all changes
```
**Time**: ~2-4 hours (broken into 1-2 hour subtasks)
---
### Example 3: Using Subagents Directly
**Task**: "Review and test the authentication system"
**Workflow**:
```
# Step 1: Discover context
Use the context-scout subagent to find:
- Security review checklists
- Test standards
- Code quality guidelines
# Step 2: Review code
Use the code-reviewer subagent to review:
- src/auth/ directory
- Check security patterns
- Identify issues
# Step 3: Generate tests
Use the test-engineer subagent to create:
- Unit tests for JWT service
- Integration tests for auth flow
- Security validation tests
# Step 4: Verify
Run tests and confirm all pass
```
---
## 🏗️ Architecture: Flattened Delegation
OAC for Claude Code uses a **flattened hierarchy** (no nested subagent calls):
### ❌ Traditional OAC (Not Allowed in Claude Code)
```
Main Agent
└─> TaskManager
└─> CoderAgent
└─> ContextScout (nested - not allowed)
```
### ✅ Claude Code OAC (Flattened)
```
Main Agent (orchestrated by /using-oac skill)
├─> task-manager subagent
├─> context-scout subagent
├─> coder-agent subagent
├─> test-engineer subagent
└─> code-reviewer subagent
```
**How it works**:
1. **Skills** guide the main agent's workflow (when to invoke which subagent)
2. **Main agent** invokes subagents directly (no nesting)
3. **Context** is pre-loaded in Stage 3 (no nested ContextScout calls during execution)
4. **Subagents** return results to main agent for orchestration
---
## 🆘 Troubleshooting
### "Context files not found"
```bash
# Download context
/oac:setup --core
# Verify installation
/oac:status
```
### "Subagent not available"
```bash
# Check status
/oac:status
# Should show 6 subagents
# If missing, reinstall plugin
```
### "Approval not requested"
```bash
# This is a bug - OAC should ALWAYS request approval in Stage 2
# Please report at: https://github.com/darrenhinde/OpenAgentsControl/issues
```
### "Nested subagent call error"
```bash
# Claude Code doesn't support nested calls
# Use skills to orchestrate, not subagents calling subagents
# The /using-oac skill handles this automatically
```
### "Tests failing in Stage 5"
```bash
# This is expected behavior - OAC stops on test failure
# Fix the failing tests before proceeding
# Re-run validation after fixes
```
---
## 🎯 Best Practices
### 1. Context First, Code Second
Always let the workflow discover and load context before implementing. This ensures your code follows project standards.
### 2. Approve Before Execution
Review the plan in Stage 2 carefully. Once approved, OAC will execute automatically.
### 3. Break Down Complex Tasks
For features with 4+ files or >30 min work, use task breakdown for better tracking and parallel execution.
### 4. Trust the Self-Review
CoderAgent runs comprehensive checks before completion. If it passes, the code is ready.
### 5. Use Status Commands
Run `/oac:status` regularly to check installation and active sessions.
---
## 📚 Learn More
- **Installation**: See `INSTALL.md` for detailed setup
- **Full Help**: Run `/oac:help` for comprehensive guide
- **Architecture**: See `README.md` for system overview
- **Context Files**: Explore `.opencode/context/` after running `/oac:setup`
---
## 🔗 Quick Links
| Resource | Command/Link |
|----------|--------------|
| Check Status | `/oac:status` |
| Get Help | `/oac:help` |
| Download Context | `/oac:setup --core` |
| GitHub Issues | https://github.com/darrenhinde/OpenAgentsControl/issues |
| Discussions | https://github.com/darrenhinde/OpenAgentsControl/discussions |
---
**Ready to build!** 🎉
Start any development task and let the `/using-oac` skill guide you through context-aware development.

View file

@ -6,7 +6,7 @@ OpenAgents Control (OAC) - Multi-agent orchestration and automation for Claude C
OpenAgents Control brings powerful multi-agent capabilities to Claude Code through a **skills + subagents architecture**:
- **9 Skills** orchestrate workflows and guide the main agent through multi-stage processes
- **8 Skills** orchestrate workflows and guide the main agent through multi-stage processes
- **6 Subagents** execute specialized tasks (context discovery, task breakdown, code implementation, testing, review)
- **4 Commands** provide setup, status, help, and cleanup functionality
- **Flat delegation hierarchy** - only the main agent can invoke subagents (no nested calls)
@ -23,43 +23,72 @@ OpenAgents Control brings powerful multi-agent capabilities to Claude Code throu
## 📦 Installation
### Option 1: From Marketplace (Recommended)
### Option 1: From Claude Code Marketplace (Recommended)
Install directly from the Claude Code marketplace:
```bash
# Add the OpenAgents Control marketplace
/plugin marketplace add darrenhinde/OpenAgentsControl
# Add the OpenAgents Control marketplace repository
/plugin marketplace add https://github.com/darrenhinde/OpenAgentsControl
# Install the plugin
# Install the OAC plugin
/plugin install oac
# Download context files (interactive profile selection)
/install-context
```
> **First time?** Run `/install-context` to download context files, then `/oac:status` to verify.
**That's it!** The plugin is now installed and ready to use.
### Option 2: Local Development
For plugin development or testing:
```bash
# Clone the repo
# Clone the repository
git clone https://github.com/darrenhinde/OpenAgentsControl.git
cd OpenAgentsControl
# Load plugin locally
claude --plugin-dir ./plugins/claude-code
# Download context files
/install-context
```
## 🚀 Quick Start
After installation, download context files and start using OAC:
After installation, the plugin is ready to use:
```bash
# Download context files from GitHub
/oac:setup
# Verify installation
/oac:status
# Get help and usage guide
/oac:help
# Start a development task (using-oac skill auto-invokes)
"Build a user authentication system"
```
The **using-oac** skill is automatically invoked when you start a development task, guiding you through the 6-stage workflow.
The **using-oac** skill is automatically invoked when you start a development task, guiding you through the 6-stage workflow with parallel execution for 5x faster feature development.
### Context Files
Context files are automatically downloaded during installation via `/install-context`. You can update or change profiles anytime:
```bash
# Install different profile
/install-context --profile=extended
# Force reinstall
/install-context --force
# Preview what would be installed
/install-context --dry-run --profile=all
```
## 📚 Available Skills
@ -112,13 +141,6 @@ Guide for performing thorough code reviews with security and quality analysis.
**Invokes**: `code-reviewer` subagent via `context: fork`
### context-manager
Manage context files, configuration, and project-specific settings. Set up projects, configure context sources, and integrate external task systems.
**Usage**: `/context-manager`
**Use when**: Setting up projects, configuring context sources, managing personal task systems
### parallel-execution
Execute multiple independent tasks in parallel to dramatically reduce implementation time for multi-component features.
@ -170,10 +192,10 @@ Perform thorough code review with security analysis, quality checks, and actiona
User-invocable commands for setup and status:
### /oac:setup
### /install-context
Download context files from the OpenAgents Control GitHub repository.
**Usage**: `/oac:setup [--core|--all|--category=<name>]`
**Usage**: `/install-context [--core|--all|--category=<name>]`
**Options**:
- `--core` - Download only core context files (standards, workflows, patterns)
@ -306,14 +328,15 @@ The plugin uses context files from the main OpenAgents Control repository.
plugins/claude-code/
├── .claude-plugin/
│ └── plugin.json # Plugin metadata
├── agents/ # Custom subagents (6 files)
├── agents/ # Custom subagents (7 files)
│ ├── task-manager.md
│ ├── context-scout.md
│ ├── context-manager.md
│ ├── external-scout.md
│ ├── coder-agent.md
│ ├── test-engineer.md
│ └── code-reviewer.md
├── skills/ # Workflow skills (9 files)
├── skills/ # Workflow skills (8 files)
│ ├── using-oac/SKILL.md
│ ├── context-discovery/SKILL.md
│ ├── external-scout/SKILL.md
@ -321,10 +344,10 @@ plugins/claude-code/
│ ├── code-execution/SKILL.md
│ ├── test-generation/SKILL.md
│ ├── code-review/SKILL.md
│ ├── context-manager/SKILL.md
│ ├── install-context/SKILL.md
│ └── parallel-execution/SKILL.md
├── commands/ # User commands (4 files)
│ ├── oac-setup.md
│ ├── install-context.md
│ ├── oac-help.md
│ ├── oac-status.md
│ └── oac-cleanup.md
@ -332,14 +355,15 @@ plugins/claude-code/
│ ├── hooks.json
│ └── session-start.sh
├── scripts/ # Utility scripts
│ ├── download-context.sh
│ └── verify-context.sh
│ ├── install-context.ts # Context installer (TypeScript)
│ ├── install-context.js # Context installer (JS fallback)
│ └── cleanup-tmp.sh # Temporary file cleanup
└── .context-manifest.json # Downloaded context tracking
```
### Context Files
Context files are downloaded from the main repository via `/oac:setup`:
Context files are downloaded from the main repository via `/install-context`:
```
.opencode/context/
@ -445,8 +469,6 @@ Create `hooks/hooks.json`:
## 📖 Documentation
- [Installation Guide](INSTALL.md)
- [Quick Start Guide](QUICK-START.md)
- [Main Documentation](../.opencode/docs/)
- [Context System](../docs/context-system/)
- [Planning Documents](../docs/planning/)
@ -469,8 +491,8 @@ MIT License - see [LICENSE](../LICENSE) for details.
### Phase 1: Foundation ✅ COMPLETE
- ✅ Plugin structure
- ✅ 6 custom subagents (task-manager, context-scout, external-scout, coder-agent, test-engineer, code-reviewer)
- ✅ 9 workflow skills (using-oac, context-discovery, external-scout, task-breakdown, code-execution, test-generation, code-review, context-manager, parallel-execution)
- ✅ 4 user commands (/oac:setup, /oac:help, /oac:status, /oac:cleanup)
- ✅ 8 workflow skills (using-oac, context-discovery, external-scout, task-breakdown, code-execution, test-generation, code-review, install-context, parallel-execution)
- ✅ 4 user commands (/install-context, /oac:help, /oac:status, /oac:cleanup)
- ✅ SessionStart hook for auto-loading using-oac skill
- ✅ Context download and verification scripts
- ✅ Flat delegation hierarchy (skills invoke subagents via context: fork)

View file

@ -1,7 +1,22 @@
---
name: code-reviewer
description: Reviews code for security, correctness, and quality against project standards
description: |
Review code for security vulnerabilities, correctness, and quality. Use after implementation is complete and before committing.
Examples:
<example>
Context: coder-agent has finished implementing a new auth service.
user: "The auth service is done, can you check it?"
assistant: "I'll run the code-review skill to have code-reviewer validate it before we commit."
<commentary>Implementation is complete — code-reviewer validates before commit.</commentary>
</example>
<example>
Context: User is about to merge a PR with database query changes.
user: "Review src/db/queries.ts before I merge"
assistant: "Using code-reviewer to check for SQL injection and correctness issues."
<commentary>Explicit review request on specific files — code-reviewer is the right agent.</commentary>
</example>
tools: Read, Glob, Grep
disallowedTools: Write, Edit, Bash, Task
model: sonnet
---

View file

@ -1,6 +1,20 @@
---
name: CoderAgent
description: Execute coding subtasks with self-review and quality validation
name: coder-agent
description: |
Execute a single coding subtask from a JSON task file. Use when a subtask_NN.json file exists with acceptance criteria and deliverables.
Examples:
<example>
Context: The task-manager has created subtask_01.json for a JWT service.
user: "Implement the JWT service subtask"
assistant: "I'll delegate this to the coder-agent with the subtask JSON."
<commentary>A subtask JSON file exists with clear criteria — coder-agent is the right choice.</commentary>
</example>
<example>
Context: User asks to fix a bug in auth middleware.
user: "Fix the token expiry bug in auth.middleware.ts"
assistant: "Let me use the code-execution skill to handle this via coder-agent."
<commentary>A concrete implementation task with a specific file — coder-agent executes it.</commentary>
</example>
tools: Read, Write, Edit, Glob, Grep
model: sonnet
---

View file

@ -1,8 +1,23 @@
---
name: context-scout
description: Discovers and recommends context files from project context directories ranked by priority for context-aware development
description: |
Discover relevant context files, coding standards, and project conventions. Use before implementation begins to find the right standards to follow.
Examples:
<example>
Context: User wants to build a new authentication feature.
user: "Build me a JWT authentication system"
assistant: "Before implementing, I'll use context-scout to find the security and auth standards for this project."
<commentary>New feature starting — context-scout finds the relevant standards first.</commentary>
</example>
<example>
Context: coder-agent needs to know the project's TypeScript conventions.
user: "What TypeScript patterns should I follow here?"
assistant: "Let me use context-scout to discover the TypeScript standards in this project's context."
<commentary>Standards needed before coding — context-scout navigates the context system to find them.</commentary>
</example>
tools: Read, Glob, Grep
model: sonnet
disallowedTools: Write, Edit, Bash, Task
model: haiku
---
# ContextScout
@ -62,7 +77,8 @@ model: sonnet
2. **Check .claude/context** - Claude Code default location
3. **Check context** - Simple root-level directory
4. **Check .opencode/context** - OpenCode/OAC default location
5. **Fallback** - If none found, report error (don't assume location)
5. **Check plugin context** - `plugins/claude-code/context/` (installed via /install-context)
6. **Fallback** - If none found, report error (don't assume location)
**Process**:
```
@ -83,8 +99,12 @@ Glob: context/navigation.md
Glob: .opencode/context/navigation.md
→ If exists, use .opencode/context
# Try plugin context (installed via /install-context)
Glob: plugins/claude-code/context/navigation.md
→ If exists, use plugins/claude-code/context
# If none found
→ Return error: "No context root found. Run /oac:setup to download context files."
→ Return error: "No context root found. Run /install-context to download context files."
```
**Output**: Context root path (e.g., `.claude/context`, `context`, or `.opencode/context`)

View file

@ -1,7 +1,7 @@
---
name: external-scout
description: Fetches external library and framework documentation from Context7 API and other sources, caching results for offline use
tools: Read, Write, Bash
tools: Read, Write, Bash, WebFetch
model: haiku
---

View file

@ -0,0 +1,110 @@
---
name: install-context
description: Install OpenAgents Control context files from registry with interactive profile selection
argument-hint: [--profile=<profile>] [--force] [--dry-run] [--verbose]
---
# Install Context Command
$ARGUMENTS
## Overview
Install context files from the OpenAgents Control registry with interactive profile selection.
**Available profiles**: essential, standard, extended, specialized, all
**Options**:
- `--profile=<profile>` - Install specific profile (skips interactive selection)
- `--force` - Force reinstall even if already installed
- `--dry-run` - Preview what would be installed without installing
- `--verbose` - Show detailed installation progress
- `--categories=<ids>` - Install specific context components (comma-separated)
---
## Usage
### Interactive Mode (Recommended)
```
/install-context
```
This will:
1. Check current installation status
2. Ask which profile to install
3. Confirm before proceeding
4. Run installation
5. Verify files
6. Offer cleanup options
### Direct Mode (With Options)
```
# Install essential profile
/install-context --profile=essential
# Force reinstall standard profile
/install-context --profile=standard --force
# Preview extended profile
/install-context --profile=extended --dry-run
# Install with verbose output
/install-context --profile=standard --verbose
# Install specific components
/install-context --categories=core-standards,openagents-repo
```
---
## How It Works
This command invokes the `install-context` skill which:
1. **Checks current installation** - Shows what's already installed (if any)
2. **Asks for profile** - Interactive selection or uses `--profile` option
3. **Confirms installation** - Shows summary and asks for confirmation
4. **Runs TypeScript installer** - Executes `scripts/install-context.ts`
5. **Verifies installation** - Checks files exist and manifest is created
6. **Offers cleanup** - Asks about cleaning up temporary files
---
## Profile Descriptions
**essential** (Recommended for getting started)
- Minimal components for basic functionality
- ~4 components, ~30 seconds download
- Includes: core patterns, project context, navigation
**standard** (Recommended for most users)
- Standard components for typical use
- ~12 components, ~2 minutes download
- Includes: essential + development workflows + common patterns
**extended** (For advanced features)
- Extended components for advanced features
- ~30 components, ~5 minutes download
- Includes: standard + specialized domains + advanced patterns
**specialized** (For specific domains)
- Specialized components for specific domains
- ~50 components, ~10 minutes download
- Includes: extended + domain-specific contexts (UI, data, product, etc.)
**all** (Complete installation)
- All available context components
- ~191 components, ~20 minutes download
- Includes: Everything in the registry
---
## Examples
### Example 1: First-time Installation
```
User: /install-context

View file

@ -1,705 +0,0 @@
---
name: oac:add-context
description: Add context files from GitHub, worktrees, local files, or URLs to your project
argument-hint: [source] [options]
---
# Add Context
Add context files to your project from various sources: **$ARGUMENTS**
---
## What This Command Does
The `/oac:add-context` command helps you add context files from:
1. **GitHub repositories** - Team or company standards
2. **Git worktrees** - Local development branches
3. **Local files** - Project-specific patterns
4. **URLs** - Remote documentation
This command invokes the **context-manager** subagent to:
- Discover your context root location
- Fetch/copy files from the source
- Validate file format and structure
- Update navigation for discoverability
- Verify files are accessible via `/context-discovery`
---
## Supported Sources
### 1. GitHub Repository
**Format**: `github:owner/repo[/path][#ref]`
**Examples**:
```bash
# Add from GitHub repo (main branch)
/oac:add-context github:acme-corp/standards
# Add specific path
/oac:add-context github:acme-corp/standards/security
# Add specific branch/tag
/oac:add-context github:acme-corp/standards#v1.0.0
# Add with category
/oac:add-context github:acme-corp/standards --category=team
```
**What it does**:
- Clones repository (shallow, single branch)
- Copies specified path to context root
- Validates markdown files
- Updates navigation
- Cleans up temporary clone
---
### 2. Git Worktree
**Format**: `worktree:/path/to/worktree[/subdir]`
**Examples**:
```bash
# Add from worktree
/oac:add-context worktree:../team-context
# Add specific subdirectory
/oac:add-context worktree:../team-context/standards
# Add with category
/oac:add-context worktree:../team-context/security --category=team
```
**What it does**:
- Validates worktree exists (.git directory)
- Copies files from worktree
- Validates markdown files
- Updates navigation
- Preserves worktree (no cleanup)
**Use case**: Perfect for team members working on shared context in a separate worktree
---
### 3. Local File or Directory
**Format**: `file:./path/to/file-or-dir`
**Examples**:
```bash
# Add single file
/oac:add-context file:./docs/patterns/auth-flow.md
# Add directory
/oac:add-context file:./docs/patterns/
# Add with category and priority
/oac:add-context file:./docs/security.md --category=custom --priority=critical
```
**What it does**:
- Validates file/directory exists
- Copies to context root
- Validates markdown format
- Updates navigation
- Preserves original files
**Use case**: Add project-specific patterns or documentation to context
---
### 4. URL
**Format**: `url:https://example.com/path/to/file.md`
**Examples**:
```bash
# Add from URL
/oac:add-context url:https://example.com/standards/security.md
# Add with category
/oac:add-context url:https://raw.githubusercontent.com/owner/repo/main/doc.md --category=external
```
**What it does**:
- Downloads file via HTTP/HTTPS
- Validates markdown format
- Saves to context root
- Updates navigation
**Use case**: Add public documentation or standards from the web
---
## Options
### `--category=<name>`
**Purpose**: Specify target category for context files
**Default**: `custom`
**Examples**:
```bash
# Add to team category
/oac:add-context github:acme-corp/standards --category=team
# Add to custom category
/oac:add-context file:./docs/patterns.md --category=custom
# Add to core category (override defaults)
/oac:add-context file:./security.md --category=core
```
**Categories**:
- `core` - Essential standards and workflows
- `team` - Team/company-specific context
- `custom` - Project-specific overrides
- `external` - External library documentation
- `personal` - Personal templates and patterns
---
### `--priority=<level>`
**Purpose**: Set priority level for context files
**Default**: `medium`
**Levels**:
- `critical` - Must-read files for all tasks
- `high` - Strongly recommended files
- `medium` - Optional but helpful files
**Examples**:
```bash
# Mark as critical
/oac:add-context file:./security-policy.md --priority=critical
# Mark as high priority
/oac:add-context github:acme-corp/standards --priority=high
```
**Impact**: Priority affects ranking in `/context-discovery` results
---
### `--overwrite`
**Purpose**: Overwrite existing files with same name
**Default**: `false` (skip existing files)
**Examples**:
```bash
# Overwrite existing files
/oac:add-context github:acme-corp/standards --overwrite
# Skip existing files (default)
/oac:add-context github:acme-corp/standards
```
**Warning**: Use with caution - overwrites local modifications
---
### `--dry-run`
**Purpose**: Preview what would be added without making changes
**Examples**:
```bash
# Preview GitHub addition
/oac:add-context github:acme-corp/standards --dry-run
# Preview worktree addition
/oac:add-context worktree:../team-context --dry-run
```
**Output**:
```
Dry Run: No changes will be made
Would add:
- security-patterns.md → .opencode/context/team/security-patterns.md
- auth-guidelines.md → .opencode/context/team/auth-guidelines.md
- deployment-process.md → .opencode/context/team/deployment-process.md
Would update:
- .opencode/context/team/navigation.md
- .opencode/context/navigation.md
Run without --dry-run to apply changes.
```
---
## Usage Examples
### Example 1: Add Team Standards from GitHub
**Command**:
```bash
/oac:add-context github:acme-corp/engineering-standards/security --category=team --priority=critical
```
**Process**:
1. Discover context root → `.opencode/context`
2. Clone `acme-corp/engineering-standards` (shallow)
3. Copy `security/` directory
4. Validate markdown files
5. Copy to `.opencode/context/team/security/`
6. Update navigation files
7. Verify discoverability
**Output**:
```
✅ Context root discovered: .opencode/context
✅ Cloned from GitHub: acme-corp/engineering-standards
Branch: main
Path: security/
✅ Validation passed:
- security-policies.md ✅
- auth-patterns.md ✅
- data-protection.md ✅
✅ Copied to: .opencode/context/team/security/
✅ Navigation updated:
- .opencode/context/team/navigation.md
- .opencode/context/navigation.md
✅ Verification: All files discoverable via /context-discovery
Summary:
- Added 3 context files to team/security/
- Source: github:acme-corp/engineering-standards/security
- Category: team
- Priority: critical
- Discoverable: ✅
```
---
### Example 2: Add from Git Worktree
**Command**:
```bash
/oac:add-context worktree:../team-context/standards --category=team
```
**Process**:
1. Discover context root → `.claude/context` (from .oac config)
2. Validate worktree exists
3. Copy files from `../team-context/standards/`
4. Validate markdown files
5. Copy to `.claude/context/team/standards/`
6. Update navigation
7. Verify discoverability
**Output**:
```
✅ Context root discovered: .claude/context (from .oac config)
✅ Worktree validated: ../team-context/.git exists
✅ Copied from worktree: ../team-context/standards
Files: 5 markdown files
✅ Validation passed:
- code-quality.md ✅
- naming-conventions.md ✅
- testing-standards.md ✅
- deployment-process.md ✅
- review-checklist.md ✅
✅ Copied to: .claude/context/team/standards/
✅ Navigation updated:
- .claude/context/team/navigation.md
- .claude/context/navigation.md
✅ Verification: All files discoverable via /context-discovery
Summary:
- Added 5 context files to team/standards/
- Source: worktree:../team-context/standards
- Category: team
- Priority: medium (default)
- Discoverable: ✅
```
---
### Example 3: Add Local Pattern File
**Command**:
```bash
/oac:add-context file:./docs/patterns/auth-flow.md --category=custom --priority=high
```
**Process**:
1. Discover context root → `context` (found in project root)
2. Validate file exists
3. Validate markdown format
4. Copy to `context/custom/patterns/`
5. Update navigation
6. Verify discoverability
**Output**:
```
✅ Context root discovered: context
✅ File validated: ./docs/patterns/auth-flow.md
Format: markdown ✅
Structure: valid ✅
Size: 2.3 KB
✅ Copied to: context/custom/patterns/auth-flow.md
✅ Navigation updated:
- context/custom/navigation.md
- context/navigation.md
✅ Verification: File discoverable via /context-discovery
Summary:
- Added 1 context file to custom/patterns/
- Source: file:./docs/patterns/auth-flow.md
- Category: custom
- Priority: high
- Discoverable: ✅
```
---
### Example 4: Add from URL
**Command**:
```bash
/oac:add-context url:https://raw.githubusercontent.com/openagents/standards/main/security.md --category=external --priority=critical
```
**Process**:
1. Discover context root → `.opencode/context`
2. Download file from URL
3. Validate markdown format
4. Save to `.opencode/context/external/`
5. Update navigation
6. Verify discoverability
**Output**:
```
✅ Context root discovered: .opencode/context
✅ Downloaded from URL: https://raw.githubusercontent.com/openagents/standards/main/security.md
Size: 5.2 KB
Content-Type: text/plain
✅ Validation passed:
- security.md ✅
✅ Saved to: .opencode/context/external/security.md
✅ Navigation updated:
- .opencode/context/external/navigation.md
- .opencode/context/navigation.md
✅ Verification: File discoverable via /context-discovery
Summary:
- Added 1 context file to external/
- Source: url:https://raw.githubusercontent.com/...
- Category: external
- Priority: critical
- Discoverable: ✅
```
---
## Integration with OAC Workflow
### Stage 1: Analyze & Discover
**Before adding context**:
```bash
# Discover what context you need
/context-discovery authentication security patterns
# If context is missing, add it
/oac:add-context github:acme-corp/security-standards --category=team
```
### Stage 3: LoadContext
**After adding context**:
```bash
# Context is now discoverable
/context-discovery authentication security patterns
# Returns newly added files:
# - .opencode/context/team/security-patterns.md ✅
```
### Stage 6: Complete
**After implementing a feature**:
```bash
# Add learned patterns to context
/oac:add-context file:./docs/new-pattern.md --category=custom
# Now available for future tasks
```
---
## Advanced Usage
### Batch Addition
```bash
# Add multiple sources
/oac:add-context github:acme-corp/standards --category=team
/oac:add-context worktree:../team-context --category=team
/oac:add-context file:./docs/patterns/ --category=custom
```
### Preview Before Adding
```bash
# Dry run to see what would be added
/oac:add-context github:acme-corp/standards --dry-run
# Review output, then add for real
/oac:add-context github:acme-corp/standards --category=team
```
### Update Existing Context
```bash
# Overwrite existing files with latest from GitHub
/oac:add-context github:acme-corp/standards --category=team --overwrite
```
### Add with Specific Branch/Tag
```bash
# Add from specific version
/oac:add-context github:acme-corp/standards#v2.0.0 --category=team
# Add from development branch
/oac:add-context github:acme-corp/standards#develop --category=team
```
---
## Context Root Discovery
The command automatically discovers where to add context:
**Discovery Order**:
1. **Check .oac config** - Read `context.root` setting
2. **Check .claude/context** - Claude Code default
3. **Check context** - Simple root-level directory
4. **Check .opencode/context** - OpenCode/OAC default
5. **Create .opencode/context** - Fallback if none found
**Example .oac config**:
```json
{
"context": {
"root": ".claude/context"
}
}
```
---
## Validation
All added context files are validated:
### Format Validation
- ✅ Valid markdown file
- ✅ UTF-8 encoding
- ✅ No binary content
### Structure Validation
- ✅ Has title (# heading)
- ✅ Has content sections
- ⚠️ Metadata header (optional but recommended)
### Navigation Validation
- ✅ File added to navigation.md
- ✅ Category exists in root navigation
- ✅ Priority set correctly
**Validation Output**:
```
✅ Markdown format valid
✅ Structure valid (title, content)
⚠️ Metadata header missing (recommended but optional)
✅ Navigation entry added
Status: Valid (with warnings)
```
---
## Troubleshooting
### "Source not found"
**Cause**: GitHub repo, worktree, or file doesn't exist
**Solution**:
```bash
# Verify GitHub repo exists
gh repo view acme-corp/standards
# Verify worktree exists
ls -la ../team-context/.git
# Verify local file exists
ls -la ./docs/patterns/auth-flow.md
```
---
### "Validation failed"
**Cause**: File is not valid markdown or has structural issues
**Solution**:
```
Error: Validation failed for security-pattern.md
Issues:
❌ Not a markdown file (detected: text/html)
❌ Missing title (no # heading)
⚠️ No metadata header (recommended)
Fix these issues before adding to context.
```
**Fix**: Convert to markdown, add title, then retry
---
### "Context root not found"
**Cause**: No context directory exists and .oac config missing
**Solution**:
```bash
# Option 1: Let command create default
/oac:add-context github:acme-corp/standards
# Creates .opencode/context automatically
# Option 2: Create .oac config
cat > .oac <<EOF
{
"context": {
"root": ".claude/context"
}
}
EOF
# Option 3: Create directory manually
mkdir -p .opencode/context
```
---
### "Permission denied"
**Cause**: No write access to context directory
**Solution**:
```bash
# Check permissions
ls -la .opencode/
# Fix permissions
chmod -R u+w .opencode/context/
```
---
### "Navigation update failed"
**Cause**: Navigation file is malformed or locked
**Solution**:
```bash
# Backup current navigation
cp .opencode/context/navigation.md .opencode/context/navigation.md.backup
# Let command regenerate navigation
/oac:add-context github:acme-corp/standards --category=team
```
---
## Tips
### ✅ Do
- **Use --dry-run first** - Preview changes before applying
- **Organize by category** - Use appropriate categories (team, custom, external)
- **Set priority correctly** - Critical for must-read files
- **Verify discoverability** - Test with `/context-discovery` after adding
- **Keep worktrees updated** - Pull latest changes before adding
- **Use version tags** - Pin to specific versions for stability
### ❌ Don't
- **Don't add binary files** - Only markdown files are supported
- **Don't skip validation** - Fix validation errors before adding
- **Don't overwrite without backup** - Use --overwrite carefully
- **Don't add sensitive data** - Keep API keys and secrets out of context
- **Don't add too much** - Only add relevant, high-signal context
---
## Related Commands
- `/oac:setup` - Download OAC context from GitHub
- `/oac:status` - Check context installation status
- `/oac:help` - View all available commands
- `/context-discovery` - Discover added context files
## Related Skills
- `/context-manager` - Manage context configuration
- `/using-oac` - Main workflow (uses added context)
---
## Success Criteria
After running `/oac:add-context`, you should have:
- ✅ Context files copied to context root
- ✅ All files validated (format, structure)
- ✅ Navigation updated for discoverability
- ✅ Files accessible via `/context-discovery`
- ✅ Category and priority set correctly
**Test discoverability**:
```bash
/context-discovery [topic related to added context]
# Should return newly added files
```
---
**Version**: 1.0.0
**Command**: oac:add-context
**Last Updated**: 2026-02-16

View file

@ -2,7 +2,6 @@
name: oac-cleanup
description: Clean up old temporary files from .tmp directory
argument-hint: "[--force] [--days=N]"
disable-model-invocation: true
---
# Clean Up Temporary Files
@ -74,7 +73,7 @@ cleanup:
external_days: 7 # Days before suggesting external context cleanup
```
See `/oac:setup` for more about configuration.
See `/install-context` for more about configuration.
## Output
@ -118,7 +117,7 @@ Run cleanup when:
## Related Commands
- `/oac:status` - Check current .tmp directory status
- `/oac:setup` - Configure cleanup settings
- `/install-context` - Configure cleanup settings
- `/oac:help` - General help
---

View file

@ -62,7 +62,7 @@ Deliverables returned to user
|-------|---------|---------------|---------|
| `/using-oac` | N/A (orchestrator) | All | Main workflow orchestration through 6 stages |
| `/context-discovery` | `context-scout` | Read, Glob, Grep | Discover relevant context files and standards |
| `/context-manager` | `context-manager` | Read, Write, Glob, Bash | Manage context files, validate structure, organize |
| `/install-context` | N/A (script runner) | Bash | Download context files from GitHub repository |
| `/task-breakdown` | `task-manager` | Read, Write, Bash | Break complex features into atomic subtasks |
| `/code-execution` | `coder-agent` | Read, Write, Edit, Bash | Implement code following discovered standards |
| `/test-generation` | `test-engineer` | Read, Write, Bash | Generate comprehensive tests using TDD |
@ -242,55 +242,18 @@ Guide for performing thorough code reviews.
## 📝 Available Commands
### /oac:setup
Download context files from GitHub repository.
### /install-context
Download context files from the OpenAgents Control registry with interactive profile selection.
**Usage**: `/oac:setup`
**Usage**: `/install-context [--profile=<profile>] [--force] [--dry-run]`
**Profiles**: `essential`, `standard` (recommended), `extended`, `specialized`, `all`
**What it does**:
- Fetches `.opencode/context/` from GitHub
- Validates context structure
- Asks which profile to install
- Downloads context files from GitHub registry
- Creates `.context-manifest.json`
### /oac:plan
Plan and break down a complex feature into atomic subtasks.
**Usage**: `/oac:plan [feature description]`
**Examples**:
- `/oac:plan user authentication system`
- `/oac:plan API rate limiting with Redis`
- `/oac:plan payment integration (PCI compliance required)`
**What it does**:
- Analyzes feature requirements
- Discovers relevant context
- Creates task breakdown with dependencies
- Generates JSON task files in `.tmp/tasks/{feature}/`
### /oac:add-context
Add context files from GitHub, worktrees, local files, or URLs.
**Usage**: `/oac:add-context [source] [options]`
**Examples**:
- `/oac:add-context github:acme-corp/standards --category=team`
- `/oac:add-context worktree:../team-context --category=team`
- `/oac:add-context file:./docs/patterns/auth.md --category=custom`
- `/oac:add-context url:https://example.com/doc.md --category=external`
**Options**:
- `--category=<name>` - Target category (default: custom)
- `--priority=<level>` - Priority level (critical, high, medium)
- `--overwrite` - Overwrite existing files
- `--dry-run` - Preview without making changes
**What it does**:
- Discovers context root location
- Fetches/copies files from source
- Validates markdown format
- Updates navigation for discoverability
### /oac:help
Show this usage guide (you're reading it now!).
@ -326,7 +289,7 @@ Clean up old temporary files with approval.
1. **Download context files** (required):
```
/oac:setup --core
/install-context --profile=essential
```
This downloads coding standards, security patterns, and conventions.
@ -438,15 +401,14 @@ In Claude Code, only the main agent can invoke subagents. Skills orchestrate the
## 📚 Learn More
- **Installation**: See `INSTALL.md` for setup instructions
- **Quick Start**: See `QUICK-START.md` for getting started
- **Installation & Quick Start**: See `README.md` for full setup guide
- **Architecture**: See `README.md` for system overview
- **Context System**: Explore `context/` directory for standards and patterns
## 🆘 Troubleshooting
### "Context files not found"
Run `/oac:setup` to download context from GitHub.
Run `/install-context` to download context from GitHub.
### "Subagent not available"
Verify plugin installation with `/oac:status`.
@ -459,7 +421,7 @@ Claude Code doesn't support nested calls. Use skills to orchestrate, not subagen
## 💡 Tips
1. **Start with /oac:setup** - Download context files first
1. **Start with /install-context** - Download context files first
2. **Let the workflow guide you** - The using-oac skill handles orchestration
3. **Use context-scout early** - Discover standards before coding
4. **Break down complex tasks** - Use task-manager for multi-step features

View file

@ -1,552 +0,0 @@
---
name: oac:plan
description: Plan and break down a complex feature into atomic, verifiable subtasks with dependencies
argument-hint: [feature description]
---
# Plan Feature
Break down the following feature into atomic subtasks: **$ARGUMENTS**
---
## What This Command Does
The `/oac:plan` command helps you plan complex features by:
1. **Analyzing requirements** - Understanding scope and complexity
2. **Discovering context** - Finding relevant standards and patterns
3. **Creating task breakdown** - Generating subtask files with dependencies
4. **Presenting plan** - Showing task structure and execution order
This command invokes the **task-manager** subagent to create structured task files in `.tmp/tasks/{feature}/`.
---
## When to Use This Command
Use `/oac:plan` when you need to:
- **Plan a complex feature** requiring multiple steps or files
- **Break down large tasks** into manageable 1-2 hour subtasks
- **Map dependencies** between different components
- **Identify parallel work** that can be executed simultaneously
- **Create a roadmap** before starting implementation
**Examples of features that benefit from planning**:
- User authentication system
- Payment integration
- API rate limiting
- Multi-step workflows
- Features spanning multiple files or services
---
## Usage
### Basic Usage
```bash
# Plan a feature
/oac:plan user authentication system
# Plan with specific focus
/oac:plan API rate limiting with Redis
# Plan with constraints
/oac:plan payment integration (PCI compliance required)
```
### With Context Hints
```bash
# Specify security focus
/oac:plan user authentication (security-critical)
# Specify performance focus
/oac:plan search functionality (performance-critical)
# Specify integration focus
/oac:plan Stripe payment integration (external API)
```
---
## What You'll Get
### Task Files Created
The command creates structured JSON files in `.tmp/tasks/{feature}/`:
#### 1. `task.json` - Feature Metadata
```json
{
"id": "user-authentication",
"name": "User Authentication System",
"status": "active",
"objective": "Implement JWT-based authentication with refresh tokens",
"context_files": [
".opencode/context/core/standards/code-quality.md",
".opencode/context/core/standards/security-patterns.md"
],
"reference_files": [
"src/middleware/auth.middleware.ts"
],
"exit_criteria": [
"All tests passing",
"JWT tokens signed with RS256",
"Refresh token rotation implemented"
],
"subtask_count": 4,
"completed_count": 0,
"created_at": "2026-02-16T10:00:00Z"
}
```
#### 2. `subtask_01.json` - First Subtask
```json
{
"id": "user-authentication-01",
"seq": "01",
"title": "Create JWT service with token generation",
"status": "pending",
"depends_on": [],
"parallel": true,
"suggested_agent": "CoderAgent",
"context_files": [
".opencode/context/core/standards/security-patterns.md"
],
"reference_files": [],
"acceptance_criteria": [
"JWT tokens signed with RS256 algorithm",
"Access tokens expire in 15 minutes",
"Refresh tokens expire in 7 days"
],
"deliverables": [
"src/auth/jwt.service.ts",
"src/auth/jwt.service.test.ts"
]
}
```
#### 3. `subtask_02.json`, `subtask_03.json`, etc.
Additional subtasks with clear dependencies and deliverables.
---
## Output Format
After planning, you'll see a summary:
```
## Task Plan Created
**Feature**: user-authentication
**Location**: .tmp/tasks/user-authentication/
**Files**: task.json + 4 subtasks
### Subtasks
**01: Create JWT service with token generation**
- Parallel: ✅ (can run independently)
- Agent: CoderAgent
- Deliverables: jwt.service.ts, jwt.service.test.ts
**02: Implement auth middleware**
- Parallel: ❌ (depends on subtask 01)
- Agent: CoderAgent
- Deliverables: auth.middleware.ts, auth.middleware.test.ts
**03: Create login endpoint**
- Parallel: ❌ (depends on subtask 01, 02)
- Agent: CoderAgent
- Deliverables: auth.controller.ts, auth.routes.ts
**04: Add refresh token logic**
- Parallel: ❌ (depends on subtask 01)
- Agent: CoderAgent
- Deliverables: refresh-token.service.ts, refresh-token.test.ts
### Execution Order
**Phase 1** (parallel):
- Subtask 01: JWT service
**Phase 2** (after Phase 1):
- Subtask 02: Auth middleware
- Subtask 04: Refresh token logic (parallel with 02)
**Phase 3** (after Phase 2):
- Subtask 03: Login endpoint
### Next Steps
1. Review the task plan
2. Execute subtasks in order using `/code-execution` skill
3. Track progress with task-cli.ts (if available)
4. Mark subtasks complete as you finish them
**Ready to start implementation?**
```
---
## Integration with OAC Workflow
The `/oac:plan` command fits into the **6-stage OAC workflow**:
### Stage 1: Analyze & Discover
- `/oac:plan` discovers relevant context automatically
- Finds coding standards, security patterns, workflows
### Stage 2: Plan & Approve
- Creates detailed task breakdown
- **Requests approval** before proceeding to implementation
### Stage 3: LoadContext
- Context files already identified in task.json
- Main agent loads them before execution
### Stage 4: Execute
- Execute subtasks in dependency order
- Use `/code-execution` skill for each subtask
- Track progress through subtask status
### Stage 5: Validate
- Verify acceptance criteria for each subtask
- Run tests after each subtask completion
### Stage 6: Complete
- Mark feature as complete
- Update documentation
- Archive task files (optional)
---
## Advanced Usage
### Planning with Specific Context
```bash
# Discover context first, then plan
/context-discovery authentication security patterns
# Review discovered context
/oac:plan user authentication system
```
### Planning with External Dependencies
```bash
# Plan integration with external library
/oac:plan Stripe payment integration
# The task-manager will:
# 1. Discover internal context (security, API patterns)
# 2. Suggest using /external-scout for Stripe docs
# 3. Create subtasks with both internal and external context
```
### Planning with Constraints
```bash
# Specify constraints in the description
/oac:plan user authentication (must use existing database schema)
# The task-manager will:
# 1. Include reference_files for existing schema
# 2. Create subtasks that work within constraints
# 3. Flag potential conflicts or risks
```
---
## Task Management
### Viewing Task Status
```bash
# If task-cli.ts is available
node tasks/task-cli.ts status user-authentication
# Output:
# Feature: user-authentication
# Status: active
# Progress: 2/4 subtasks complete (50%)
#
# Subtasks:
# ✅ 01: JWT service (completed)
# ✅ 02: Auth middleware (completed)
# ⏳ 03: Login endpoint (in_progress)
# ⏸️ 04: Refresh token logic (pending)
```
### Updating Subtask Status
```bash
# Mark subtask as complete
node tasks/task-cli.ts complete user-authentication 01
# Mark subtask as in progress
node tasks/task-cli.ts start user-authentication 03
```
### Listing All Tasks
```bash
# List all active tasks
node tasks/task-cli.ts list
# Output:
# Active Tasks:
# - user-authentication (2/4 complete)
# - api-rate-limiting (0/3 complete)
```
---
## Examples
### Example 1: Simple Feature
**Command**:
```bash
/oac:plan add email validation to user registration
```
**Result**:
```
## Task Plan Created
**Feature**: email-validation
**Location**: .tmp/tasks/email-validation/
**Files**: task.json + 2 subtasks
### Subtasks
**01: Add email validation regex**
- Parallel: ✅
- Agent: CoderAgent
- Deliverables: validation.utils.ts, validation.test.ts
**02: Update registration endpoint**
- Parallel: ❌ (depends on 01)
- Agent: CoderAgent
- Deliverables: registration.controller.ts
### Next Steps
Execute subtasks in order.
```
---
### Example 2: Complex Feature
**Command**:
```bash
/oac:plan complete user authentication system with JWT and refresh tokens
```
**Result**:
```
## Task Plan Created
**Feature**: user-authentication
**Location**: .tmp/tasks/user-authentication/
**Files**: task.json + 6 subtasks
### Subtasks
**01: Create JWT service**
- Parallel: ✅
- Agent: CoderAgent
**02: Create refresh token service**
- Parallel: ✅
- Agent: CoderAgent
**03: Implement auth middleware**
- Parallel: ❌ (depends on 01)
- Agent: CoderAgent
**04: Create login endpoint**
- Parallel: ❌ (depends on 01, 03)
- Agent: CoderAgent
**05: Create refresh endpoint**
- Parallel: ❌ (depends on 02)
- Agent: CoderAgent
**06: Add logout endpoint**
- Parallel: ❌ (depends on 01, 03)
- Agent: CoderAgent
### Execution Order
**Phase 1** (parallel):
- 01: JWT service
- 02: Refresh token service
**Phase 2** (after Phase 1):
- 03: Auth middleware (depends on 01)
- 05: Refresh endpoint (depends on 02)
**Phase 3** (after Phase 2):
- 04: Login endpoint (depends on 01, 03)
- 06: Logout endpoint (depends on 01, 03)
### Next Steps
Execute 6 subtasks across 3 phases.
```
---
### Example 3: Integration Feature
**Command**:
```bash
/oac:plan Stripe payment integration with webhook handling
```
**Result**:
```
## Task Plan Created
**Feature**: stripe-payment-integration
**Location**: .tmp/tasks/stripe-payment-integration/
**Files**: task.json + 5 subtasks
### Subtasks
**01: Set up Stripe SDK and configuration**
- Parallel: ✅
- Agent: CoderAgent
- External Context: Stripe API docs (use /external-scout)
**02: Create payment intent service**
- Parallel: ❌ (depends on 01)
- Agent: CoderAgent
**03: Implement webhook handler**
- Parallel: ❌ (depends on 01)
- Agent: CoderAgent
**04: Add payment endpoints**
- Parallel: ❌ (depends on 02)
- Agent: CoderAgent
**05: Add webhook verification**
- Parallel: ❌ (depends on 03)
- Agent: CoderAgent
### External Dependencies
⚠️ This feature requires external documentation:
- Run: /external-scout Stripe payment intents
- Run: /external-scout Stripe webhooks
### Next Steps
1. Fetch external docs with /external-scout
2. Execute subtasks in dependency order
```
---
## Tips
### ✅ Do
- **Be specific** - "user authentication with JWT" is better than "auth"
- **Mention constraints** - Include important requirements in the description
- **Review the plan** - Check subtasks and dependencies before executing
- **Use parallel tasks** - Take advantage of tasks that can run simultaneously
- **Track progress** - Update subtask status as you complete them
### ❌ Don't
- **Don't skip planning** - Complex features benefit from upfront planning
- **Don't ignore dependencies** - Follow the execution order
- **Don't modify task files manually** - Use task-cli.ts or let agents update them
- **Don't plan trivial tasks** - Simple 1-file changes don't need planning
---
## Troubleshooting
### "No context found for planning"
**Cause**: Context files haven't been downloaded
**Solution**:
```bash
# Download context first
/oac:setup --core
# Then plan
/oac:plan your feature
```
---
### "Task files already exist"
**Cause**: A task with the same name already exists
**Solution**:
```bash
# Option 1: Use a different name
/oac:plan user-authentication-v2
# Option 2: Delete old task files
rm -rf .tmp/tasks/user-authentication/
# Option 3: Complete the existing task first
node tasks/task-cli.ts complete user-authentication
```
---
### "Subtasks seem too large"
**Cause**: Feature is very complex, subtasks are >2 hours
**Solution**:
- Break down the feature further
- Plan in phases (plan phase 1, execute, then plan phase 2)
- Manually split large subtasks into smaller ones
---
## Related Commands
- `/oac:setup` - Download context files (required before planning)
- `/oac:status` - Check OAC installation status
- `/oac:help` - View all available commands
## Related Skills
- `/context-discovery` - Discover context before planning
- `/task-breakdown` - Alternative way to invoke task-manager
- `/code-execution` - Execute planned subtasks
- `/test-generation` - Generate tests for subtasks
---
## Success Criteria
After running `/oac:plan`, you should have:
- ✅ Task files created in `.tmp/tasks/{feature}/`
- ✅ Clear subtasks with binary acceptance criteria
- ✅ Dependencies mapped correctly
- ✅ Parallel tasks identified
- ✅ Context files referenced
- ✅ Execution order clear
**Ready to implement? Start with the first subtask!**
---
**Version**: 1.0.0
**Command**: oac:plan
**Last Updated**: 2026-02-16

View file

@ -1,110 +0,0 @@
---
name: oac:setup
description: Download OpenAgents Control context files from GitHub repository
argument-hint: "[--core|--all|--category=<name>]"
disable-model-invocation: true
---
# OAC Setup Command
Download context files from the OpenAgents Control repository to enable context-aware development.
## Download Progress
!`${CLAUDE_PLUGIN_ROOT}/scripts/download-context.sh $ARGUMENTS`
## What Was Downloaded
The setup script has downloaded context files to `.opencode/context/` in your project directory.
### Available Options
- `--core` - Download only core context files (standards, workflows, patterns)
- `--all` - Download all context files including examples and guides
- `--category=<name>` - Download specific category (e.g., `--category=standards`)
### Context Categories
- **core** - Essential standards and workflows
- **openagents-repo** - OAC-specific guides and patterns
- **plugins** - Plugin development guides
- **skills** - Skill creation and usage
## Verification
The context files have been validated and a manifest has been created at:
`plugins/claude-code/.context-manifest.json`
## Configuration
You can customize OAC behavior by creating a `.oac` configuration file in your project root or `~/.oac` for global settings.
### Example Configuration
Copy the example config:
```bash
cp ${CLAUDE_PLUGIN_ROOT}/.oac.example .oac
```
### Available Settings
**Context Settings**:
- `context.auto_download` - Auto-download context on first use (default: false)
- `context.categories` - Default categories to download (default: core,openagents-repo)
- `context.update_check` - Check for context updates (default: true)
- `context.cache_days` - Days to cache external context (default: 7)
**Cleanup Settings**:
- `cleanup.auto_prompt` - Prompt for cleanup on session start (default: true)
- `cleanup.session_days` - Days before suggesting session cleanup (default: 7)
- `cleanup.task_days` - Days before suggesting task cleanup (default: 30)
- `cleanup.external_days` - Days before suggesting external context cleanup (default: 7)
**Workflow Settings**:
- `workflow.auto_approve` - Skip approval gates - DANGEROUS (default: false)
- `workflow.verbose` - Show detailed workflow steps (default: false)
**External Scout Settings**:
- `external_scout.enabled` - Enable external documentation fetching (default: true)
- `external_scout.cache_enabled` - Cache fetched documentation (default: true)
- `external_scout.sources` - Documentation sources to use (default: context7)
### Load Configuration
Configuration is automatically loaded on session start. To manually load:
```bash
bash ${CLAUDE_PLUGIN_ROOT}/scripts/load-config.sh
```
## Next Steps
1. **Configure OAC** (optional): Copy `.oac.example` to `.oac` and customize settings
2. **Explore available skills**: Run `/oac:help` to see what OAC can do
3. **Start a workflow**: Use `/using-oac` to begin context-aware development
4. **Check status**: Run `/oac:status` to verify installation
## Troubleshooting
If the download fails:
- Check your internet connection
- Verify GitHub repository access
- Ensure you have write permissions in the project directory
- Try running with `--core` first for minimal setup
## Manual Setup
If automatic download doesn't work, you can manually clone the context:
```bash
git clone --depth 1 --filter=blob:none --sparse \
https://github.com/darrenhinde/OpenAgentsControl.git temp-oac
cd temp-oac
git sparse-checkout set .opencode/context
cp -r .opencode/context /path/to/your/project/.opencode/
cd ..
rm -rf temp-oac
```
---
**Note**: Context files are cached locally. Re-run this command to update to the latest version.

View file

@ -8,35 +8,34 @@ description: Show OpenAgents Control plugin installation status and context
## Plugin Information
**Plugin**: OpenAgents Control (OAC)
**Version**: !`cat plugins/claude-code/.claude-plugin/plugin.json | grep '"version"' | sed 's/.*: "\(.*\)".*/\1/'`
**Version**: !`jq -r '.version' ${CLAUDE_PLUGIN_ROOT}/.claude-plugin/plugin.json 2>/dev/null || cat ${CLAUDE_PLUGIN_ROOT}/.claude-plugin/plugin.json | grep '"version"' | sed 's/.*: "\(.*\)".*/\1/'`
**Repository**: https://github.com/darrenhinde/OpenAgentsControl
---
## Context Installation Status
!`if [ -f "plugins/claude-code/.context-manifest.json" ]; then
!`PLUGIN_CONTEXT="${CLAUDE_PLUGIN_ROOT}/context"
MANIFEST="${CLAUDE_PLUGIN_ROOT}/.context-manifest.json"
if [ -f "$MANIFEST" ]; then
echo "✅ **Context Installed**"
echo ""
echo "### Manifest Details"
cat plugins/claude-code/.context-manifest.json | sed 's/^/ /'
cat "$MANIFEST" | sed 's/^/ /'
echo ""
echo "### Installed Context Files"
if [ -d ".opencode/context" ]; then
if [ -d "$PLUGIN_CONTEXT" ]; then
echo ""
echo "**Core Context**:"
find .opencode/context/core -type f -name "*.md" 2>/dev/null | wc -l | xargs -I {} echo " - {} files"
echo ""
echo "**OpenAgents Repository Context**:"
find .opencode/context/openagents-repo -type f -name "*.md" 2>/dev/null | wc -l | xargs -I {} echo " - {} files"
find "$PLUGIN_CONTEXT/core" -type f -name "*.md" 2>/dev/null | wc -l | xargs -I {} echo " - {} files"
echo ""
echo "**Categories**:"
find .opencode/context -type d -mindepth 2 -maxdepth 2 2>/dev/null | sed 's|.opencode/context/||' | sed 's/^/ - /'
find "$PLUGIN_CONTEXT" -type d -mindepth 1 -maxdepth 1 2>/dev/null | xargs -I {} basename {} | sed 's/^/ - /'
fi
else
echo "❌ **Context Not Installed**"
echo ""
echo "Run \`/oac:setup\` to download context files from GitHub."
echo "Run \`/install-context\` to download context files from GitHub."
fi`
---
@ -76,16 +75,17 @@ fi`
- `/code-review` - Guide code review process
### Commands
- `/oac:setup` - Download context files from GitHub
- `/install-context` - Download context files from GitHub
- `/oac:help` - Show usage guide and available skills
- `/oac:status` - Show this status information
- `/oac:cleanup` - Clean up old temporary files
---
## Recommendations
!`if [ ! -f "plugins/claude-code/.context-manifest.json" ]; then
echo "⚠️ **Action Required**: Run \`/oac:setup\` to install context files"
!`if [ ! -f "${CLAUDE_PLUGIN_ROOT}/.context-manifest.json" ]; then
echo "⚠️ **Action Required**: Run \`/install-context\` to install context files"
elif [ -d ".tmp/sessions" ]; then
SESSION_COUNT=$(find .tmp/sessions -maxdepth 1 -type d ! -path .tmp/sessions | wc -l | tr -d ' ')
if [ "$SESSION_COUNT" -gt 5 ]; then
@ -103,7 +103,7 @@ fi`
To start using OpenAgents Control:
1. **Ensure context is installed**: Run `/oac:setup` if not already done
1. **Ensure context is installed**: Run `/install-context` if not already done
2. **Invoke the main workflow**: Use `/using-oac` or let Claude auto-invoke it
3. **Get help**: Run `/oac:help` for detailed usage guide

View file

@ -1,4 +1,5 @@
{
"description": "OAC session initialization — injects workflow context on session start",
"hooks": {
"SessionStart": [
{
@ -7,6 +8,7 @@
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/session-start.sh",
"timeout": 30,
"async": false
}
]

View file

@ -11,13 +11,26 @@ SKILL_FILE="${PLUGIN_ROOT}/skills/using-oac/SKILL.md"
# Read using-oac content
using_oac_content=$(cat "${SKILL_FILE}" 2>&1 || echo "Error reading using-oac skill")
# Escape string for JSON embedding using bash parameter substitution
# Each ${s//old/new} is a single C-level pass - orders of magnitude
# faster than character-by-character loop
# Escape string for JSON embedding
# SECURITY: This function prevents command injection attacks from malicious SKILL.md files
# Previous implementation was vulnerable to:
# - $(command) injection via unescaped dollar signs
# - `command` injection via unescaped backticks
# - Control character injection
#
# We now escape ALL dangerous characters in the correct order:
# 1. Backslashes FIRST (to avoid double-escaping)
# 2. Double quotes (JSON string delimiter)
# 3. Dollar signs (prevent variable expansion and $(cmd) injection)
# 4. Backticks (prevent `cmd` command substitution)
# 5. Newlines, carriage returns, tabs (JSON control characters)
escape_for_json() {
local s="$1"
# Escape backslashes FIRST - order matters!
s="${s//\\/\\\\}"
# Escape double quotes
s="${s//\"/\\\"}"
# Escape newlines, carriage returns, tabs
s="${s//$'\n'/\\n}"
s="${s//$'\r'/\\r}"
s="${s//$'\t'/\\t}"
@ -28,18 +41,24 @@ using_oac_escaped=$(escape_for_json "$using_oac_content")
# Build warning message for first-time users
warning_message=""
if [[ ! -f ".context-manifest.json" ]]; then
warning_message="\n\n<important-reminder>IN YOUR FIRST REPLY AFTER SEEING THIS MESSAGE YOU MUST TELL THE USER:👋 **Welcome to OpenAgents Control!** To get started, run /oac:setup to download context files. Then use /oac:help to learn the 6-stage workflow.</important-reminder>"
if [[ ! -f "${PLUGIN_ROOT}/.context-manifest.json" ]]; then
warning_message="\n\n<important-reminder>IN YOUR FIRST REPLY AFTER SEEING THIS MESSAGE YOU MUST TELL THE USER:👋 **Welcome to OpenAgents Control!** To get started, run /install-context to download context files. Then use /oac:help to learn the 6-stage workflow.</important-reminder>"
fi
warning_escaped=$(escape_for_json "$warning_message")
# Output context injection as JSON
# Build context string once, reuse in both output formats
OAC_CONTEXT="<EXTREMELY_IMPORTANT>\nYou are using OpenAgents Control (OAC).\n\nIN YOUR VERY FIRST REPLY you MUST start with exactly this line (no exceptions):\n🤖 **OAC Active** — 6-stage workflow enabled. Type /oac:help for commands.\n\n**Below is the full content of your 'using-oac' skill - your guide to the 6-stage workflow. For all other skills, use the 'Skill' tool:**\n\n${using_oac_escaped}\n\n${warning_escaped}\n</EXTREMELY_IMPORTANT>"
# Output dual-format JSON for cross-tool compatibility
# - additionalContext: Claude Code (hookSpecificOutput)
# - additional_context: Cursor / OpenCode / other tools
cat <<EOF
{
"additional_context": "${OAC_CONTEXT}",
"hookSpecificOutput": {
"hookEventName": "SessionStart",
"additionalContext": "<EXTREMELY_IMPORTANT>\nYou are using OpenAgents Control (OAC).\n\n**Below is the full content of your 'using-oac' skill - your guide to the 6-stage workflow. For all other skills, use the 'Skill' tool:**\n\n${using_oac_escaped}\n\n${warning_escaped}\n</EXTREMELY_IMPORTANT>"
"additionalContext": "${OAC_CONTEXT}"
}
}
EOF

View file

@ -0,0 +1,186 @@
# Context Installer Scripts
TypeScript implementation of the context installer for the Claude Code plugin.
## Overview
This directory contains a TypeScript-based context installer that downloads context files from the OpenAgents Control repository using git sparse-checkout.
## Files
### Core Implementation
- **`install-context.ts`** - Main installer script with CLI interface
- **`test-install.ts`** - Test script for verifying installation against real GitHub repository
### Type Definitions
- **`types/registry.ts`** - Registry schema and types (with Zod validation)
- **`types/manifest.ts`** - Manifest schema and types
### Utilities
- **`utils/registry-fetcher.ts`** - Fetch and parse registry.json from GitHub
- **`utils/git-sparse.ts`** - Git sparse-checkout operations
## Usage
### Install Context
```bash
# Install essential profile (default)
bun run plugins/claude-code/scripts/install-context.ts
# Install specific profile
bun run plugins/claude-code/scripts/install-context.ts --profile=standard
# Install specific components
bun run plugins/claude-code/scripts/install-context.ts --component=core-standards --component=openagents-repo
# Dry run (see what would be installed)
bun run plugins/claude-code/scripts/install-context.ts --profile=extended --dry-run
# Force reinstall with verbose output
bun run plugins/claude-code/scripts/install-context.ts --force --verbose
```
### Run Tests
```bash
# Run test suite
bun run plugins/claude-code/scripts/test-install.ts
```
## Profiles
- **essential** - Minimal components for basic functionality
- **standard** - Standard components for typical use
- **extended** - Extended components for advanced features
- **specialized** - Specialized components for specific domains
- **all** - All available context
## Features
✅ Fetch registry.json from GitHub
✅ Parse and validate with Zod
✅ Filter context components by profile
✅ Download using git sparse-checkout
✅ Create manifest tracking installation
✅ Handle errors gracefully
✅ Dry run mode
✅ Verbose logging
✅ Force reinstall option
## Architecture
### Registry Fetching
The `registry-fetcher` utility:
1. Fetches registry.json from GitHub raw URL
2. Validates structure with Zod schema
3. Filters components by profile or custom IDs
4. Extracts unique directory paths for sparse checkout
### Git Sparse Checkout
The `git-sparse` utility:
1. Clones repository with `--filter=blob:none --sparse`
2. Configures sparse-checkout for specific paths
3. Copies files to target directory
4. Cleans up temporary files
### Manifest Creation
The installer creates a `.context-manifest.json` file tracking:
- Installation profile
- Source repository and commit SHA
- Downloaded components with local paths
- Installation timestamp
## Testing
The test script (`test-install.ts`) verifies:
1. **Registry Fetch** - Fetches from real GitHub repository
2. **Profile Filtering** - Filters components by profile
3. **Dry Run** - Simulates installation without downloading
To test actual installation, uncomment Test 4 in `test-install.ts`.
## Example Output
```
Context Installer
========================
ℹ Profile: essential
ℹ Repository: darrenhinde/OpenAgentsControl
ℹ Branch: main
ℹ Dry run: false
ℹ Fetching registry from GitHub...
✓ Registry version: 2.0.0
✓ Context components available: 150
ℹ Filtering by profile: essential
✓ Selected 12 components
ℹ Downloading context files...
✓ Files downloaded successfully
ℹ Copying files to context directory...
✓ Files copied to: /path/to/context
ℹ Creating manifest...
✓ Manifest created: .context-manifest.json
ℹ Verifying installation...
✓ Installation complete!
ℹ Files verified: 12/12
```
## Error Handling
The installer handles:
- Network failures (GitHub unavailable)
- Invalid registry structure
- Git command failures
- Missing dependencies (git not installed)
- File system errors
All errors are logged with clear messages and the installer exits with appropriate exit codes.
## Dependencies
- **Bun** - Runtime and package manager
- **Zod** - Schema validation
- **Git** - Sparse checkout operations
## Development
### Type Safety
All types are defined in `types/` directory with Zod schemas for runtime validation.
### Testing
Run tests before committing changes:
```bash
bun run plugins/claude-code/scripts/test-install.ts
```
### Adding New Profiles
To add a new profile, update the `Profile` type in `types/registry.ts` and the profile mapping in `utils/registry-fetcher.ts`.
## Migration from JavaScript
This TypeScript implementation replaces the original `install-context.js` with:
- Type safety with TypeScript and Zod
- Better error handling
- Modular architecture
- Comprehensive testing
- Improved documentation
The JavaScript version is kept for backward compatibility but the TypeScript version is recommended for new installations.

269
plugins/claude-code/scripts/cleanup-tmp.sh Normal file → Executable file
View file

@ -1,255 +1,58 @@
#!/bin/bash
# cleanup-tmp.sh - Clean old temporary files from .tmp directory
# Usage: cleanup-tmp.sh [--force] [--days=N]
#!/usr/bin/env bash
# cleanup-tmp.sh - Clean up old temporary files from .tmp directory
set -euo pipefail
# Default settings
FORCE_MODE=false
# Defaults
SESSION_DAYS=7
TASK_DAYS=30
EXTERNAL_DAYS=7
FORCE=false
# Parse arguments
for arg in "$@"; do
case $arg in
--force)
FORCE_MODE=true
shift
;;
--days=*)
CUSTOM_DAYS="${arg#*=}"
SESSION_DAYS=$CUSTOM_DAYS
TASK_DAYS=$CUSTOM_DAYS
EXTERNAL_DAYS=$CUSTOM_DAYS
shift
;;
--session-days=*)
SESSION_DAYS="${arg#*=}"
shift
;;
--task-days=*)
TASK_DAYS="${arg#*=}"
shift
;;
--external-days=*)
EXTERNAL_DAYS="${arg#*=}"
shift
;;
*)
# Unknown option
;;
case "$arg" in
--force) FORCE=true ;;
--session-days=*) SESSION_DAYS="${arg#*=}" ;;
--task-days=*) TASK_DAYS="${arg#*=}" ;;
--external-days=*) EXTERNAL_DAYS="${arg#*=}" ;;
esac
done
# Helper function to get directory size
get_dir_size() {
local dir=$1
if [[ -d "$dir" ]]; then
du -sh "$dir" 2>/dev/null | cut -f1
else
echo "0B"
# Find old files
SESSION_FILES=$(find .tmp/sessions -maxdepth 1 -mindepth 1 -type d -mtime +${SESSION_DAYS} 2>/dev/null || true)
TASK_FILES=$(find .tmp/tasks -maxdepth 1 -mindepth 1 -type d -mtime +${TASK_DAYS} 2>/dev/null | while read d; do
# Only include completed tasks (skip active ones)
if [ -f "$d/task.json" ] && grep -q '"status": "completed"' "$d/task.json" 2>/dev/null; then
echo "$d"
fi
}
done || true)
EXTERNAL_FILES=$(find .tmp/external-context -maxdepth 1 -mindepth 1 -type d -mtime +${EXTERNAL_DAYS} 2>/dev/null || true)
# Helper function to find old directories
find_old_dirs() {
local base_dir=$1
local days=$2
if [[ ! -d "$base_dir" ]]; then
return
fi
find "$base_dir" -mindepth 1 -maxdepth 1 -type d -mtime +$days 2>/dev/null || true
}
SESSION_COUNT=$(echo "$SESSION_FILES" | grep -c . 2>/dev/null || echo 0)
TASK_COUNT=$(echo "$TASK_FILES" | grep -c . 2>/dev/null || echo 0)
EXTERNAL_COUNT=$(echo "$EXTERNAL_FILES" | grep -c . 2>/dev/null || echo 0)
TOTAL=$((SESSION_COUNT + TASK_COUNT + EXTERNAL_COUNT))
# Helper function to find completed tasks older than N days
find_old_completed_tasks() {
local base_dir=$1
local days=$2
if [[ ! -d "$base_dir" ]]; then
return
fi
# Find task directories with completed subtasks
for task_dir in "$base_dir"/*; do
if [[ ! -d "$task_dir" ]]; then
continue
fi
# Check if all subtasks are completed and older than N days
local all_completed=true
local has_subtasks=false
for subtask_file in "$task_dir"/subtask_*.json; do
if [[ ! -f "$subtask_file" ]]; then
continue
fi
has_subtasks=true
# Check if subtask is completed
if ! grep -q '"status": "completed"' "$subtask_file" 2>/dev/null; then
all_completed=false
break
fi
# Check if file is older than N days
if [[ $(find "$subtask_file" -mtime +$days 2>/dev/null | wc -l) -eq 0 ]]; then
all_completed=false
break
fi
done
# If all subtasks are completed and old, include this task directory
if [[ "$has_subtasks" == "true" ]] && [[ "$all_completed" == "true" ]]; then
echo "$task_dir"
fi
done
}
# Collect cleanup candidates
declare -a SESSION_DIRS
declare -a TASK_DIRS
declare -a EXTERNAL_DIRS
# Find old sessions
while IFS= read -r dir; do
SESSION_DIRS+=("$dir")
done < <(find_old_dirs ".tmp/sessions" "$SESSION_DAYS")
# Find old completed tasks
while IFS= read -r dir; do
TASK_DIRS+=("$dir")
done < <(find_old_completed_tasks ".tmp/tasks" "$TASK_DAYS")
# Find old external context
while IFS= read -r dir; do
EXTERNAL_DIRS+=("$dir")
done < <(find_old_dirs ".tmp/external-context" "$EXTERNAL_DAYS")
# Calculate totals
TOTAL_ITEMS=$((${#SESSION_DIRS[@]} + ${#TASK_DIRS[@]} + ${#EXTERNAL_DIRS[@]}))
# If nothing to clean, exit early
if [[ $TOTAL_ITEMS -eq 0 ]]; then
cat <<EOF
{
"status": "success",
"message": "No old temporary files found",
"cleaned": {
"sessions": 0,
"tasks": 0,
"external": 0
},
"totalSize": "0B"
}
EOF
if [ "$TOTAL" -eq 0 ]; then
echo '{"status":"success","deleted":{"sessions":0,"tasks":0,"external":0},"freed_space":"0 B","summary":"No old temporary files found."}'
exit 0
fi
# Build cleanup report
CLEANUP_REPORT=""
TOTAL_SIZE=0
if [[ ${#SESSION_DIRS[@]} -gt 0 ]]; then
CLEANUP_REPORT+="## Sessions (older than ${SESSION_DAYS} days)\n\n"
for dir in "${SESSION_DIRS[@]}"; do
size=$(get_dir_size "$dir")
CLEANUP_REPORT+="- $(basename "$dir") - $size\n"
done
CLEANUP_REPORT+="\n"
fi
if [[ ${#TASK_DIRS[@]} -gt 0 ]]; then
CLEANUP_REPORT+="## Completed Tasks (older than ${TASK_DAYS} days)\n\n"
for dir in "${TASK_DIRS[@]}"; do
size=$(get_dir_size "$dir")
CLEANUP_REPORT+="- $(basename "$dir") - $size\n"
done
CLEANUP_REPORT+="\n"
fi
if [[ ${#EXTERNAL_DIRS[@]} -gt 0 ]]; then
CLEANUP_REPORT+="## External Context Cache (older than ${EXTERNAL_DAYS} days)\n\n"
for dir in "${EXTERNAL_DIRS[@]}"; do
size=$(get_dir_size "$dir")
CLEANUP_REPORT+="- $(basename "$dir") - $size\n"
done
CLEANUP_REPORT+="\n"
fi
# If not in force mode, ask for approval
if [[ "$FORCE_MODE" != "true" ]]; then
echo "# Cleanup Report"
# Show what will be deleted
if [ "$FORCE" = false ]; then
echo "Files to be deleted:"
[ -n "$SESSION_FILES" ] && echo "$SESSION_FILES" | sed 's/^/ [session] /'
[ -n "$TASK_FILES" ] && echo "$TASK_FILES" | sed 's/^/ [task] /'
[ -n "$EXTERNAL_FILES" ] && echo "$EXTERNAL_FILES" | sed 's/^/ [external] /'
echo ""
echo -e "$CLEANUP_REPORT"
echo "Total items to clean: $TOTAL_ITEMS"
echo ""
echo "Run with --force to proceed with cleanup"
echo "Run with --days=N to customize age threshold"
echo ""
cat <<EOF
{
"status": "approval_required",
"message": "Cleanup requires approval. Run with --force to proceed.",
"preview": {
"sessions": ${#SESSION_DIRS[@]},
"tasks": ${#TASK_DIRS[@]},
"external": ${#EXTERNAL_DIRS[@]},
"total": $TOTAL_ITEMS
}
}
EOF
exit 0
read -r -p "Delete $TOTAL items? [y/N] " confirm
[[ "$confirm" =~ ^[Yy]$ ]] || { echo "Cancelled."; exit 0; }
fi
# Perform cleanup
CLEANED_SESSIONS=0
CLEANED_TASKS=0
CLEANED_EXTERNAL=0
# Delete
[ -n "$SESSION_FILES" ] && echo "$SESSION_FILES" | xargs rm -rf
[ -n "$TASK_FILES" ] && echo "$TASK_FILES" | xargs rm -rf
[ -n "$EXTERNAL_FILES" ] && echo "$EXTERNAL_FILES" | xargs rm -rf
# Clean sessions
for dir in "${SESSION_DIRS[@]}"; do
if rm -rf "$dir" 2>/dev/null; then
((CLEANED_SESSIONS++))
fi
done
# Clean tasks
for dir in "${TASK_DIRS[@]}"; do
if rm -rf "$dir" 2>/dev/null; then
((CLEANED_TASKS++))
fi
done
# Clean external context
for dir in "${EXTERNAL_DIRS[@]}"; do
if rm -rf "$dir" 2>/dev/null; then
((CLEANED_EXTERNAL++))
fi
done
TOTAL_CLEANED=$((CLEANED_SESSIONS + CLEANED_TASKS + CLEANED_EXTERNAL))
# Output JSON result
cat <<EOF
{
"status": "success",
"message": "Cleanup completed successfully",
"cleaned": {
"sessions": $CLEANED_SESSIONS,
"tasks": $CLEANED_TASKS,
"external": $CLEANED_EXTERNAL,
"total": $TOTAL_CLEANED
},
"thresholds": {
"sessionDays": $SESSION_DAYS,
"taskDays": $TASK_DAYS,
"externalDays": $EXTERNAL_DAYS
}
}
EOF
echo "{\"status\":\"success\",\"deleted\":{\"sessions\":${SESSION_COUNT},\"tasks\":${TASK_COUNT},\"external\":${EXTERNAL_COUNT}},\"summary\":\"Cleaned up ${TOTAL} old temporary items.\"}"

View file

@ -1,408 +0,0 @@
#!/usr/bin/env bash
# download-context.sh - Fetch context files from GitHub repository
# Part of OpenAgents Control (OAC) Claude Code Plugin
set -euo pipefail
# Configuration
GITHUB_REPO="${GITHUB_REPO:-darrenhinde/OpenAgentsControl}"
GITHUB_BRANCH="${GITHUB_BRANCH:-main}"
CONTEXT_DIR="${CLAUDE_PLUGIN_ROOT:-.}/context"
MANIFEST_FILE="${CLAUDE_PLUGIN_ROOT:-.}/.context-manifest.json"
GITHUB_API_BASE="https://api.github.com/repos/${GITHUB_REPO}"
GITHUB_RAW_BASE="https://raw.githubusercontent.com/${GITHUB_REPO}/${GITHUB_BRANCH}"
# Core categories (minimal required set)
CORE_CATEGORIES=(
"core"
"openagents-repo"
)
# All available categories
ALL_CATEGORIES=(
"core"
"openagents-repo"
"development"
"ui"
"content-creation"
"data"
"product"
"learning"
"project"
"project-intelligence"
)
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Usage information
usage() {
cat <<EOF
Usage: $(basename "$0") [OPTIONS]
Download context files from OpenAgents Control GitHub repository.
OPTIONS:
--core Download core categories only (core, openagents-repo)
--all Download all available categories
--category=NAME Download specific category (can be used multiple times)
--branch=NAME Use specific branch (default: main)
--pr=NUMBER Download from pull request
--force Force re-download even if files exist
--help Show this help message
EXAMPLES:
# Download core context only
$(basename "$0") --core
# Download all context
$(basename "$0") --all
# Download specific categories
$(basename "$0") --category=core --category=development
# Download from a PR
$(basename "$0") --pr=123 --core
CATEGORIES:
Core (required):
- core Universal standards & workflows
- openagents-repo OpenAgents Control repository work
Optional:
- development Software development (all stacks)
- ui Visual design & UX
- content-creation Content creation (all formats)
- data Data engineering & analytics
- product Product management
- learning Educational content
- project Project-specific context
- project-intelligence Project intelligence & decisions
EOF
exit 0
}
# Logging functions
log_info() {
echo -e "${BLUE}ℹ${NC} $*"
}
log_success() {
echo -e "${GREEN}✓${NC} $*"
}
log_warning() {
echo -e "${YELLOW}⚠${NC} $*"
}
log_error() {
echo -e "${RED}✗${NC} $*" >&2
}
# Check if command exists
command_exists() {
command -v "$1" >/dev/null 2>&1
}
# Validate dependencies
check_dependencies() {
local missing=()
if ! command_exists curl; then
missing+=("curl")
fi
if ! command_exists jq; then
missing+=("jq")
fi
if [ ${#missing[@]} -gt 0 ]; then
log_error "Missing required dependencies: ${missing[*]}"
log_info "Install with: brew install ${missing[*]}"
exit 1
fi
}
# Get GitHub authentication token
get_github_token() {
if [ -n "${GITHUB_TOKEN:-}" ]; then
echo "$GITHUB_TOKEN"
elif [ -n "${GH_TOKEN:-}" ]; then
echo "$GH_TOKEN"
elif command_exists gh; then
gh auth token 2>/dev/null || echo ""
else
echo ""
fi
}
# Fetch file from GitHub
fetch_file() {
local file_path="$1"
local output_path="$2"
local token
token=$(get_github_token)
local url="${GITHUB_RAW_BASE}/.opencode/context/${file_path}"
# Create directory if needed
mkdir -p "$(dirname "$output_path")"
# Download file
if [ -n "$token" ]; then
curl -sf -H "Authorization: token $token" "$url" -o "$output_path"
else
curl -sf "$url" -o "$output_path"
fi
}
# List files in a directory from GitHub
list_github_directory() {
local dir_path="$1"
local token
token=$(get_github_token)
local api_url="${GITHUB_API_BASE}/contents/.opencode/context/${dir_path}?ref=${GITHUB_BRANCH}"
if [ -n "$token" ]; then
curl -sf -H "Authorization: token $token" "$api_url" | jq -r '.[] | select(.type == "file") | .path' | sed 's|^.opencode/context/||'
else
curl -sf "$api_url" | jq -r '.[] | select(.type == "file") | .path' | sed 's|^.opencode/context/||'
fi
}
# Recursively download directory
download_directory() {
local category="$1"
local token
token=$(get_github_token)
log_info "Downloading category: $category"
# Get all files in the category recursively
local api_url="${GITHUB_API_BASE}/git/trees/${GITHUB_BRANCH}?recursive=1"
local files
if [ -n "$token" ]; then
files=$(curl -sf -H "Authorization: token $token" "$api_url" | \
jq -r ".tree[] | select(.type == \"blob\" and (.path | startswith(\".opencode/context/${category}/\"))) | .path" | \
sed 's|^.opencode/context/||')
else
files=$(curl -sf "$api_url" | \
jq -r ".tree[] | select(.type == \"blob\" and (.path | startswith(\".opencode/context/${category}/\"))) | .path" | \
sed 's|^.opencode/context/||')
fi
local count=0
local total
total=$(echo "$files" | wc -l | tr -d ' ')
while IFS= read -r file; do
if [ -n "$file" ]; then
((count++))
local output_path="${CONTEXT_DIR}/${file}"
# Show progress
printf "\r [%d/%d] %s" "$count" "$total" "$file"
if fetch_file "$file" "$output_path" 2>/dev/null; then
: # Success, continue
else
log_warning "Failed to download: $file"
fi
fi
done <<< "$files"
echo "" # New line after progress
log_success "Downloaded $count files from $category"
}
# Verify navigation.md files exist
verify_navigation() {
local categories=("$@")
local missing=()
log_info "Verifying navigation files..."
for category in "${categories[@]}"; do
local nav_file="${CONTEXT_DIR}/${category}/navigation.md"
if [ ! -f "$nav_file" ]; then
missing+=("$category/navigation.md")
fi
done
if [ ${#missing[@]} -gt 0 ]; then
log_warning "Missing navigation files:"
for file in "${missing[@]}"; do
echo " - $file"
done
return 1
else
log_success "All navigation files present"
return 0
fi
}
# Create context manifest
create_manifest() {
local categories=("$@")
log_info "Creating context manifest..."
# Get commit SHA
local token
token=$(get_github_token)
local commit_sha
if [ -n "$token" ]; then
commit_sha=$(curl -sf -H "Authorization: token $token" \
"${GITHUB_API_BASE}/commits/${GITHUB_BRANCH}" | jq -r '.sha')
else
commit_sha=$(curl -sf "${GITHUB_API_BASE}/commits/${GITHUB_BRANCH}" | jq -r '.sha')
fi
# Create manifest JSON
cat > "$MANIFEST_FILE" <<EOF
{
"version": "1.0.0",
"source": {
"repository": "${GITHUB_REPO}",
"branch": "${GITHUB_BRANCH}",
"commit": "${commit_sha}",
"downloaded_at": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
},
"categories": $(printf '%s\n' "${categories[@]}" | jq -R . | jq -s .),
"files": {
$(
for category in "${categories[@]}"; do
local count
count=$(find "${CONTEXT_DIR}/${category}" -type f 2>/dev/null | wc -l | tr -d ' ')
echo " \"${category}\": ${count},"
done | sed '$ s/,$//'
)
}
}
EOF
log_success "Created manifest: $MANIFEST_FILE"
}
# Main download function
download_context() {
local categories=("$@")
log_info "Starting context download..."
log_info "Repository: ${GITHUB_REPO}"
log_info "Branch: ${GITHUB_BRANCH}"
log_info "Categories: ${categories[*]}"
echo ""
# Create context directory
mkdir -p "$CONTEXT_DIR"
# Download each category
for category in "${categories[@]}"; do
download_directory "$category"
done
echo ""
# Verify navigation files
verify_navigation "${categories[@]}"
# Create manifest
create_manifest "${categories[@]}"
echo ""
log_success "Context download complete!"
log_info "Context location: $CONTEXT_DIR"
log_info "Manifest: $MANIFEST_FILE"
}
# Parse command line arguments
main() {
local categories=()
local download_mode=""
local force=false
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
--core)
download_mode="core"
shift
;;
--all)
download_mode="all"
shift
;;
--category=*)
categories+=("${1#*=}")
shift
;;
--branch=*)
GITHUB_BRANCH="${1#*=}"
shift
;;
--pr=*)
local pr_number="${1#*=}"
# Get PR branch
local token
token=$(get_github_token)
if [ -n "$token" ]; then
GITHUB_BRANCH=$(curl -sf -H "Authorization: token $token" \
"${GITHUB_API_BASE}/pulls/${pr_number}" | jq -r '.head.ref')
else
GITHUB_BRANCH=$(curl -sf "${GITHUB_API_BASE}/pulls/${pr_number}" | jq -r '.head.ref')
fi
log_info "Using PR #${pr_number} branch: ${GITHUB_BRANCH}"
shift
;;
--force)
force=true
shift
;;
--help|-h)
usage
;;
*)
log_error "Unknown option: $1"
echo ""
usage
;;
esac
done
# Determine categories to download
if [ "$download_mode" = "core" ]; then
categories=("${CORE_CATEGORIES[@]}")
elif [ "$download_mode" = "all" ]; then
categories=("${ALL_CATEGORIES[@]}")
elif [ ${#categories[@]} -eq 0 ]; then
# Default to core if nothing specified
log_warning "No categories specified, defaulting to --core"
categories=("${CORE_CATEGORIES[@]}")
fi
# Check dependencies
check_dependencies
# Check if context already exists
if [ -f "$MANIFEST_FILE" ] && [ "$force" = false ]; then
log_warning "Context already exists. Use --force to re-download."
log_info "Current manifest:"
cat "$MANIFEST_FILE" | jq .
exit 0
fi
# Download context
download_context "${categories[@]}"
}
# Run main function
main "$@"

View file

@ -0,0 +1,328 @@
#!/usr/bin/env node
/**
* install-context.js
* Simple context installer for OAC Claude Code Plugin
*
* Downloads context files from OpenAgents Control repository
* Supports profile-based installation (core, full, custom)
*/
const { execSync } = require('child_process');
const { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync } = require('fs');
const { join } = require('path');
// Configuration
const GITHUB_REPO = 'darrenhinde/OpenAgentsControl';
const GITHUB_BRANCH = 'main';
const CONTEXT_SOURCE_PATH = '.opencode/context';
const PLUGIN_ROOT = process.env.CLAUDE_PLUGIN_ROOT || process.cwd();
const CONTEXT_DIR = join(PLUGIN_ROOT, 'context');
const MANIFEST_FILE = join(PLUGIN_ROOT, '.context-manifest.json');
// Installation profiles
const PROFILES = {
core: {
name: 'Core',
description: 'Essential standards and workflows',
categories: ['core', 'openagents-repo']
},
full: {
name: 'Full',
description: 'All available context',
categories: [
'core',
'openagents-repo',
'development',
'ui',
'content-creation',
'data',
'product',
'learning',
'project',
'project-intelligence'
]
}
};
// Colors for output
const colors = {
reset: '\x1b[0m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
};
// Logging helpers
const log = {
info: (msg) => console.log(`${colors.blue}ℹ${colors.reset} ${msg}`),
success: (msg) => console.log(`${colors.green}✓${colors.reset} ${msg}`),
warning: (msg) => console.log(`${colors.yellow}⚠${colors.reset} ${msg}`),
error: (msg) => console.error(`${colors.red}✗${colors.reset} ${msg}`),
};
/**
* Check if required commands are available
*/
function checkDependencies() {
const required = ['git'];
const missing = [];
for (const cmd of required) {
try {
execSync(`command -v ${cmd}`, { stdio: 'ignore' });
} catch {
missing.push(cmd);
}
}
if (missing.length > 0) {
log.error(`Missing required dependencies: ${missing.join(', ')}`);
log.info('Install with: brew install ' + missing.join(' '));
process.exit(1);
}
}
/**
* Download context using git sparse-checkout
*/
function downloadContext(categories) {
const tempDir = join(PLUGIN_ROOT, '.tmp-context-download');
try {
log.info(`Downloading context from ${GITHUB_REPO}...`);
log.info(`Categories: ${categories.join(', ')}`);
// Clean up temp directory if it exists
if (existsSync(tempDir)) {
rmSync(tempDir, { recursive: true, force: true });
}
// Clone with sparse checkout (no working tree files)
log.info('Cloning repository...');
execSync(
`git clone --depth 1 --filter=blob:none --sparse https://github.com/${GITHUB_REPO}.git "${tempDir}"`,
{ stdio: 'pipe' }
);
// Configure sparse checkout for requested categories
log.info('Configuring sparse checkout...');
const sparseCheckoutPaths = categories.map(cat => `${CONTEXT_SOURCE_PATH}/${cat}`);
// Also include root navigation
sparseCheckoutPaths.push(`${CONTEXT_SOURCE_PATH}/navigation.md`);
execSync(
`cd "${tempDir}" && git sparse-checkout set ${sparseCheckoutPaths.join(' ')}`,
{ stdio: 'pipe' }
);
// Create context directory if it doesn't exist
if (!existsSync(CONTEXT_DIR)) {
mkdirSync(CONTEXT_DIR, { recursive: true });
}
// Copy files to context directory
log.info('Copying context files...');
const sourceContextDir = join(tempDir, CONTEXT_SOURCE_PATH);
if (existsSync(sourceContextDir)) {
execSync(`cp -r "${sourceContextDir}"/* "${CONTEXT_DIR}"/`, { stdio: 'pipe' });
log.success('Context files downloaded successfully');
} else {
throw new Error('Context directory not found in repository');
}
// Count downloaded files
const fileCount = execSync(`find "${CONTEXT_DIR}" -type f | wc -l`, { encoding: 'utf-8' }).trim();
log.success(`Downloaded ${fileCount} files`);
// Clean up temp directory
rmSync(tempDir, { recursive: true, force: true });
} catch (error) {
log.error('Failed to download context');
if (error instanceof Error) {
log.error(error.message);
}
// Clean up on error
if (existsSync(tempDir)) {
rmSync(tempDir, { recursive: true, force: true });
}
process.exit(1);
}
}
/**
* Create manifest file tracking installation
*/
function createManifest(profile, categories) {
try {
// Get commit SHA
const tempDir = join(PLUGIN_ROOT, '.tmp-manifest-check');
if (existsSync(tempDir)) {
rmSync(tempDir, { recursive: true, force: true });
}
execSync(
`git clone --depth 1 https://github.com/${GITHUB_REPO}.git "${tempDir}"`,
{ stdio: 'pipe' }
);
const commitSha = execSync(`cd "${tempDir}" && git rev-parse HEAD`, { encoding: 'utf-8' }).trim();
rmSync(tempDir, { recursive: true, force: true });
// Count files per category
const files = {};
for (const category of categories) {
const categoryPath = join(CONTEXT_DIR, category);
if (existsSync(categoryPath)) {
const count = parseInt(
execSync(`find "${categoryPath}" -type f | wc -l`, { encoding: 'utf-8' }).trim(),
10
);
files[category] = count;
}
}
// Create manifest
const manifest = {
version: '1.0.0',
profile,
source: {
repository: GITHUB_REPO,
branch: GITHUB_BRANCH,
commit: commitSha,
downloaded_at: new Date().toISOString(),
},
categories,
files,
};
writeFileSync(MANIFEST_FILE, JSON.stringify(manifest, null, 2));
log.success(`Created manifest: ${MANIFEST_FILE}`);
} catch (error) {
log.warning('Failed to create manifest (non-fatal)');
}
}
/**
* Show usage information
*/
function showUsage() {
console.log(`
Usage: node install-context.js [PROFILE] [OPTIONS]
PROFILES:
core Download core context only (default)
Categories: core, openagents-repo
full Download all available context
Categories: all domains
custom Specify custom categories
Use with --category flags
OPTIONS:
--category=NAME Add specific category (use with 'custom' profile)
--force Force re-download even if context exists
--help Show this help message
EXAMPLES:
# Install core context (default)
node install-context.js
# Install full context
node install-context.js full
# Install custom categories
node install-context.js custom --category=core --category=development
# Force reinstall
node install-context.js core --force
`);
}
/**
* Main installation function
*/
function main() {
const args = process.argv.slice(2);
// Parse arguments
let profile = 'core';
let customCategories = [];
let force = false;
for (const arg of args) {
if (arg === '--help' || arg === '-h') {
showUsage();
process.exit(0);
} else if (arg === '--force') {
force = true;
} else if (arg.startsWith('--category=')) {
customCategories.push(arg.split('=')[1]);
} else if (arg === 'core' || arg === 'full' || arg === 'custom') {
profile = arg;
} else {
log.error(`Unknown argument: ${arg}`);
showUsage();
process.exit(1);
}
}
// Determine categories to install
let categories;
if (profile === 'custom') {
if (customCategories.length === 0) {
log.error('Custom profile requires --category flags');
showUsage();
process.exit(1);
}
categories = customCategories;
} else {
categories = PROFILES[profile].categories;
}
// Check if context already exists
if (existsSync(MANIFEST_FILE) && !force) {
log.warning('Context already installed. Use --force to reinstall.');
log.info('Current installation:');
try {
const manifest = JSON.parse(readFileSync(MANIFEST_FILE, 'utf-8'));
console.log(JSON.stringify(manifest, null, 2));
} catch {
log.error('Failed to read manifest');
}
process.exit(0);
}
// Check dependencies
checkDependencies();
// Download context
console.log('');
log.info(`Installing ${profile} profile`);
log.info(`Repository: ${GITHUB_REPO}`);
log.info(`Branch: ${GITHUB_BRANCH}`);
console.log('');
downloadContext(categories);
// Create manifest
createManifest(profile, categories);
console.log('');
log.success('Context installation complete!');
log.info(`Context location: ${CONTEXT_DIR}`);
log.info(`Manifest: ${MANIFEST_FILE}`);
console.log('');
}
// Run main function
main();

View file

@ -0,0 +1,356 @@
#!/usr/bin/env bun
/**
* install-context.ts
* TypeScript context installer for OAC Claude Code Plugin
*
* Downloads context files from OpenAgents Control repository using git sparse-checkout
* Supports profile-based installation (essential, standard, extended, specialized, all)
*/
import { existsSync, writeFileSync, readFileSync } from 'fs'
import { join } from 'path'
import type { InstallOptions, InstallResult, Profile } from './types/registry'
import type { Manifest, ManifestComponent } from './types/manifest'
import { fetchRegistry, filterContextByProfile, filterContextByIds, getUniquePaths } from './utils/registry-fetcher'
import { sparseClone, copyFiles, cleanup, checkGitAvailable } from './utils/git-sparse'
// Configuration
const GITHUB_REPO = 'darrenhinde/OpenAgentsControl'
const GITHUB_BRANCH = 'main'
const CONTEXT_SOURCE_PATH = '.opencode/context'
const PLUGIN_ROOT = process.env.CLAUDE_PLUGIN_ROOT || process.cwd()
const CONTEXT_DIR = join(PLUGIN_ROOT, 'context')
const MANIFEST_FILE = join(PLUGIN_ROOT, '.context-manifest.json')
// Colors for output
const colors = {
reset: '\x1b[0m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
cyan: '\x1b[36m',
bold: '\x1b[1m',
}
// Logging helpers
const log = {
info: (msg: string) => console.log(`${colors.blue}ℹ${colors.reset} ${msg}`),
success: (msg: string) => console.log(`${colors.green}✓${colors.reset} ${msg}`),
warning: (msg: string) => console.log(`${colors.yellow}⚠${colors.reset} ${msg}`),
error: (msg: string) => console.error(`${colors.red}✗${colors.reset} ${msg}`),
header: (msg: string) => console.log(`\n${colors.bold}${colors.cyan}${msg}${colors.reset}\n`),
}
/**
* Main installation function
*/
export async function installContext(options: InstallOptions = {}): Promise<InstallResult> {
const {
profile = 'essential',
customComponents = [],
dryRun = false,
force = false,
verbose = false,
} = options
try {
// Check dependencies
if (!checkGitAvailable()) {
throw new Error('Git is not available. Please install git.')
}
// Check if already installed
if (existsSync(MANIFEST_FILE) && !force) {
log.warning('Context already installed. Use --force to reinstall.')
const manifest = JSON.parse(readFileSync(MANIFEST_FILE, 'utf-8')) as Manifest
return {
success: true,
manifest: convertManifestToInstallManifest(manifest),
}
}
log.header('Context Installer')
log.info(`Profile: ${profile}`)
log.info(`Repository: ${GITHUB_REPO}`)
log.info(`Branch: ${GITHUB_BRANCH}`)
log.info(`Dry run: ${dryRun}`)
console.log('')
// Fetch registry
log.info('Fetching registry from GitHub...')
const registry = await fetchRegistry({
source: 'github',
repository: GITHUB_REPO,
branch: GITHUB_BRANCH,
})
log.success(`Registry version: ${registry.version}`)
log.success(`Context components available: ${registry.components.contexts?.length || 0}`)
console.log('')
// Filter components by profile or custom IDs
let components
if (customComponents.length > 0) {
log.info('Filtering by custom component IDs...')
components = filterContextByIds(registry, customComponents)
} else {
log.info(`Filtering by profile: ${profile}`)
components = filterContextByProfile(registry, profile)
}
log.success(`Selected ${components.length} components`)
if (verbose) {
console.log('')
log.info('Components to install:')
for (const component of components) {
console.log(` - ${component.id}: ${component.path}`)
}
}
console.log('')
if (dryRun) {
log.info('Dry run mode - no files will be downloaded')
return {
success: true,
manifest: {
version: '1.0.0',
profile: customComponents.length > 0 ? 'custom' : profile,
source: {
repository: GITHUB_REPO,
branch: GITHUB_BRANCH,
commit: 'dry-run',
downloaded_at: new Date().toISOString(),
},
context: components.map((c) => ({
id: c.id,
name: c.name,
path: c.path,
local_path: join(CONTEXT_DIR, c.path.replace(`${CONTEXT_SOURCE_PATH}/`, '')),
category: c.category,
})),
},
}
}
// Get unique directory paths for sparse checkout
const sparsePaths = getUniquePaths(components)
if (verbose) {
log.info('Sparse checkout paths:')
for (const path of sparsePaths) {
console.log(` - ${path}`)
}
console.log('')
}
// Download using git sparse-checkout
log.info('Downloading context files...')
const tempDir = join(PLUGIN_ROOT, '.tmp-context-download')
const cloneResult = await sparseClone({
repository: GITHUB_REPO,
branch: GITHUB_BRANCH,
paths: sparsePaths,
targetDir: tempDir,
verbose,
})
if (!cloneResult.success) {
throw new Error(`Git sparse clone failed: ${cloneResult.error}`)
}
log.success('Files downloaded successfully')
console.log('')
// Copy files to context directory
log.info('Copying files to context directory...')
const sourceContextDir = join(tempDir, CONTEXT_SOURCE_PATH)
copyFiles(sourceContextDir, CONTEXT_DIR, verbose)
log.success(`Files copied to: ${CONTEXT_DIR}`)
console.log('')
// Create manifest
log.info('Creating manifest...')
const manifestComponents: ManifestComponent[] = components.map((c) => ({
id: c.id,
name: c.name,
path: c.path,
local_path: join(CONTEXT_DIR, c.path.replace(`${CONTEXT_SOURCE_PATH}/`, '')),
category: c.category,
}))
const manifest: Manifest = {
version: '1.0.0',
profile: customComponents.length > 0 ? 'custom' : profile,
source: {
repository: GITHUB_REPO,
branch: GITHUB_BRANCH,
commit: cloneResult.commit,
downloaded_at: new Date().toISOString(),
},
context: manifestComponents,
}
writeFileSync(MANIFEST_FILE, JSON.stringify(manifest, null, 2))
log.success(`Manifest created: ${MANIFEST_FILE}`)
console.log('')
// Clean up temp directory
cleanup(tempDir, verbose)
// Verify installation
log.info('Verifying installation...')
let filesExist = 0
let filesMissing = 0
for (const component of manifestComponents) {
if (existsSync(component.local_path)) {
filesExist++
if (verbose) {
log.success(`${component.id}: EXISTS`)
}
} else {
filesMissing++
log.error(`${component.id}: MISSING`)
}
}
console.log('')
log.success(`Installation complete!`)
log.info(`Files verified: ${filesExist}/${manifestComponents.length}`)
if (filesMissing > 0) {
log.warning(`Missing files: ${filesMissing}`)
}
return {
success: true,
manifest: convertManifestToInstallManifest(manifest),
}
} catch (error) {
log.error('Installation failed')
log.error(error instanceof Error ? error.message : String(error))
return {
success: false,
manifest: {
version: '1.0.0',
profile: 'essential',
source: {
repository: GITHUB_REPO,
branch: GITHUB_BRANCH,
commit: '',
downloaded_at: new Date().toISOString(),
},
context: [],
},
errors: [error instanceof Error ? error.message : String(error)],
}
}
}
/**
* Convert Manifest to InstallManifest format
*/
function convertManifestToInstallManifest(manifest: Manifest): InstallResult['manifest'] {
return manifest as InstallResult['manifest']
}
/**
* Show usage information
*/
function showUsage(): void {
console.log(`
${colors.bold}Usage:${colors.reset} bun run install-context.ts [OPTIONS]
${colors.bold}OPTIONS:${colors.reset}
--profile=PROFILE Installation profile (default: essential)
Options: essential, standard, extended, specialized, all
--component=ID Install specific component by ID (can be used multiple times)
Example: --component=core-standards --component=openagents-repo
--dry-run Show what would be installed without downloading
--force Force reinstall even if context exists
--verbose Show detailed output
--help Show this help message
${colors.bold}PROFILES:${colors.reset}
essential Minimal components for basic functionality
standard Standard components for typical use
extended Extended components for advanced features
specialized Specialized components for specific domains
all All available context
${colors.bold}EXAMPLES:${colors.reset}
# Install essential profile (default)
bun run install-context.ts
# Install standard profile
bun run install-context.ts --profile=standard
# Install specific components
bun run install-context.ts --component=core-standards --component=openagents-repo
# Dry run to see what would be installed
bun run install-context.ts --profile=extended --dry-run
# Force reinstall
bun run install-context.ts --force --verbose
`)
}
/**
* CLI entry point
*/
async function main(): Promise<void> {
const args = process.argv.slice(2)
// Parse arguments
let profile: Profile = 'essential'
const customComponents: string[] = []
let dryRun = false
let force = false
let verbose = false
for (const arg of args) {
if (arg === '--help' || arg === '-h') {
showUsage()
process.exit(0)
} else if (arg === '--dry-run') {
dryRun = true
} else if (arg === '--force') {
force = true
} else if (arg === '--verbose' || arg === '-v') {
verbose = true
} else if (arg.startsWith('--profile=')) {
profile = arg.split('=')[1] as Profile
} else if (arg.startsWith('--component=')) {
customComponents.push(arg.split('=')[1])
} else {
log.error(`Unknown argument: ${arg}`)
showUsage()
process.exit(1)
}
}
// Run installation
const result = await installContext({
profile,
customComponents,
dryRun,
force,
verbose,
})
if (!result.success) {
process.exit(1)
}
}
// Run main function
main().catch((error) => {
console.error('Fatal error:', error)
process.exit(1)
})

View file

@ -1,239 +0,0 @@
#!/bin/bash
# load-config.sh - Load .oac configuration file
# Searches for .oac in current directory, then ~/.oac
# Exports configuration as environment variables
set -euo pipefail
# Find config file
CONFIG_FILE=""
if [[ -f ".oac" ]]; then
CONFIG_FILE=".oac"
elif [[ -f "${HOME}/.oac" ]]; then
CONFIG_FILE="${HOME}/.oac"
fi
# If no config file found, return defaults
if [[ -z "$CONFIG_FILE" ]]; then
cat <<EOF
{
"status": "no_config",
"message": "No .oac config file found. Using defaults.",
"config": {
"version": "1.0",
"context": {
"auto_download": false,
"categories": ["core", "openagents-repo"],
"update_check": true,
"cache_days": 7
},
"cleanup": {
"auto_prompt": true,
"session_days": 7,
"task_days": 30,
"external_days": 7
},
"workflow": {
"auto_approve": false,
"verbose": false
},
"external_scout": {
"enabled": true,
"cache_enabled": true,
"sources": ["context7"]
}
}
}
EOF
exit 0
fi
# Parse config file (simple key-value parsing)
declare -A CONFIG
while IFS= read -r line; do
# Skip comments and empty lines
if [[ "$line" =~ ^[[:space:]]*# ]] || [[ -z "$line" ]]; then
continue
fi
# Parse key: value pairs
if [[ "$line" =~ ^([a-z_\.]+):[[:space:]]*(.+)$ ]]; then
key="${BASH_REMATCH[1]}"
value="${BASH_REMATCH[2]}"
# Trim quotes from value
value="${value#\"}"
value="${value%\"}"
value="${value# }"
value="${value% }"
CONFIG["$key"]="$value"
fi
done < "$CONFIG_FILE"
# Helper function to get config value with default
get_config() {
local key=$1
local default=$2
echo "${CONFIG[$key]:-$default}"
}
# Helper function to convert string to boolean JSON
to_bool() {
local value=$1
if [[ "$value" == "true" ]] || [[ "$value" == "yes" ]] || [[ "$value" == "1" ]]; then
echo "true"
else
echo "false"
fi
}
# Helper function to convert comma-separated string to JSON array
to_array() {
local value=$1
local items=()
IFS=',' read -ra items <<< "$value"
local json_array="["
local first=true
for item in "${items[@]}"; do
item="${item# }"
item="${item% }"
if [[ "$first" == "true" ]]; then
first=false
else
json_array+=", "
fi
json_array+="\"$item\""
done
json_array+="]"
echo "$json_array"
}
# Extract configuration values
VERSION=$(get_config "version" "1.0")
# Context settings
CONTEXT_AUTO_DOWNLOAD=$(to_bool "$(get_config "context.auto_download" "false")")
CONTEXT_CATEGORIES=$(to_array "$(get_config "context.categories" "core,openagents-repo")")
CONTEXT_UPDATE_CHECK=$(to_bool "$(get_config "context.update_check" "true")")
CONTEXT_CACHE_DAYS=$(get_config "context.cache_days" "7")
# Cleanup settings
CLEANUP_AUTO_PROMPT=$(to_bool "$(get_config "cleanup.auto_prompt" "true")")
CLEANUP_SESSION_DAYS=$(get_config "cleanup.session_days" "7")
CLEANUP_TASK_DAYS=$(get_config "cleanup.task_days" "30")
CLEANUP_EXTERNAL_DAYS=$(get_config "cleanup.external_days" "7")
# Workflow settings
WORKFLOW_AUTO_APPROVE=$(to_bool "$(get_config "workflow.auto_approve" "false")")
WORKFLOW_VERBOSE=$(to_bool "$(get_config "workflow.verbose" "false")")
# External scout settings
EXTERNAL_SCOUT_ENABLED=$(to_bool "$(get_config "external_scout.enabled" "true")")
EXTERNAL_SCOUT_CACHE_ENABLED=$(to_bool "$(get_config "external_scout.cache_enabled" "true")")
EXTERNAL_SCOUT_SOURCES=$(to_array "$(get_config "external_scout.sources" "context7")")
# Validate configuration
VALIDATION_ERRORS=()
# Validate version
if [[ "$VERSION" != "1.0" ]]; then
VALIDATION_ERRORS+=("Invalid version: $VERSION (expected 1.0)")
fi
# Validate numeric values
if ! [[ "$CONTEXT_CACHE_DAYS" =~ ^[0-9]+$ ]]; then
VALIDATION_ERRORS+=("Invalid context.cache_days: must be a number")
fi
if ! [[ "$CLEANUP_SESSION_DAYS" =~ ^[0-9]+$ ]]; then
VALIDATION_ERRORS+=("Invalid cleanup.session_days: must be a number")
fi
if ! [[ "$CLEANUP_TASK_DAYS" =~ ^[0-9]+$ ]]; then
VALIDATION_ERRORS+=("Invalid cleanup.task_days: must be a number")
fi
if ! [[ "$CLEANUP_EXTERNAL_DAYS" =~ ^[0-9]+$ ]]; then
VALIDATION_ERRORS+=("Invalid cleanup.external_days: must be a number")
fi
# If validation errors, output error JSON
if [[ ${#VALIDATION_ERRORS[@]} -gt 0 ]]; then
ERRORS_JSON="["
first=true
for error in "${VALIDATION_ERRORS[@]}"; do
if [[ "$first" == "true" ]]; then
first=false
else
ERRORS_JSON+=", "
fi
ERRORS_JSON+="\"$error\""
done
ERRORS_JSON+="]"
cat <<EOF
{
"status": "validation_error",
"message": "Configuration validation failed",
"errors": $ERRORS_JSON,
"configFile": "$CONFIG_FILE"
}
EOF
exit 1
fi
# Export as environment variables
export OAC_CONTEXT_AUTO_DOWNLOAD="$CONTEXT_AUTO_DOWNLOAD"
export OAC_CONTEXT_CATEGORIES="$(get_config "context.categories" "core,openagents-repo")"
export OAC_CONTEXT_UPDATE_CHECK="$CONTEXT_UPDATE_CHECK"
export OAC_CONTEXT_CACHE_DAYS="$CONTEXT_CACHE_DAYS"
export OAC_CLEANUP_AUTO_PROMPT="$CLEANUP_AUTO_PROMPT"
export OAC_CLEANUP_SESSION_DAYS="$CLEANUP_SESSION_DAYS"
export OAC_CLEANUP_TASK_DAYS="$CLEANUP_TASK_DAYS"
export OAC_CLEANUP_EXTERNAL_DAYS="$CLEANUP_EXTERNAL_DAYS"
export OAC_WORKFLOW_AUTO_APPROVE="$WORKFLOW_AUTO_APPROVE"
export OAC_WORKFLOW_VERBOSE="$WORKFLOW_VERBOSE"
export OAC_EXTERNAL_SCOUT_ENABLED="$EXTERNAL_SCOUT_ENABLED"
export OAC_EXTERNAL_SCOUT_CACHE_ENABLED="$EXTERNAL_SCOUT_CACHE_ENABLED"
export OAC_EXTERNAL_SCOUT_SOURCES="$(get_config "external_scout.sources" "context7")"
# Output JSON with loaded config
cat <<EOF
{
"status": "success",
"message": "Configuration loaded successfully",
"configFile": "$CONFIG_FILE",
"config": {
"version": "$VERSION",
"context": {
"auto_download": $CONTEXT_AUTO_DOWNLOAD,
"categories": $CONTEXT_CATEGORIES,
"update_check": $CONTEXT_UPDATE_CHECK,
"cache_days": $CONTEXT_CACHE_DAYS
},
"cleanup": {
"auto_prompt": $CLEANUP_AUTO_PROMPT,
"session_days": $CLEANUP_SESSION_DAYS,
"task_days": $CLEANUP_TASK_DAYS,
"external_days": $CLEANUP_EXTERNAL_DAYS
},
"workflow": {
"auto_approve": $WORKFLOW_AUTO_APPROVE,
"verbose": $WORKFLOW_VERBOSE
},
"external_scout": {
"enabled": $EXTERNAL_SCOUT_ENABLED,
"cache_enabled": $EXTERNAL_SCOUT_CACHE_ENABLED,
"sources": $EXTERNAL_SCOUT_SOURCES
}
}
}
EOF

View file

@ -0,0 +1,188 @@
#!/usr/bin/env bun
/**
* Test script for context installer
* Tests against real GitHub repository
*/
import { existsSync } from 'fs'
import { join } from 'path'
import { fetchRegistry, filterContextByProfile } from './utils/registry-fetcher'
import { installContext } from './install-context'
const colors = {
reset: '\x1b[0m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
cyan: '\x1b[36m',
bold: '\x1b[1m',
}
function printHeader(msg: string): void {
console.log(`\n${colors.bold}${colors.cyan}${msg}${colors.reset}\n`)
}
function printSuccess(msg: string): void {
console.log(`${colors.green}✓${colors.reset} ${msg}`)
}
function printError(msg: string): void {
console.log(`${colors.red}✗${colors.reset} ${msg}`)
}
function printInfo(msg: string): void {
console.log(`${colors.blue}ℹ${colors.reset} ${msg}`)
}
async function runTests(): Promise<void> {
let passed = 0
let failed = 0
printHeader('Testing Context Installer')
printInfo('Testing against real GitHub repository')
console.log('')
// Test 1: Fetch Registry
printHeader('Test 1: Fetch Registry')
try {
const registry = await fetchRegistry({ source: 'github' })
printSuccess(`Fetched from: https://raw.githubusercontent.com/darrenhinde/OpenAgentsControl/main/registry.json`)
printSuccess(`Registry version: ${registry.version}`)
printSuccess(`Context components found: ${registry.components.contexts?.length || 0}`)
passed++
} catch (error) {
printError(`Failed to fetch registry: ${error}`)
failed++
}
console.log('')
// Test 2: Filter by Profile
printHeader('Test 2: Filter by Profile')
try {
const registry = await fetchRegistry({ source: 'github' })
const essential = filterContextByProfile(registry, 'essential')
printSuccess(`Essential profile: ${essential.length} components`)
for (const component of essential.slice(0, 5)) {
console.log(` - ${component.id}: ${component.path}`)
}
if (essential.length > 5) {
console.log(` ... and ${essential.length - 5} more`)
}
passed++
} catch (error) {
printError(`Failed to filter by profile: ${error}`)
failed++
}
console.log('')
// Test 3: Dry Run Installation
printHeader('Test 3: Dry Run Installation')
try {
const result = await installContext({
profile: 'essential',
dryRun: true,
verbose: false,
})
if (result.success) {
printSuccess('Dry run completed successfully')
printSuccess(`Would install ${result.manifest.context.length} components`)
printSuccess(`Profile: ${result.manifest.profile}`)
passed++
} else {
printError('Dry run failed')
if (result.errors) {
for (const error of result.errors) {
printError(` ${error}`)
}
}
failed++
}
} catch (error) {
printError(`Dry run error: ${error}`)
failed++
}
console.log('')
// Test 4: Actual Installation (optional - commented out by default)
// Uncomment to test actual installation
/*
printHeader('Test 4: Install Essential Profile')
try {
const result = await installContext({
profile: 'essential',
dryRun: false,
force: true,
verbose: true,
})
if (result.success) {
printSuccess('Installation complete')
printSuccess(`Installed ${result.manifest.context.length} components`)
printSuccess(`Commit: ${result.manifest.source.commit}`)
// Verify files exist
let filesExist = 0
let filesMissing = 0
for (const component of result.manifest.context) {
if (existsSync(component.local_path)) {
filesExist++
} else {
filesMissing++
printError(`Missing: ${component.id}`)
}
}
printSuccess(`Files verified: ${filesExist}/${result.manifest.context.length}`)
if (filesMissing === 0) {
passed++
} else {
printError(`${filesMissing} files missing`)
failed++
}
} else {
printError('Installation failed')
if (result.errors) {
for (const error of result.errors) {
printError(` ${error}`)
}
}
failed++
}
} catch (error) {
printError(`Installation error: ${error}`)
failed++
}
console.log('')
*/
// Summary
printHeader('Test Summary')
console.log(`Total tests: ${passed + failed}`)
printSuccess(`Passed: ${passed}`)
if (failed > 0) {
printError(`Failed: ${failed}`)
}
console.log('')
if (failed === 0) {
printSuccess('All tests passed! ✓')
} else {
printError('Some tests failed')
process.exit(1)
}
}
// Run tests
runTests().catch((error) => {
console.error('Fatal error:', error)
process.exit(1)
})

View file

@ -0,0 +1,13 @@
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "Bundler",
"resolvePackageJsonExports": true,
"resolvePackageJsonImports": true,
"target": "ES2022",
"skipLibCheck": true,
"types": ["bun-types"]
},
"include": ["**/*.ts"],
"exclude": ["node_modules"]
}

View file

@ -0,0 +1,49 @@
/**
* Manifest Type Definitions
* Schema for .context-manifest.json
*/
import { z } from 'zod'
import type { Profile } from './registry'
// Manifest component schema
export const ManifestComponentSchema = z.object({
id: z.string(),
name: z.string(),
path: z.string(),
local_path: z.string(),
category: z.string(),
})
export type ManifestComponent = z.infer<typeof ManifestComponentSchema>
// Manifest schema
export const ManifestSchema = z.object({
version: z.string(),
profile: z.union([
z.literal('essential'),
z.literal('standard'),
z.literal('extended'),
z.literal('specialized'),
z.literal('all'),
z.literal('custom'),
]),
source: z.object({
repository: z.string(),
branch: z.string(),
commit: z.string(),
downloaded_at: z.string(),
}),
context: z.array(ManifestComponentSchema),
})
export type Manifest = z.infer<typeof ManifestSchema>
// Manifest creation options
export interface CreateManifestOptions {
profile: Profile | 'custom'
repository: string
branch: string
commit: string
components: ManifestComponent[]
}

View file

@ -0,0 +1,81 @@
/**
* Registry Type Definitions
* Schema for OpenAgents Control registry.json
*/
import { z } from 'zod'
// Component schema
export const ComponentSchema = z.object({
id: z.string(),
name: z.string(),
type: z.string(),
path: z.string(),
description: z.string().optional(),
tags: z.array(z.string()).optional(),
dependencies: z.array(z.string()).optional(),
category: z.string(),
files: z.array(z.string()).optional(),
aliases: z.array(z.string()).optional(),
version: z.string().optional(),
})
export type Component = z.infer<typeof ComponentSchema>
// Registry schema
export const RegistrySchema = z.object({
version: z.string(),
schema_version: z.string(),
repository: z.string(),
categories: z.record(z.string()),
components: z.object({
agents: z.array(ComponentSchema).optional(),
subagents: z.array(ComponentSchema).optional(),
commands: z.array(ComponentSchema).optional(),
tools: z.array(ComponentSchema).optional(),
plugins: z.array(ComponentSchema).optional(),
skills: z.array(ComponentSchema).optional(),
contexts: z.array(ComponentSchema).optional(),
config: z.array(ComponentSchema).optional(),
}),
})
export type Registry = z.infer<typeof RegistrySchema>
// Profile types
export type Profile = 'essential' | 'standard' | 'extended' | 'specialized' | 'all'
// Installation options
export interface InstallOptions {
profile?: Profile
customComponents?: string[]
dryRun?: boolean
force?: boolean
verbose?: boolean
}
// Installation result
export interface InstallResult {
success: boolean
manifest: InstallManifest
errors?: string[]
}
// Manifest types (defined in manifest.ts but referenced here)
export interface InstallManifest {
version: string
profile: Profile | 'custom'
source: {
repository: string
branch: string
commit: string
downloaded_at: string
}
context: Array<{
id: string
name: string
path: string
local_path: string
category: string
}>
}

View file

@ -0,0 +1,135 @@
/**
* Git Sparse Checkout Utilities
* Handles git sparse-checkout operations for downloading specific paths
*/
import { execSync } from 'child_process'
import { existsSync, rmSync, mkdirSync } from 'fs'
import { join } from 'path'
export interface GitSparseOptions {
repository: string
branch: string
paths: string[]
targetDir: string
verbose?: boolean
}
export interface GitSparseResult {
success: boolean
commit: string
error?: string
}
/**
* Clone repository with sparse checkout
*/
export async function sparseClone(
options: GitSparseOptions
): Promise<GitSparseResult> {
const { repository, branch, paths, targetDir, verbose } = options
try {
// Clean up target directory if it exists
if (existsSync(targetDir)) {
rmSync(targetDir, { recursive: true, force: true })
}
// Create parent directory
const parentDir = join(targetDir, '..')
if (!existsSync(parentDir)) {
mkdirSync(parentDir, { recursive: true })
}
// Clone with sparse checkout (no working tree files)
if (verbose) {
console.log(`Cloning ${repository}...`)
}
execSync(
`git clone --depth 1 --filter=blob:none --sparse --branch ${branch} https://github.com/${repository}.git "${targetDir}"`,
{ stdio: verbose ? 'inherit' : 'pipe' }
)
// Configure sparse checkout for requested paths
if (verbose) {
console.log('Configuring sparse checkout...')
}
const sparseCheckoutPaths = paths.join(' ')
execSync(`cd "${targetDir}" && git sparse-checkout set ${sparseCheckoutPaths}`, {
stdio: verbose ? 'inherit' : 'pipe',
})
// Get commit SHA
const commit = execSync(`cd "${targetDir}" && git rev-parse HEAD`, {
encoding: 'utf-8',
}).trim()
if (verbose) {
console.log(`Downloaded commit: ${commit}`)
}
return {
success: true,
commit,
}
} catch (error) {
return {
success: false,
commit: '',
error: error instanceof Error ? error.message : String(error),
}
}
}
/**
* Copy files from sparse checkout to target location
*/
export function copyFiles(
sourceDir: string,
targetDir: string,
verbose?: boolean
): void {
if (!existsSync(sourceDir)) {
throw new Error(`Source directory not found: ${sourceDir}`)
}
// Create target directory if it doesn't exist
if (!existsSync(targetDir)) {
mkdirSync(targetDir, { recursive: true })
}
// Copy files
if (verbose) {
console.log(`Copying files from ${sourceDir} to ${targetDir}...`)
}
execSync(`cp -r "${sourceDir}"/* "${targetDir}"/`, {
stdio: verbose ? 'inherit' : 'pipe',
})
}
/**
* Clean up temporary directory
*/
export function cleanup(dir: string, verbose?: boolean): void {
if (existsSync(dir)) {
if (verbose) {
console.log(`Cleaning up ${dir}...`)
}
rmSync(dir, { recursive: true, force: true })
}
}
/**
* Check if git is available
*/
export function checkGitAvailable(): boolean {
try {
execSync('command -v git', { stdio: 'ignore' })
return true
} catch {
return false
}
}

View file

@ -0,0 +1,119 @@
/**
* Registry Fetcher
* Fetches and parses registry.json from GitHub
*/
import { RegistrySchema, type Registry, type Component, type Profile } from '../types/registry'
export interface FetchRegistryOptions {
source?: 'github' | 'local'
repository?: string
branch?: string
localPath?: string
}
/**
* Fetch registry from GitHub or local file
*/
export async function fetchRegistry(
options: FetchRegistryOptions = {}
): Promise<Registry> {
const {
source = 'github',
repository = 'darrenhinde/OpenAgentsControl',
branch = 'main',
localPath,
} = options
let registryData: unknown
if (source === 'github') {
// Fetch from GitHub raw URL
const url = `https://raw.githubusercontent.com/${repository}/${branch}/registry.json`
const response = await fetch(url)
if (!response.ok) {
throw new Error(`Failed to fetch registry: ${response.statusText}`)
}
registryData = await response.json()
} else {
// Load from local file
if (!localPath) {
throw new Error('localPath required for local source')
}
const fs = await import('fs/promises')
const content = await fs.readFile(localPath, 'utf-8')
registryData = JSON.parse(content)
}
// Validate with Zod
const registry = RegistrySchema.parse(registryData)
return registry
}
/**
* Filter context components by profile
*/
export function filterContextByProfile(
registry: Registry,
profile: Profile
): Component[] {
const contexts = registry.components.contexts || []
if (profile === 'all') {
return contexts
}
// Map profiles to categories
const profileCategories: Record<Profile, string[]> = {
essential: ['essential', 'core'],
standard: ['essential', 'core', 'standard'],
extended: ['essential', 'core', 'standard', 'extended'],
specialized: ['essential', 'core', 'standard', 'extended', 'specialized'],
all: [], // handled above
}
const categories = profileCategories[profile]
if (!categories) {
throw new Error(`Unknown profile: ${profile}`)
}
return contexts.filter((component) => categories.includes(component.category))
}
/**
* Filter context components by custom IDs
*/
export function filterContextByIds(
registry: Registry,
componentIds: string[]
): Component[] {
const contexts = registry.components.contexts || []
return contexts.filter((component) => componentIds.includes(component.id))
}
/**
* Get unique paths from components
*/
export function getUniquePaths(components: Component[]): string[] {
const paths = new Set<string>()
for (const component of components) {
// Extract directory path from component path
const pathParts = component.path.split('/')
pathParts.pop() // Remove filename
const dirPath = pathParts.join('/')
if (dirPath) {
paths.add(dirPath)
}
}
return Array.from(paths)
}

View file

@ -1,218 +0,0 @@
#!/usr/bin/env bash
# verify-context.sh - Validate context structure for Claude Code plugin
# Exit codes: 0 (valid), 1 (invalid)
set -euo pipefail
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Counters
ERRORS=0
WARNINGS=0
# Get plugin root directory
PLUGIN_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
CONTEXT_DIR="${PLUGIN_ROOT}/context"
MANIFEST_FILE="${PLUGIN_ROOT}/.context-manifest.json"
echo "🔍 Verifying context structure..."
echo ""
# Function to report error
error() {
echo -e "${RED}✗ ERROR:${NC} $1"
((ERRORS++))
}
# Function to report warning
warning() {
echo -e "${YELLOW}⚠ WARNING:${NC} $1"
((WARNINGS++))
}
# Function to report success
success() {
echo -e "${GREEN}✓${NC} $1"
}
# Check 1: Context directory exists
echo "Checking context directory..."
if [[ ! -d "$CONTEXT_DIR" ]]; then
error "Context directory not found: $CONTEXT_DIR"
else
success "Context directory exists"
fi
# Check 2: Required top-level categories exist
echo ""
echo "Checking required categories..."
REQUIRED_CATEGORIES=(
"core"
"openagents-repo"
"development"
"ui"
"content-creation"
"data"
"product"
"learning"
)
for category in "${REQUIRED_CATEGORIES[@]}"; do
if [[ ! -d "$CONTEXT_DIR/$category" ]]; then
warning "Missing category: $category"
else
success "Category exists: $category"
fi
done
# Check 3: Navigation files exist
echo ""
echo "Checking navigation files..."
# Main navigation
if [[ ! -f "$CONTEXT_DIR/navigation.md" ]]; then
error "Missing main navigation.md"
else
success "Main navigation.md exists"
# Validate navigation.md structure
if ! grep -q "^# Context Navigation" "$CONTEXT_DIR/navigation.md"; then
warning "navigation.md missing expected header"
fi
fi
# Category navigation files
for category in "${REQUIRED_CATEGORIES[@]}"; do
NAV_FILE="$CONTEXT_DIR/$category/navigation.md"
if [[ -d "$CONTEXT_DIR/$category" ]] && [[ ! -f "$NAV_FILE" ]]; then
warning "Missing navigation.md in $category/"
fi
done
# Check 4: Core standards exist
echo ""
echo "Checking core standards..."
CORE_STANDARDS=(
"core/standards/code-quality.md"
"core/standards/documentation.md"
"core/standards/test-coverage.md"
)
for standard in "${CORE_STANDARDS[@]}"; do
if [[ ! -f "$CONTEXT_DIR/$standard" ]]; then
warning "Missing core standard: $standard"
else
success "Found: $standard"
fi
done
# Check 5: Validate .context-manifest.json
echo ""
echo "Checking .context-manifest.json..."
if [[ ! -f "$MANIFEST_FILE" ]]; then
warning ".context-manifest.json not found (run download-context.sh first)"
else
success ".context-manifest.json exists"
# Validate JSON format
if ! jq empty "$MANIFEST_FILE" 2>/dev/null; then
error ".context-manifest.json is not valid JSON"
else
success ".context-manifest.json is valid JSON"
# Check required fields
REQUIRED_FIELDS=("version" "source" "updated_at" "categories")
for field in "${REQUIRED_FIELDS[@]}"; do
if ! jq -e ".$field" "$MANIFEST_FILE" >/dev/null 2>&1; then
error ".context-manifest.json missing required field: $field"
else
success "Manifest has field: $field"
fi
done
fi
fi
# Check 6: Validate context file metadata
echo ""
echo "Checking context file metadata..."
CONTEXT_FILES=$(find "$CONTEXT_DIR" -name "*.md" -type f 2>/dev/null || true)
CHECKED_FILES=0
INVALID_FILES=0
for file in $CONTEXT_FILES; do
# Skip navigation files (they have different format)
if [[ "$file" == *"/navigation.md" ]]; then
continue
fi
((CHECKED_FILES++))
# Check for context metadata comment
if ! head -n 1 "$file" | grep -q "^<!-- Context:"; then
((INVALID_FILES++))
if [[ $INVALID_FILES -le 5 ]]; then
warning "Missing context metadata: ${file#$CONTEXT_DIR/}"
fi
fi
done
if [[ $CHECKED_FILES -gt 0 ]]; then
if [[ $INVALID_FILES -eq 0 ]]; then
success "All $CHECKED_FILES context files have metadata"
else
warning "$INVALID_FILES of $CHECKED_FILES files missing metadata"
fi
fi
# Check 7: Verify no broken internal links
echo ""
echo "Checking for broken internal links..."
BROKEN_LINKS=0
for file in $CONTEXT_FILES; do
# Extract markdown links
while IFS= read -r link; do
# Skip external links
if [[ "$link" =~ ^https?:// ]]; then
continue
fi
# Resolve relative path
FILE_DIR=$(dirname "$file")
LINK_PATH="$FILE_DIR/$link"
if [[ ! -f "$LINK_PATH" ]]; then
((BROKEN_LINKS++))
if [[ $BROKEN_LINKS -le 5 ]]; then
warning "Broken link in ${file#$CONTEXT_DIR/}: $link"
fi
fi
done < <(grep -oP '\[.*?\]\(\K[^)]+' "$file" 2>/dev/null || true)
done
if [[ $BROKEN_LINKS -eq 0 ]]; then
success "No broken internal links found"
elif [[ $BROKEN_LINKS -gt 5 ]]; then
warning "Found $BROKEN_LINKS broken links (showing first 5)"
fi
# Summary
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Summary:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
if [[ $ERRORS -eq 0 ]] && [[ $WARNINGS -eq 0 ]]; then
echo -e "${GREEN}✓ Context structure is valid${NC}"
exit 0
elif [[ $ERRORS -eq 0 ]]; then
echo -e "${YELLOW}⚠ Context structure is valid with $WARNINGS warnings${NC}"
exit 0
else
echo -e "${RED}✗ Context structure has $ERRORS errors and $WARNINGS warnings${NC}"
exit 1
fi

View file

@ -1,44 +1,44 @@
---
name: code-execution
description: Execute coding subtasks with self-review and quality validation. Use when implementing features, refactoring code, creating new files, or modifying existing code. Invokes the coder-agent subagent for isolated execution.
description: Use when a subtask is ready to implement and has a subtask JSON file with acceptance criteria and deliverables.
context: fork
agent: coder-agent
---
# Code Execution Skill
# Code Execution
Execute coding subtask: $ARGUMENTS
## Overview
Execute coding subtasks with self-review and quality validation. Runs in isolated coder-agent context with pre-loaded standards.
## Context
**Announce at start:** "I'm using the code-execution skill to implement [subtask title]."
You are running in the **coder-agent subagent** with isolated context. The main agent has pre-loaded all necessary context files and created the subtask JSON.
## Your Task
1. **Read the subtask JSON** at the path provided in $ARGUMENTS
2. **Load all context_files** listed in the subtask (standards, patterns, conventions)
3. **Load all reference_files** to understand existing code patterns
4. **Implement deliverables** following acceptance criteria exactly
5. **Run self-review** (type validation, import verification, anti-pattern scan)
6. **Mark subtask complete** using task-cli.ts
7. **Return completion report** to main agent
## Workflow
## The Process
### Step 1: Read Subtask JSON
The subtask path is: $ARGUMENTS
Load the subtask file specified in $ARGUMENTS:
Read it to understand:
```bash
Read: .tmp/tasks/{feature}/subtask_{seq}.json
```
Extract:
- `title` — What to implement
- `acceptance_criteria` — What defines success
- `deliverables` — Files/endpoints to create
- `context_files` — Standards to apply (pre-discovered by main agent)
- `context_files` — Standards to apply
- `reference_files` — Existing code to study
### Step 2: Load Context Files
Read each file in `context_files` to understand:
Read each file in `context_files`:
```bash
Read: .opencode/context/core/standards/code-quality.md
Read: .opencode/context/core/standards/security-patterns.md
```
Understand:
- Project coding standards
- Naming conventions
- Security patterns
@ -46,14 +46,20 @@ Read each file in `context_files` to understand:
### Step 3: Load Reference Files
Read each file in `reference_files` to understand:
Read each file in `reference_files`:
```bash
Read: src/middleware/auth.middleware.ts
```
Study:
- Existing patterns
- Code structure
- Conventions already in use
- Conventions in use
### Step 4: Update Status
### Step 4: Update Status to In Progress
Use `edit` to update the subtask JSON:
Edit subtask JSON:
```json
"status": "in_progress",
@ -65,119 +71,103 @@ Use `edit` to update the subtask JSON:
For each deliverable:
- Create or modify the specified file
- Follow acceptance criteria exactly
- Follow acceptance criteria EXACTLY
- Apply standards from context_files
- Use patterns from reference_files
- Write clean, modular, functional code
### Step 6: Self-Review (MANDATORY)
### Step 6: Run Self-Review (MANDATORY)
Run ALL checks:
**Type & Import Validation:**
- ✅ Function signatures match usage
- ✅ All imports/exports exist
- ✅ No missing type annotations
- ✅ No circular dependencies
**Type & Import Validation**:
- Verify function signatures match usage
- Confirm all imports/exports exist
- Check for missing type annotations
- Verify no circular dependencies
**Anti-Pattern Scan:**
```bash
grep "console.log" deliverables # NO debug statements
grep "TODO\|FIXME" deliverables # NO unfinished work
grep "api[_-]key\|secret" deliverables # NO hardcoded secrets
```
**Anti-Pattern Scan** (use `grep`):
- `console.log` — debug statements
- `TODO` or `FIXME` — unfinished work
- Hardcoded secrets or API keys
- Missing error handling in async functions
- `any` types where specific types required
**Acceptance Criteria Verification**:
- Re-read acceptance_criteria array
- Confirm EACH criterion is met
- Fix any unmet criteria before proceeding
**Acceptance Criteria Check:**
- Re-read `acceptance_criteria` array
- Confirm EACH criterion met
- Fix unmet criteria before proceeding
### Step 7: Mark Complete
Update subtask status:
```bash
bash .opencode/skills/task-management/router.sh complete {feature} {seq} "{completion_summary}"
bash .opencode/skills/task-management/router.sh complete {feature} {seq} "{summary}"
```
Verify completion:
Verify:
```bash
bash .opencode/skills/task-management/router.sh status {feature}
```
### Step 8: Return Completion Report
Report to main agent:
### Step 8: Return Report
```
✅ Subtask {feature}-{seq} COMPLETED
Self-Review: ✅ Types clean | ✅ Imports verified | ✅ No debug artifacts | ✅ All acceptance criteria met
Self-Review: ✅ Types | ✅ Imports | ✅ No debug code | ✅ Criteria met
Deliverables:
- {file1}
- {file2}
- {file3}
- src/auth/jwt.service.ts
- src/auth/jwt.service.test.ts
Summary: {completion_summary}
Summary: JWT service with RS256 signing and 15min token expiry
```
## Principles
## Error Handling
- **Context first, code second** — Always read context_files before implementing
- **One subtask at a time** — Complete fully before moving on
- **Self-review is mandatory** — Quality gate before signaling done
- **Functional, declarative, modular** — Clean code patterns
- **Return results to main agent** — Report completion for orchestration
**Missing subtask JSON:**
- Main agent must create subtask before invoking this skill
## When Main Agent Should Use This Skill
**Context files not found:**
- Main agent must run `/context-discovery` first
The main agent should invoke this skill when:
**Acceptance criteria unmet:**
- DO NOT mark complete—fix issues first
- **Implementing new features** — Creating new files, functions, or modules
- **Refactoring existing code** — Improving structure, performance, or maintainability
- **Fixing bugs** — Modifying code to resolve issues
- **Adding functionality** — Extending existing code with new capabilities
- **Creating tests** — Writing unit, integration, or e2e tests (though test-generation skill is preferred)
## Red Flags
## What Main Agent Must Do First
If you think any of these, STOP and re-read this skill:
Before invoking this skill, the main agent MUST:
- "I know the pattern, I don't need to read the context files"
- "I'll do the self-review quickly at the end"
- "The acceptance criteria are obvious, I don't need to check them"
- "I'll mark it done and fix the edge cases later"
1. **Discover context** using context-discovery skill
2. **Create subtask JSON** with all required fields:
- `title`, `acceptance_criteria`, `deliverables`
- `context_files` (from context-discovery)
- `reference_files` (existing code to study)
3. **Get approval** from user for the implementation plan
4. **Pass subtask JSON path** as $ARGUMENTS to this skill
## Common Rationalizations
## Example Usage
| Excuse | Reality |
|--------|---------|
| "I've seen this pattern before, context files will just confirm what I know" | Projects diverge from common patterns. One wrong assumption = rework. Read the files. |
| "Self-review is just checking my own work" | Self-review catches type errors, missing imports, and debug code before the main agent sees it. |
| "The criteria are implied by the task title" | Implied criteria are unverifiable. If it's not written, it's not a gate. |
| "I'll handle edge cases in a follow-up" | Edge cases left for follow-up become bugs in production. Handle them now. |
Main agent workflow:
## Remember
```
1. User: "Implement JWT authentication"
- Context FIRST, code SECOND—always read context_files before implementing
- One subtask at a time—complete fully before moving on
- Self-review is MANDATORY—quality gate before marking done
- Functional, declarative, modular—clean code patterns only
- Return results to main agent—report completion for orchestration
2. Main agent invokes: /context-discovery "JWT authentication patterns"
→ Returns: security patterns, auth standards, coding conventions
## Related
3. Main agent creates: .tmp/tasks/auth-system/subtask_01.json
→ Includes: context_files, acceptance_criteria, deliverables
- context-discovery
- task-breakdown
- test-generation
- code-review
4. Main agent presents plan and gets approval
---
5. Main agent invokes: /code-execution ".tmp/tasks/auth-system/subtask_01.json"
→ Coder-agent executes in isolated context
→ Returns completion report
6. Main agent continues orchestration
```
## Notes
- This skill runs in **isolated context** (coder-agent subagent)
- Context files are **pre-loaded** by main agent (no nested ContextScout calls)
- Results are **returned to main agent** for orchestration
- Main agent handles **workflow progression** and **approval gates**
**Task**: Execute coding subtask: **$ARGUMENTS**

View file

@ -1,232 +1,162 @@
---
name: code-review
description: Review code for security, correctness, and quality before commits or after refactoring. Use when you need to validate code changes, check for security vulnerabilities, or ensure code quality standards are met.
description: Use when code has been written and needs validation before committing, or when the user asks for a code review or security check.
context: fork
agent: code-reviewer
---
# Code Review Skill
# Code Review
Review code changes using the specialized code-reviewer subagent. This skill performs comprehensive code analysis for security vulnerabilities, correctness issues, style violations, and maintainability concerns.
## Overview
Review code for security, correctness, and quality. Runs in isolated code-reviewer context with pre-loaded standards.
## When to Use This Skill
**Announce at start:** "I'm using the code-review skill to validate [files/feature]."
Invoke `/code-review` when:
## The Process
- **Before committing code** — validate changes meet quality standards
- **After refactoring** — ensure refactored code maintains correctness
- **Security-sensitive changes** — review authentication, authorization, data handling
- **Complex logic changes** — verify correctness of algorithms or business logic
- **Before pull requests** — catch issues before code review
- **After dependency updates** — check for breaking changes or security issues
### Step 1: Pre-Load Context (Main Agent)
## How to Use
### Basic Usage
Load standards BEFORE invoking review:
```bash
Read: .opencode/context/core/standards/code-quality.md
Read: .opencode/context/core/standards/security-patterns.md
```
### Step 2: Invoke Review
```bash
/code-review path/to/file.ts
```
### Review Multiple Files
```
/code-review src/auth/*.ts
```
### Review with Specific Focus
```
/code-review src/api/handler.ts --focus security
```
### Review Recent Changes
```
/code-review $(git diff --name-only HEAD~1)
```
## Pre-Loading Context (IMPORTANT)
### Step 3: Analyze Report
**Before invoking this skill**, the main agent should load relevant context files:
1. **Code Quality Standards** — `.opencode/context/core/standards/code-quality.md`
2. **Security Patterns** — `.opencode/context/core/standards/security-patterns.md`
3. **TypeScript Standards** — `.opencode/context/core/standards/typescript.md`
4. **Project-Specific Conventions** — Any project naming or style guides
**Example workflow**:
```markdown
1. Read code quality standards
2. Read security patterns
3. Invoke /code-review with file paths
4. Interpret results (see below)
```
## What the Reviewer Checks
The code-reviewer subagent performs a comprehensive analysis:
### 🔴 CRITICAL (Security Vulnerabilities)
- SQL injection risks
- XSS vulnerabilities
- Hardcoded credentials or API keys
- Path traversal risks
- Command injection
- Exposed secrets
- Missing authentication/authorization
### 🟠 HIGH (Correctness Issues)
- Missing error handling (async without try/catch)
- Type mismatches
- Null/undefined handling gaps
- Logic errors (off-by-one, race conditions)
- Missing imports or circular dependencies
### 🟡 MEDIUM (Style & Maintainability)
- Naming convention violations
- Code duplication (DRY violations)
- Poor code organization
- Missing comments on complex logic
- Overly complex functions
### 🟢 LOW (Suggestions)
- Performance optimizations
- Documentation improvements
- Test coverage gaps
- Refactoring opportunities
## Interpreting Results
The code-reviewer returns a structured report:
Code-reviewer returns structured findings:
```markdown
## Code Review: [Feature/File]
## Code Review: Auth Service
### 🔴 CRITICAL Issues (Must Fix)
1. **SQL Injection Risk** — `src/db/query.ts:42`
- **Problem**: Unparameterized query with user input
- **Risk**: Database compromise
- **Fix**: Use parameterized queries
- **Diff**:
### 🔴 CRITICAL (Must Fix)
1. **SQL Injection Risk** — src/db/query.ts:42
- Problem: Unparameterized query with user input
- Risk: Database compromise
- Fix:
```diff
- db.query(`SELECT * FROM users WHERE id = ${userId}`)
+ db.query('SELECT * FROM users WHERE id = ?', [userId])
```
### 🟠 HIGH (Correctness)
2. **Missing Error Handling** — src/auth/service.ts:28
- Problem: Async function without try/catch
- Risk: Unhandled promise rejection
- Fix: Wrap in try/catch with proper logging
### 🟡 MEDIUM (Style)
3. **Naming Convention** — src/auth/middleware.ts:15
- Problem: snake_case instead of camelCase
- Fix: Rename verify_token → verifyToken
### Summary
- **Total Issues**: 12 (3 Critical, 4 High, 3 Medium, 2 Low)
- **Blocking Issues**: 7
- **Recommendation**: REQUEST CHANGES
Total Issues: 3 (1 Critical, 1 High, 1 Medium)
Recommendation: REQUEST CHANGES
```
## Action Based on Results
### Step 4: Take Action
### If CRITICAL or HIGH issues found:
1. **STOP** — Do not commit or merge
2. **Fix issues** — Apply suggested changes
3. **Re-review** — Run `/code-review` again after fixes
4. **Verify** — Ensure all blocking issues resolved
**If CRITICAL or HIGH issues:**
1. STOP—do not commit
2. Fix issues using suggested diffs
3. Re-run `/code-review` to verify
4. Proceed only when clean
### If only MEDIUM or LOW issues:
1. **Evaluate** — Decide if fixes should be in this PR or follow-up
2. **Apply fixes** — Address issues that improve code quality
3. **Document** — If deferring fixes, create follow-up tasks
4. **Proceed** — Safe to commit/merge
**If only MEDIUM or LOW issues:**
1. Evaluate whether to fix now or later
2. Apply quality improvements
3. Safe to commit
### If no issues found:
1. **Celebrate** — Code meets quality standards
2. **Commit** — Proceed with confidence
3. **Document** — Note positive patterns for team learning
**If no issues:**
1. Commit with confidence
2. Note positive patterns
## Example Workflow
## Review Checks
### Scenario: Review authentication changes before commit
**🔴 CRITICAL (Security):**
- SQL injection, XSS, command injection
- Hardcoded credentials or secrets
- Path traversal, auth bypass
```markdown
**Step 1: Load Context**
Read the following files:
- .opencode/context/core/standards/security-patterns.md
- .opencode/context/core/standards/code-quality.md
**🟠 HIGH (Correctness):**
- Missing error handling
- Type mismatches
- Null/undefined gaps
- Logic errors, race conditions
**Step 2: Invoke Review**
/code-review src/auth/service.ts src/auth/middleware.ts
**🟡 MEDIUM (Maintainability):**
- Naming violations
- Code duplication
- Poor organization
**Step 3: Analyze Results**
Review report shows:
- 1 CRITICAL: Hardcoded JWT secret
- 2 HIGH: Missing error handling in async functions
- 1 MEDIUM: Inconsistent naming (camelCase vs snake_case)
**🟢 LOW (Suggestions):**
- Performance optimizations
- Documentation improvements
**Step 4: Take Action**
- Fix CRITICAL: Move JWT secret to environment variable
- Fix HIGH: Add try/catch blocks with proper error logging
- Fix MEDIUM: Standardize naming to camelCase
- Re-run /code-review to verify fixes
## Error Handling
**Step 5: Commit**
All blocking issues resolved → Safe to commit
```
**Review fails:**
- Ensure context files pre-loaded
## Integration with OAC Workflow
**Too many findings:**
- Fix CRITICAL first, then re-review
This skill integrates with the OpenAgents Control 6-stage workflow:
**Unclear findings:**
- Request clarification in report
- **Stage 4 (Execute)**: After implementing code, invoke `/code-review` before marking complete
- **Stage 5 (Validate)**: Use review results as validation gate
- **Stage 6 (Complete)**: Only proceed if no blocking issues
## Red Flags
## Tips for Effective Reviews
If you think any of these, STOP and re-read this skill:
1. **Review early and often** — Catch issues before they compound
2. **Focus reviews** — Use `--focus security` for security-sensitive changes
3. **Review incrementally** — Review files as you complete them, not all at once
4. **Learn from findings** — Positive observations highlight good patterns
5. **Pre-load context** — Always load standards before reviewing
6. **Act on results** — Don't ignore CRITICAL or HIGH findings
- "The code looks fine, a review is overkill"
- "I wrote it, I know it's correct"
- "We're in a hurry, we can review later"
- "It's a small change, no security risk"
## What the Reviewer Does NOT Do
## Common Rationalizations
- ❌ **Does not modify code** — Provides suggested diffs only
- ❌ **Does not run tests** — Use `/test-generation` skill for testing
- ❌ **Does not deploy** — Review is a quality gate, not deployment
- ❌ **Does not replace human review** — Complements, doesn't replace peer review
| Excuse | Reality |
|--------|---------|
| "I just wrote it so I know it's right" | The author is the worst reviewer. Fresh eyes catch what familiarity hides. |
| "It's a small change" | Security vulnerabilities are almost always in small, "obvious" changes. |
| "We can review after merging" | Post-merge review finds bugs in production. Pre-merge review finds them for free. |
| "There's no user input so no injection risk" | Internal data becomes user input when requirements change. Review now. |
## Related Skills
## Remember
- `/context-discovery` — Find code quality standards before reviewing
- `/test-generation` — Generate tests for reviewed code
- `/code-execution` — Implement fixes suggested by reviewer
- Pre-load standards BEFORE invoking review
- CRITICAL and HIGH issues BLOCK commits
- Apply suggested fixes with code diffs
- Re-review after fixing blocking issues
- Review does NOT modify code—only suggests changes
- Review does NOT run tests—use test-generation for that
## Related
- context-discovery
- code-execution
- test-generation
---
## Skill Execution
**Task**: Review the following files: **$ARGUMENTS**
When you invoke `/code-review $ARGUMENTS`, this skill:
**Instructions for code-reviewer subagent:**
1. **Forks to code-reviewer subagent** — Isolated context for focused review
2. **Passes file paths** — `$ARGUMENTS` contains files to review
3. **Expects pre-loaded context** — Main agent should load standards first
4. **Returns structured report** — Findings organized by severity
5. **Exits back to main agent** — Results available for action
**Review the following files**: $ARGUMENTS
**Instructions for code-reviewer subagent**:
1. Read all files specified in the arguments
2. Apply pre-loaded code quality standards, security patterns, and conventions
3. Perform comprehensive analysis:
- Security scan (HIGHEST PRIORITY)
- Correctness review
- Style & convention check
- Performance & maintainability assessment
4. Structure findings by severity (CRITICAL → HIGH → MEDIUM → LOW)
5. For each finding, provide:
- Clear problem description
- Risk/impact assessment
- Suggested fix with code diff
6. Include positive observations (what was done well)
7. Return structured report with recommendation (APPROVE | REQUEST CHANGES | COMMENT)
**Output format**: Use the structured markdown format defined in the code-reviewer agent (see Step 8 of Review Workflow).
1. Read all files in $ARGUMENTS
2. Apply pre-loaded standards (code quality, security, conventions)
3. Scan for: Security (HIGHEST PRIORITY) → Correctness → Style → Performance
4. Structure findings by severity: CRITICAL → HIGH → MEDIUM → LOW
5. For each finding: Problem + Risk + Suggested fix with diff
6. Include positive observations
7. Return recommendation: APPROVE | REQUEST CHANGES | COMMENT

View file

@ -1,299 +1,113 @@
---
name: context-discovery
description: Discover context files for a task. Use when you need coding standards, security patterns, workflows, or project-specific context before implementing a feature. Invokes the context-scout subagent to find and rank relevant files from .opencode/context/.
description: Use when coding standards, security patterns, or project conventions need to be discovered before implementation begins.
context: fork
agent: context-scout
---
# Context Discovery Skill
# Context Discovery
> **Purpose**: Discover and load context files before implementing features. This skill invokes the `context-scout` subagent to find relevant standards, patterns, and workflows from `.opencode/context/`.
## Overview
Discover project standards and patterns before implementing features. Context-scout finds and ranks relevant files from `.opencode/context/` based on your request.
---
**Announce at start:** "I'm using the context-discovery skill to find relevant standards for [feature/task]."
## When to Use This Skill
## The Process
Invoke `/context-discovery` when you need to:
### Step 1: Invoke Context-Scout
- **Find coding standards** before writing code
- **Discover security patterns** before implementing auth, data handling, or user input
- **Locate workflow guides** before breaking down complex tasks
- **Find project-specific context** before modifying existing features
- **Identify naming conventions** before creating new files or modules
- **Understand architectural patterns** before designing new components
Run the skill with your implementation topic:
**Rule of thumb**: If you're about to write code or create a plan, discover context FIRST.
---
## How It Works
This skill runs in the `context-scout` subagent (isolated context) and:
1. **Analyzes your request** — Understands what context you need
2. **Follows navigation** — Discovers files via `.opencode/context/navigation.md`
3. **Ranks results** — Returns Critical → High → Medium priority files
4. **Returns to main agent** — You load the recommended files
---
## Usage
### Basic Usage
```
```bash
/context-discovery [what you're implementing]
```
**Examples**:
```
/context-discovery authentication system
/context-discovery React component with animations
/context-discovery task breakdown workflow
/context-discovery TypeScript coding standards
```
**Examples:**
- `/context-discovery JWT authentication`
- `/context-discovery React form validation`
- `/context-discovery database migration workflow`
### What You'll Get Back
### Step 2: Load Critical Priority Files
The context-scout subagent returns a ranked list of context files:
Read EVERY file marked **Critical Priority**:
```markdown
# Context Files Found
## Critical Priority
**File**: `.opencode/context/core/standards/code-quality.md`
**Contains**: Code quality standards, functional patterns, error handling
**Why**: Defines coding patterns you must follow for all implementations
## High Priority
**File**: `.opencode/context/core/standards/security-patterns.md`
**Contains**: Security best practices, auth patterns, data protection
**Why**: Important for secure implementation
## Medium Priority
**File**: `.opencode/context/core/workflows/approval-gates.md`
**Contains**: When to request approval before execution
**Why**: Helps you know when to pause for approval
---
**Summary**: Found 3 context files. Start with Critical priority files.
```
---
## What to Do with Results
### Step 1: Load Critical Priority Files
Read every file marked as **Critical Priority** before proceeding:
```
```bash
Read: .opencode/context/core/standards/code-quality.md
Read: .opencode/context/core/standards/security-patterns.md
```
These files contain **must-follow** standards and patterns.
These are **mandatory**—proceed only after loading.
### Step 2: Load High Priority Files
### Step 3: Load High Priority Files
Read **High Priority** files for important context:
Read files marked **High Priority**:
```
```bash
Read: .opencode/context/core/workflows/approval-gates.md
```
These files provide **strongly recommended** guidance.
These are **strongly recommended** for your implementation.
### Step 3: Load Medium Priority Files (Optional)
### Step 4: Load Medium Priority (If Needed)
Read **Medium Priority** files if you need additional context:
Read **Medium Priority** files for additional context:
```
```bash
Read: .opencode/context/project-intelligence/architecture.md
```
These files are **helpful but not required**.
These are **optional but helpful**.
### Step 4: Apply Context to Your Work
### Step 5: Apply to Implementation
- **Follow standards** from loaded files
- **Apply patterns** to your implementation
- **Check workflows** before executing
- **Use naming conventions** from context
- Follow standards from loaded files
- Apply patterns to your code
- Use naming conventions discovered
- Check workflows before executing
---
## Delegation Pattern
## Passing Results to Other Subagents
When you need to delegate work to another subagent (e.g., `coder-agent`, `task-manager`), include the discovered context files in your delegation:
### Example: Task Breakdown with Context
When invoking subagents, pass discovered context files:
```markdown
Invoke task-manager subagent:
Invoke coder-agent:
**Task**: Break down authentication system into subtasks
Task: Implement JWT service
**Context to load first**:
Context to load:
- .opencode/context/core/standards/code-quality.md
- .opencode/context/core/standards/security-patterns.md
- .opencode/context/core/workflows/task-delegation-basics.md
**Instructions**: Create subtask files following the task.json schema. Apply security patterns from context.
Instructions: Follow functional patterns and security best practices.
```
### Example: Code Implementation with Context
## Error Handling
```markdown
Invoke coder-agent subagent:
**"No context files found"**
- Run `/install-context` to download context first
**Task**: Implement JWT authentication service
**"Too many files returned"**
- Be more specific (e.g., "TypeScript coding standards" not "coding")
**Context to load first**:
- .opencode/context/core/standards/code-quality.md
- .opencode/context/core/standards/security-patterns.md
- .opencode/context/core/standards/typescript.md
**"Which files do I load?"**
- Always: Critical → High → Medium (if needed)
**Instructions**: Follow functional patterns and security best practices from loaded context.
```
## Remember
- Context FIRST, code SECOND—never skip discovery
- Critical priority files are MANDATORY, not optional
- Training data is outdated—context is current
- Pass context forward when delegating to subagents
- Only use file paths returned by context-scout
## Related
- task-breakdown
- code-execution
- external-scout
---
## Integration with OAC Workflow
**Task**: Discover context files for **$ARGUMENTS**
This skill is part of the **6-stage OAC workflow**:
### Stage 1: Analyze & Discover (YOU ARE HERE)
- **Action**: Invoke `/context-discovery` to find relevant context
- **Output**: Ranked list of context files
### Stage 2: Plan & Approve
- **Action**: Load discovered context files
- **Action**: Create implementation plan
- **Action**: REQUEST APPROVAL before proceeding
### Stage 3: LoadContext
- **Action**: Read all Critical and High priority files
- **Action**: Understand standards, patterns, workflows
### Stage 4: Execute
- **Simple tasks**: Implement directly
- **Complex tasks**: Invoke `/task-breakdown` to create subtasks
### Stage 5: Validate
- **Action**: Run tests, verify implementation
- **Action**: STOP on failure
### Stage 6: Complete
- **Action**: Update docs, summarize changes
---
## Common Scenarios
### Scenario 1: Starting a New Feature
**You**: "I need to implement user authentication"
**Action**:
```
/context-discovery user authentication
```
**Result**: Context-scout finds security patterns, coding standards, auth workflows
**Next Steps**:
1. Load Critical priority files
2. Create implementation plan
3. Request approval
4. Implement following loaded standards
---
### Scenario 2: Unclear Project Patterns
**You**: "I'm not sure how to structure this React component"
**Action**:
```
/context-discovery React component patterns
```
**Result**: Context-scout finds UI patterns, React standards, component structure guides
**Next Steps**:
1. Load recommended files
2. Apply patterns to component design
3. Implement following standards
---
### Scenario 3: Before Task Breakdown
**You**: "I need to break down a complex feature"
**Action**:
```
/context-discovery task breakdown workflow
```
**Result**: Context-scout finds task delegation guides, subtask schemas, workflow patterns
**Next Steps**:
1. Load workflow guides
2. Invoke `/task-breakdown` with context
3. Create subtasks following schema
---
## What NOT to Do
- ❌ **Don't skip context discovery** — Always discover context before implementing
- ❌ **Don't ignore Critical priority files** — These are mandatory, not optional
- ❌ **Don't assume you know the standards** — Training data is outdated, context is current
- ❌ **Don't implement before loading context** — Context first, code second
- ❌ **Don't pass unverified file paths** — Only use paths returned by context-scout
---
## Troubleshooting
### "No context files found"
**Cause**: Context hasn't been downloaded yet
**Solution**: Run `/oac:setup` to download context from GitHub
### "Context-scout returned too many files"
**Cause**: Request was too broad
**Solution**: Be more specific in your request (e.g., "TypeScript coding standards" instead of "coding")
### "Not sure which files to load"
**Cause**: Unclear prioritization
**Solution**: Always start with Critical priority files, then High, then Medium if needed
---
## Principles
- **Context first, code second** — Always discover context before implementing
- **Follow navigation** — Context-scout uses navigation.md files to find relevant context
- **Prioritize wisely** — Critical files are mandatory, High are recommended, Medium are optional
- **Pass context forward** — When delegating to subagents, include discovered context files
- **Verify paths** — Only use file paths returned by context-scout (they're verified to exist)
---
## Task
Discover context files for: **$ARGUMENTS**
Follow the navigation-driven discovery process and return ranked recommendations.
Follow navigation-driven discovery and return ranked recommendations.

View file

@ -1,922 +0,0 @@
---
name: context-manager
description: Manage context files, discover context roots, validate structure, and organize project context. Use when adding context from GitHub/worktrees or managing context organization.
context: fork
agent: context-manager
---
# Context Manager Skill
> **Subagent**: context-manager
> **Purpose**: Manage context files, discover context roots, validate structure, and organize project-specific context for optimal discoverability.
---
## Task
Manage context for: **$ARGUMENTS**
**Operations Available**:
- **discover-root** - Find where context files are stored
- **add-context** - Add context from GitHub, worktrees, local files, or URLs
- **validate** - Validate existing context files
- **update-navigation** - Rebuild navigation files
- **organize** - Reorganize context by category
**Instructions**: Execute the requested context management operation following the guidelines below.
---
## When to Use This Skill
Invoke `/context-manager` when you need to:
- **Set up a new project** with OAC context files
- **Configure context sources** and download preferences
- **Integrate external task systems** (SpecKit, Linear, Jira, custom)
- **Manage personal context** files and templates
- **Troubleshoot context** loading or configuration issues
- **Update or refresh** downloaded context files
- **Configure cleanup** and maintenance settings
**Rule of thumb**: If you're setting up a project or configuring how context works, use this skill.
---
## Context Sources
Context files can come from multiple sources, loaded in priority order:
### 1. Project-Specific Context (Highest Priority)
**Location**: `.opencode/context/` (in your project root)
**Purpose**: Project-specific overrides, custom standards, team conventions
**Use when**:
- Your project has unique coding standards
- You need to override default patterns
- Team-specific workflows or conventions
- Project-specific security requirements
**Example**:
```bash
# Create project-specific override
mkdir -p .opencode/context/core/standards
vim .opencode/context/core/standards/code-quality.md
```
**Priority**: Files here override all other sources
---
### 2. OAC Repository Context (Default)
**Location**: `.opencode/context/` (downloaded from GitHub)
**Purpose**: Standard OAC patterns, workflows, coding standards
**Download via**: `/oac:setup`
**Categories**:
- `core` - Essential standards and workflows
- `openagents-repo` - OAC-specific guides and patterns
- `plugins` - Plugin development guides
- `skills` - Skill creation and usage
**Example**:
```bash
# Download core context only
/oac:setup --core
# Download all context
/oac:setup --all
# Download specific category
/oac:setup --category=standards
```
---
### 3. Personal Context (Global)
**Location**: `~/.opencode/context/` (your home directory)
**Purpose**: Personal templates, preferences, reusable patterns
**Use when**:
- You have personal coding preferences
- Reusable templates across projects
- Personal workflow patterns
- Custom snippets and examples
**Example**:
```bash
# Create personal context
mkdir -p ~/.opencode/context/personal/templates
vim ~/.opencode/context/personal/templates/react-component.md
```
**Priority**: Loaded if not found in project-specific context
---
### 4. External Task Systems
**Location**: Configured via `.oac` file
**Purpose**: Integration with external task management systems
**Supported systems**:
- **SpecKit** - Specification-driven task management
- **Linear** - Issue tracking and project management
- **Jira** - Enterprise project management
- **Custom JSON** - Your own task.json format
**Example**:
```json
{
"tasks": {
"source": "speckit",
"path": "~/projects/specs",
"sync": true
}
}
```
---
## Configuration (.oac file)
The `.oac` configuration file controls OAC behavior. It can be placed:
- **Project-level**: `.oac` (in project root) - project-specific settings
- **Global**: `~/.oac` - personal defaults across all projects
**Priority**: Project-level `.oac` overrides global `~/.oac`
### Configuration Schema
```json
{
"$schema": "https://openagents.dev/schemas/oac-v1.json",
"version": "1.0.0",
"project": {
"name": "my-project",
"type": "web-app",
"version": "1.0.0"
},
"context": {
"root": ".opencode/context",
"auto_download": false,
"categories": ["core", "openagents-repo"],
"update_check": true,
"cache_days": 7,
"locations": {
"tasks": "tasks/subtasks",
"docs": "docs"
},
"update": {
"check_on_start": true,
"auto_update": false,
"interval": "1h",
"strategy": "notify"
}
},
"cleanup": {
"auto_prompt": true,
"session_days": 7,
"task_days": 30,
"external_days": 7
},
"workflow": {
"auto_approve": false,
"verbose": false
},
"external_scout": {
"enabled": true,
"cache_enabled": true,
"sources": ["context7"]
},
"tasks": {
"source": "local",
"path": ".tmp/tasks",
"sync": false
}
}
```
### Configuration Options
#### Context Settings
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `context.root` | string | `.opencode/context` | Root directory for context files |
| `context.auto_download` | boolean | `false` | Auto-download context on first use |
| `context.categories` | array | `["core", "openagents-repo"]` | Default categories to download |
| `context.update_check` | boolean | `true` | Check for context updates |
| `context.cache_days` | number | `7` | Days to cache external context |
#### Cleanup Settings
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `cleanup.auto_prompt` | boolean | `true` | Prompt for cleanup on session start |
| `cleanup.session_days` | number | `7` | Days before suggesting session cleanup |
| `cleanup.task_days` | number | `30` | Days before suggesting task cleanup |
| `cleanup.external_days` | number | `7` | Days before suggesting external context cleanup |
#### Workflow Settings
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `workflow.auto_approve` | boolean | `false` | Skip approval gates (DANGEROUS) |
| `workflow.verbose` | boolean | `false` | Show detailed workflow steps |
#### External Scout Settings
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `external_scout.enabled` | boolean | `true` | Enable external documentation fetching |
| `external_scout.cache_enabled` | boolean | `true` | Cache fetched documentation |
| `external_scout.sources` | array | `["context7"]` | Documentation sources to use |
#### Task System Settings
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `tasks.source` | string | `"local"` | Task source: `local`, `speckit`, `linear`, `jira`, `custom` |
| `tasks.path` | string | `.tmp/tasks` | Path to task files |
| `tasks.sync` | boolean | `false` | Sync with external system |
---
## Managing Downloaded Context
### Download Context
Use `/oac:setup` to download context files from the OAC repository:
```bash
# Interactive mode - prompts for options
/oac:setup
# Download core context only (~50 files)
/oac:setup --core
# Download all context (~200 files)
/oac:setup --all
# Download specific category
/oac:setup --category=standards
/oac:setup --category=workflows
/oac:setup --category=openagents-repo
```
**What gets downloaded**:
- Context files to `.opencode/context/`
- Manifest file to `plugins/claude-code/.context-manifest.json`
- Validation and verification
---
### Verify Context
Check what context is installed and available:
```bash
# Check OAC installation status
/oac:status
# Verify specific context files exist
ls .opencode/context/core/standards/
ls .opencode/context/core/workflows/
```
**Status output includes**:
- Context files installed
- Configuration loaded
- Task system status
- External scout cache status
---
### Update Context
Re-run setup to update to the latest version:
```bash
# Update core context
/oac:setup --core
# Force re-download (overwrite existing)
/oac:setup --all --force
```
**Note**: Context files are cached locally. Updates only download changed files.
---
### Custom Context
Add your own context files to project or personal directories:
**Project-specific** (overrides defaults):
```bash
mkdir -p .opencode/context/custom/patterns
vim .opencode/context/custom/patterns/my-pattern.md
```
**Personal** (reusable across projects):
```bash
mkdir -p ~/.opencode/context/personal/templates
vim ~/.opencode/context/personal/templates/my-template.md
```
**Context file format**:
```markdown
<!-- Context: category/subcategory | Priority: critical | Version: 1.0 | Updated: 2026-02-16 -->
# Context Title
**Purpose**: Brief description
---
## Content
Your context content here...
```
---
## Personal Projects & Task Systems
### Local Task Management (Default)
**Configuration**:
```json
{
"tasks": {
"source": "local",
"path": ".tmp/tasks",
"sync": false
}
}
```
**Usage**:
- Tasks stored in `.tmp/tasks/{feature}/`
- JSON-based task and subtask files
- No external dependencies
- Managed via `/task-breakdown` skill
**Best for**: Solo developers, simple projects, no external tools
---
### SpecKit Integration
**What is SpecKit**: Specification-driven task management system
**Configuration**:
```json
{
"tasks": {
"source": "speckit",
"path": "~/projects/specs",
"sync": true,
"config": {
"api_key": "${SPECKIT_API_KEY}",
"project_id": "my-project"
}
}
}
```
**Setup**:
1. Install SpecKit CLI: `npm install -g speckit`
2. Configure API key: `export SPECKIT_API_KEY=your-key`
3. Update `.oac` with SpecKit settings
4. Run `/oac:status` to verify connection
**Usage**:
- Tasks synced from SpecKit specs
- Bidirectional sync (local ↔ SpecKit)
- Automatic spec updates on task completion
**Best for**: Specification-driven development, documentation-first workflows
---
### Linear Integration
**What is Linear**: Modern issue tracking and project management
**Configuration**:
```json
{
"tasks": {
"source": "linear",
"sync": true,
"config": {
"api_key": "${LINEAR_API_KEY}",
"team_id": "my-team",
"project_id": "my-project",
"sync_interval": "5m"
}
}
}
```
**Setup**:
1. Get Linear API key from https://linear.app/settings/api
2. Configure API key: `export LINEAR_API_KEY=your-key`
3. Update `.oac` with Linear settings
4. Run `/oac:status` to verify connection
**Usage**:
- Tasks synced from Linear issues
- Status updates pushed to Linear
- Comments and progress tracked
- Automatic issue linking
**Best for**: Team projects, agile workflows, issue tracking
---
### Jira Integration
**What is Jira**: Enterprise project management and issue tracking
**Configuration**:
```json
{
"tasks": {
"source": "jira",
"sync": true,
"config": {
"url": "https://your-domain.atlassian.net",
"email": "your-email@example.com",
"api_token": "${JIRA_API_TOKEN}",
"project_key": "PROJ",
"sync_interval": "10m"
}
}
}
```
**Setup**:
1. Generate Jira API token from https://id.atlassian.com/manage-profile/security/api-tokens
2. Configure credentials:
```bash
export JIRA_API_TOKEN=your-token
```
3. Update `.oac` with Jira settings
4. Run `/oac:status` to verify connection
**Usage**:
- Tasks synced from Jira issues
- Status updates pushed to Jira
- Work logs and time tracking
- Custom field mapping
**Best for**: Enterprise teams, complex workflows, compliance requirements
---
### Custom Task System
**What is Custom**: Your own task.json format or API
**Configuration**:
```json
{
"tasks": {
"source": "custom",
"path": "/path/to/tasks",
"sync": true,
"config": {
"adapter": "./scripts/task-adapter.js",
"sync_command": "npm run sync-tasks",
"format": "json"
}
}
}
```
**Setup**:
1. Create task adapter script:
```javascript
// scripts/task-adapter.js
module.exports = {
async fetchTasks() {
// Fetch from your system
},
async updateTask(taskId, updates) {
// Update your system
}
};
```
2. Update `.oac` with custom settings
3. Test adapter: `node scripts/task-adapter.js`
**Usage**:
- Define your own task format
- Custom sync logic
- Integration with any system
- Full control over behavior
**Best for**: Unique workflows, legacy systems, custom requirements
---
## Integration Examples
### Example 1: Solo Developer Setup
**Scenario**: Individual developer, personal projects, local task management
**Configuration** (`.oac`):
```json
{
"project": {
"name": "my-personal-project",
"type": "web-app"
},
"context": {
"auto_download": true,
"categories": ["core"]
},
"tasks": {
"source": "local",
"path": ".tmp/tasks"
},
"cleanup": {
"auto_prompt": true,
"session_days": 3
}
}
```
**Setup steps**:
1. Create `.oac` in project root
2. Run `/oac:setup --core`
3. Start coding with `/using-oac`
**Benefits**:
- Minimal setup
- No external dependencies
- Fast and simple
- Full control
---
### Example 2: Team Project Setup
**Scenario**: Team using Linear for issue tracking, shared context
**Configuration** (`.oac`):
```json
{
"project": {
"name": "team-project",
"type": "web-app",
"version": "1.0.0"
},
"context": {
"auto_download": true,
"categories": ["core", "openagents-repo"],
"update_check": true
},
"tasks": {
"source": "linear",
"sync": true,
"config": {
"api_key": "${LINEAR_API_KEY}",
"team_id": "engineering",
"project_id": "web-app"
}
},
"workflow": {
"verbose": true
}
}
```
**Setup steps**:
1. Team lead creates `.oac` in project root
2. Each developer runs `/oac:setup --all`
3. Configure Linear API key: `export LINEAR_API_KEY=your-key`
4. Verify: `/oac:status`
5. Start workflow: `/using-oac`
**Benefits**:
- Shared context and standards
- Automatic issue sync
- Team visibility
- Consistent workflows
---
### Example 3: Multi-Project Setup
**Scenario**: Developer working on multiple projects with shared personal context
**Global configuration** (`~/.oac`):
```json
{
"context": {
"auto_download": true,
"categories": ["core"],
"cache_days": 14
},
"cleanup": {
"auto_prompt": true,
"session_days": 7
},
"external_scout": {
"enabled": true,
"cache_enabled": true
}
}
```
**Personal context** (`~/.opencode/context/personal/`):
```
~/.opencode/context/personal/
├── templates/
│ ├── react-component.md
│ ├── api-endpoint.md
│ └── test-suite.md
├── patterns/
│ ├── error-handling.md
│ └── logging.md
└── workflows/
└── my-workflow.md
```
**Project-specific** (`.oac` in each project):
```json
{
"project": {
"name": "project-a",
"type": "web-app"
},
"tasks": {
"source": "local"
}
}
```
**Benefits**:
- Reusable personal templates
- Project-specific overrides
- Consistent personal preferences
- Efficient multi-project workflow
---
### Example 4: Custom Task System Integration
**Scenario**: Company with custom task management API
**Configuration** (`.oac`):
```json
{
"project": {
"name": "enterprise-app",
"type": "web-app"
},
"context": {
"categories": ["core", "openagents-repo"]
},
"tasks": {
"source": "custom",
"sync": true,
"config": {
"adapter": "./scripts/company-task-adapter.js",
"api_url": "https://tasks.company.com/api",
"api_key": "${COMPANY_TASK_API_KEY}",
"sync_interval": "5m"
}
}
}
```
**Custom adapter** (`scripts/company-task-adapter.js`):
```javascript
const axios = require('axios');
module.exports = {
async fetchTasks() {
const response = await axios.get(
`${process.env.COMPANY_TASK_API_URL}/tasks`,
{
headers: {
'Authorization': `Bearer ${process.env.COMPANY_TASK_API_KEY}`
}
}
);
// Transform to OAC task format
return response.data.tasks.map(task => ({
id: task.id,
title: task.name,
description: task.description,
status: task.state,
assignee: task.assigned_to,
priority: task.priority_level
}));
},
async updateTask(taskId, updates) {
await axios.patch(
`${process.env.COMPANY_TASK_API_URL}/tasks/${taskId}`,
updates,
{
headers: {
'Authorization': `Bearer ${process.env.COMPANY_TASK_API_KEY}`
}
}
);
}
};
```
**Benefits**:
- Integration with existing systems
- Custom business logic
- Full control over sync
- Company-specific workflows
---
## Troubleshooting
### Context files not found
**Symptom**: `/context-discovery` returns "No context files found"
**Cause**: Context hasn't been downloaded yet
**Solution**:
```bash
# Download core context
/oac:setup --core
# Verify installation
/oac:status
# Check files exist
ls .opencode/context/core/standards/
```
---
### Configuration not loading
**Symptom**: Settings in `.oac` not being applied
**Cause**: Invalid JSON or wrong location
**Solution**:
```bash
# Validate JSON syntax
cat .oac | jq .
# Check file location (should be in project root)
ls -la .oac
# Verify schema
cat .oac | jq '."$schema"'
```
---
### Task system not syncing
**Symptom**: External tasks not appearing or updating
**Cause**: API credentials missing or invalid
**Solution**:
```bash
# Check environment variables
echo $LINEAR_API_KEY
echo $JIRA_API_TOKEN
# Verify configuration
cat .oac | jq '.tasks'
# Test connection
/oac:status
# Check logs
tail -f .tmp/logs/task-sync.log
```
---
### Context priority conflicts
**Symptom**: Wrong context file being loaded
**Cause**: Multiple sources with same file path
**Solution**:
```bash
# Check priority order:
# 1. .opencode/context/ (project-specific)
# 2. ~/.opencode/context/ (personal)
# 3. Downloaded context
# Find which file is being used
find . -name "code-quality.md" -o -path "~/.opencode/context/**/code-quality.md"
# Remove unwanted override
rm .opencode/context/core/standards/code-quality.md
```
---
### Update check failing
**Symptom**: "Failed to check for context updates"
**Cause**: Network issues or GitHub rate limiting
**Solution**:
```bash
# Disable update check temporarily
cat > .oac <<EOF
{
"context": {
"update_check": false
}
}
EOF
# Or update manually
/oac:setup --core --force
```
---
## Best Practices
### ✅ Do
- **Start with core context** - Run `/oac:setup --core` first
- **Use project-specific .oac** - Keep project settings in version control
- **Keep personal context separate** - Use `~/.opencode/context/` for personal templates
- **Version your .oac file** - Commit to git for team consistency
- **Document custom integrations** - Add README for custom task adapters
- **Test configuration changes** - Run `/oac:status` after updates
- **Use environment variables** - Never commit API keys to `.oac`
### ❌ Don't
- **Don't commit API keys** - Use environment variables instead
- **Don't skip context download** - Always run `/oac:setup` first
- **Don't modify downloaded context** - Use project-specific overrides instead
- **Don't enable auto_approve** - It bypasses important safety checks
- **Don't ignore update checks** - Keep context files current
- **Don't mix task systems** - Choose one task source per project
---
## Related Skills
- `/using-oac` - Main OAC workflow (uses context from this skill)
- `/context-discovery` - Find relevant context files
- `/external-scout` - Fetch external library documentation
- `/task-breakdown` - Create task breakdowns (uses task system config)
---
## Related Commands
- `/oac:setup` - Download context files
- `/oac:status` - Check installation status
- `/oac:help` - View available commands
- `/oac:cleanup` - Clean up old files
---
## Success Criteria
✅ Context files downloaded and verified
✅ Configuration file created and valid
✅ Task system integrated (if applicable)
✅ Personal context organized
✅ Project-specific overrides working
✅ Team members can replicate setup
✅ `/oac:status` shows all green

View file

@ -1,87 +1,38 @@
---
name: external-scout
description: Fetch external library and framework documentation. Use when you need current API patterns for npm packages, Python libraries, or other external dependencies. Invokes the external-scout subagent to fetch and cache documentation from Context7 and other sources.
description: Use when the task involves an external library or package and current API docs are needed before writing code.
context: fork
agent: external-scout
---
# External Scout Skill
# External Scout
> **Purpose**: Fetch current documentation for external libraries and frameworks. This skill invokes the `external-scout` subagent to retrieve and cache up-to-date API patterns from Context7 and other documentation sources.
## Overview
Fetch and cache current documentation for external libraries and frameworks. Training data is outdated—this skill ensures you use current, correct API patterns.
---
**Announce at start:** "I'm using the external-scout skill to fetch current docs for [package]."
## When to Use This Skill
## The Process
Invoke `/external-scout` when you need to:
### Step 1: Invoke External-Scout
- **Verify current API patterns** for external packages before implementing
- **Check for breaking changes** in library versions
- **Get up-to-date examples** for framework features
- **Understand correct usage** of third-party libraries
- **Avoid outdated patterns** from training data
Request documentation with package and topic:
**Rule of thumb**: If you're using ANY external package (npm, pip, etc.), fetch current docs FIRST.
---
## Why This Matters
**Training data is outdated.** Libraries change their APIs, deprecate features, and introduce new patterns. Using ExternalScout ensures you're implementing with current, correct patterns.
**Examples of what can go wrong without current docs**:
- Using deprecated API methods that no longer exist
- Missing new features that simplify implementation
- Following old patterns that have been replaced
- Implementing workarounds for bugs that are already fixed
---
## How It Works
This skill runs in the `external-scout` subagent (isolated context) and:
1. **Checks cache** — Is this package/topic already cached and fresh (< 7 days)?
2. **Fetches if needed** — Calls Context7 API or other sources for current docs
3. **Caches results** — Saves to `.tmp/external-context/{package}/{topic}.md`
4. **Returns paths** — You load the cached documentation files
---
## Usage
### Basic Usage
```
```bash
/external-scout <package> <topic>
```
**Examples**:
```
**Examples:**
```bash
/external-scout drizzle schemas
/external-scout react hooks
/external-scout express middleware
/external-scout zod validation
/external-scout prisma queries
```
### With Context
### Step 2: Check Response
Provide additional context to focus the documentation search:
```
/external-scout drizzle schemas - Building user authentication with PostgreSQL
/external-scout react hooks - Building a form with validation
/external-scout express middleware - Adding JWT authentication
```
---
## What You'll Get Back
The external-scout subagent returns JSON with cached file paths:
### Success Response
External-scout returns JSON with cached file paths:
```json
{
@ -96,158 +47,55 @@ The external-scout subagent returns JSON with cached file paths:
"cachedAt": "2026-02-16T10:30:00Z",
"source": "context7",
"age": "fresh"
},
"message": "Documentation cached successfully. Load files to access current API patterns."
}
}
```
### Cache Hit Response
**Cache status:**
- `"fresh"` — < 7 days old (use cached)
- `"stale"` — > 7 days old (re-fetches automatically)
```json
{
"status": "cache_hit",
"package": "react",
"topic": "hooks",
"cached": true,
"files": [
".tmp/external-context/react/hooks.md"
],
"metadata": {
"cachedAt": "2026-02-14T15:00:00Z",
"source": "context7",
"age": "2 days"
},
"message": "Using cached documentation (2 days old). Load files to access API patterns."
}
```
### Step 3: Load Cached Documentation
---
Read the returned file:
## What to Do with Results
### Step 1: Load Cached Documentation
Read the files returned by ExternalScout:
```
```bash
Read: .tmp/external-context/drizzle/schemas.md
```
This file contains current API patterns, examples, and best practices.
### Step 2: Apply Patterns to Implementation
### Step 4: Apply to Implementation
Use the loaded documentation to:
- **Verify API signatures** — Ensure you're calling methods correctly
- **Follow current patterns** — Use recommended approaches from docs
- **Check for deprecations** — Avoid deprecated features
- **Use new features** — Take advantage of recent improvements
Use loaded documentation to:
- Verify API signatures are correct
- Follow current patterns (not training data)
- Check for deprecations
- Use new features introduced since training
### Step 3: Implement with Confidence
### Step 5: Implement with Confidence
Now that you have current docs, implement following the verified patterns.
Now that you have current docs, implement following verified patterns.
---
## Example: Using Drizzle ORM
## Integration with OAC Workflow
```markdown
1. Invoke: /external-scout drizzle schemas
This skill is part of the **6-stage OAC workflow**:
2. Response:
{
"status": "success",
"files": [".tmp/external-context/drizzle/schemas.md"]
}
### Stage 1: Analyze & Discover
- **Action**: Invoke `/context-discovery` for internal context
- **Action**: Invoke `/external-scout` for external library docs
3. Load: Read .tmp/external-context/drizzle/schemas.md
### Stage 2: Plan & Approve
- **Action**: Load discovered context files (internal + external)
- **Action**: Create implementation plan
- **Action**: REQUEST APPROVAL before proceeding
4. Review: Current API for defining tables and relations
### Stage 3: LoadContext
- **Action**: Read all internal context files
- **Action**: Read all external documentation files
- **Action**: Understand standards, patterns, and current APIs
### Stage 4: Execute
- **Action**: Implement using loaded context and current API patterns
- **Action**: Follow both internal standards and external library patterns
### Stage 5: Validate
- **Action**: Run tests, verify implementation
- **Action**: STOP on failure
### Stage 6: Complete
- **Action**: Update docs, summarize changes
---
## Common Scenarios
### Scenario 1: Using Drizzle ORM
**You**: "I need to implement database schemas with Drizzle"
**Action**:
```
/external-scout drizzle schemas
5. Implement: Use current patterns from loaded docs
```
**Result**: ExternalScout fetches current Drizzle schema API patterns
**Next Steps**:
1. Load `.tmp/external-context/drizzle/schemas.md`
2. Review current API for defining tables and relations
3. Implement schemas following current patterns
4. Avoid outdated patterns from training data
---
### Scenario 2: React Hooks
**You**: "I'm building a form with React hooks"
**Action**:
```
/external-scout react hooks - Building a form with validation
```
**Result**: ExternalScout fetches current React hooks documentation
**Next Steps**:
1. Load `.tmp/external-context/react/hooks.md`
2. Review current patterns for useState, useEffect, custom hooks
3. Implement form following current best practices
4. Use any new hooks introduced since training data
---
### Scenario 3: Express Middleware
**You**: "I need to add JWT authentication middleware to Express"
**Action**:
```
/external-scout express middleware - JWT authentication
```
**Result**: ExternalScout fetches current Express middleware patterns
**Next Steps**:
1. Load `.tmp/external-context/express/middleware.md`
2. Review current middleware API and patterns
3. Implement JWT middleware following current conventions
4. Avoid deprecated middleware patterns
---
## Cache Management
### Cache Freshness
- **Fresh**: < 7 days old (use cached version)
- **Stale**: > 7 days old (re-fetch from source)
- **Missing**: No cache exists (fetch from source)
### Cache Location
## Cache Location
```
.tmp/external-context/
@ -263,84 +111,38 @@ This skill is part of the **6-stage OAC workflow**:
└── middleware.md
```
### Cache Cleanup
Cache files auto-refresh after 7 days.
Cache files are managed by the cleanup script:
- External context older than 7 days is flagged for cleanup
- Run cleanup script to review and remove old cache
## Error Handling
**"External documentation fetch failed":**
- Check internet connection
- Try again in a few minutes
- Fallback: Visit official docs manually
**"Cache is stale, re-fetching":**
- Normal behavior—external-scout auto-fetches fresh docs
**"Package not found in Context7":**
- Visit official package documentation
- Check npm/PyPI for package README
- Review GitHub repository for API docs
## Remember
- Training data is OUTDATED—always fetch current patterns
- Cache lasts 7 days before auto-refresh
- Load external docs BEFORE writing code
- Trust current docs over training data assumptions
- External docs prevent using deprecated APIs
## Related
- context-discovery
- code-execution
---
## Configuration
**Task**: Fetch external documentation for: **$ARGUMENTS**
ExternalScout behavior can be configured via `.oac` config file:
```yaml
# External scout settings
external_scout.enabled: true
external_scout.cache_enabled: true
external_scout.sources: context7
```
**Settings**:
- `external_scout.enabled` - Enable/disable external documentation fetching
- `external_scout.cache_enabled` - Enable/disable caching (always fetch if false)
- `external_scout.sources` - Documentation sources to use (context7, web, etc.)
---
## What NOT to Do
- ❌ **Don't skip external docs** — Always fetch current patterns for external packages
- ❌ **Don't trust training data** — APIs change, training data is outdated
- ❌ **Don't use stale cache** — If cache is > 7 days old, it will be re-fetched
- ❌ **Don't implement before loading docs** — External docs first, code second
- ❌ **Don't assume API patterns** — Verify with current documentation
---
## Troubleshooting
### "External documentation fetch failed"
**Cause**: Context7 API unavailable or network issue
**Solution**:
1. Check internet connection
2. Try again in a few minutes
3. Use fallback: Visit official documentation manually
4. Cache will be created on next successful fetch
### "Cache is stale, re-fetching"
**Cause**: Cached documentation is > 7 days old
**Solution**: This is normal behavior. ExternalScout will automatically fetch fresh docs.
### "Package not found in Context7"
**Cause**: Package may not be indexed in Context7 yet
**Solution**:
1. Visit official package documentation
2. Check npm/PyPI for package README
3. Review GitHub repository for API docs
4. Manually create cache file if needed
---
## Principles
- **Current docs matter** — Training data is outdated, always fetch current patterns
- **Cache for performance** — Fetch once, use many times (within 7 days)
- **Verify before implement** — Load external docs before writing code
- **Trust the source** — Official docs > training data assumptions
- **Fresh is better** — Re-fetch stale cache to get latest patterns
---
## Task
Fetch external documentation for: **$ARGUMENTS**
Check cache first, fetch if needed, and return file paths for loading.
Check cache first (< 7 days fresh), fetch from Context7 if needed, return file paths for loading.

View file

@ -0,0 +1,122 @@
---
name: install-context
description: Install context files from registry. Use when user mentions "install context", "download context", or context is missing.
disable-model-invocation: true
---
# Install Context
## Overview
Guide user through installing context files from OpenAgents Control registry with profile selection.
**Announce at start:** "I'm using the install-context skill to set up your context files."
---
## The Process
### Step 1: Check Current Installation
```bash
cat ${CLAUDE_PLUGIN_ROOT}/.context-manifest.json 2>/dev/null
```
**If exists:** Show current profile and ask if they want to change/reinstall.
**If missing:** Proceed to Step 2.
---
### Step 2: Ask Which Profile
Present options, ask user to choose:
```
Available profiles:
essential - Core patterns only (~4 components, 30s)
standard - Typical use (~12 components, 2min) [RECOMMENDED]
extended - Advanced features (~30 components, 5min)
specialized - Domain-specific (~50 components, 10min)
all - Everything (~191 components, 20min)
Which profile? [standard]
```
Wait for response.
---
### Step 3: Run Installer
```bash
cd ${CLAUDE_PLUGIN_ROOT}/scripts
bun run install-context.ts --profile={selected_profile}
```
**If bun is not available, fallback to:** `node install-context.js --profile={selected_profile}`
**If user provided --force or --dry-run:** Pass those flags.
Show output to user.
---
### Step 4: Verify
```bash
cat ${CLAUDE_PLUGIN_ROOT}/.context-manifest.json
ls ${CLAUDE_PLUGIN_ROOT}/context/
```
Report: "✓ Installed {count} components. Context ready."
---
## CLI Options
If user provides options, skip interactive prompts:
```bash
/install-context --profile=essential
/install-context --force
/install-context --dry-run
/install-context --categories=core-standards,openagents-repo
```
---
## Error Handling
**Git not installed:**
```
✗ Git required. Install: brew install git
```
**Network failure:**
```
✗ Can't reach GitHub. Check connection and retry.
```
**Already installed (without --force):**
```
⚠ Already installed. Use --force to reinstall.
```
---
## Remember
- Keep it simple - just install and verify
- Don't over-explain profiles
- Show progress from installer
- Verify manifest exists
- Done
---
## Related
- `using-oac` - Uses installed context
- `context-discovery` - Discovers from installed context

View file

@ -1,142 +1,27 @@
---
name: parallel-execution
description: Execute multiple independent tasks in parallel using Claude Code's agent teams or multiple subagent invocations. Use when you have independent tasks with no dependencies, need to speed up multi-component features, or when task-manager marks tasks with parallel:true.
description: Use when multiple subtasks have no shared files or dependencies and can be executed simultaneously.
---
# Parallel Execution Skill
# Parallel Execution
Execute multiple independent tasks simultaneously to dramatically reduce implementation time for multi-component features.
## Overview
Execute multiple independent tasks simultaneously using multiple subagent invocations in a single message. Reduces implementation time by 50-80% for multi-component features.
## When to Use This Skill
**Announce at start:** "I'm using parallel-execution to run [N] independent tasks simultaneously."
Invoke parallel execution when:
## The Process
- **Multiple independent tasks** — Tasks with no shared files or dependencies
- **Task-manager marks parallel:true** — TaskManager identified parallelizable work
- **Multi-component features** — Frontend + backend + tests can run simultaneously
- **Time-sensitive delivery** — Need to reduce total execution time
- **Isolated work streams** — Different agents working on different areas
- **Batch operations** — Converting multiple files, running multiple tests
### Step 1: Identify Parallel Tasks
## When NOT to Use
Avoid parallel execution when:
- ❌ **Tasks modify the same files** — Will cause merge conflicts
- ❌ **Tasks have dependencies** — One task needs output from another
- ❌ **Shared state or resources** — Database migrations, global config changes
- ❌ **Sequential logic required** — Steps must happen in specific order
- ❌ **Single small task** — Overhead not worth it for simple operations
## How Parallel Execution Works
### Approach A: Multiple Subagent Invocations (Native)
**Claude Code natively supports parallel work via multiple tool calls in one message.**
When you make multiple independent `task()` calls in a single response, Claude Code executes them in parallel:
```markdown
I'll execute these three tasks in parallel:
task(subagent_type="CoderAgent", description="Implement auth service", prompt="...")
task(subagent_type="CoderAgent", description="Implement user service", prompt="...")
task(subagent_type="TestEngineer", description="Create integration tests", prompt="...")
```
**Key points**:
- All three tasks start simultaneously
- Each runs in isolated context
- Main agent waits for ALL to complete before proceeding
- Results are collected and can be integrated
### Approach B: Agent Teams (Experimental)
**Requires**: `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=true`
Agent teams allow multiple agents to collaborate on a shared workspace:
```markdown
I'll create an agent team for this feature:
team(
name="auth-implementation",
agents=[
{type: "CoderAgent", task: "Backend auth service"},
{type: "OpenFrontendSpecialist", task: "Login UI components"},
{type: "TestEngineer", task: "E2E auth tests"}
],
shared_context=".tmp/sessions/auth-context.md"
)
```
**Key points**:
- Agents share context file for coordination
- Can communicate via shared state
- More complex but enables tighter integration
- Experimental feature, may change
## Integration with Task-Manager
TaskManager automatically identifies parallel tasks and marks them with `parallel: true`:
### Task Structure Example
**task.json**:
```json
{
"id": "user-dashboard",
"subtask_count": 5,
"context_files": [".opencode/context/core/standards/code-quality.md"]
}
```
**subtask_01.json** (parallel):
```json
{
"id": "user-dashboard-01",
"seq": "01",
"title": "Create user profile API",
"parallel": true,
"depends_on": [],
"suggested_agent": "CoderAgent"
}
```
**subtask_02.json** (parallel):
```json
{
"id": "user-dashboard-02",
"seq": "02",
"title": "Design dashboard UI components",
"parallel": true,
"depends_on": [],
"suggested_agent": "OpenFrontendSpecialist"
}
```
**subtask_03.json** (sequential - depends on 01 and 02):
```json
{
"id": "user-dashboard-03",
"seq": "03",
"title": "Integrate API with UI",
"parallel": false,
"depends_on": ["01", "02"],
"suggested_agent": "CoderAgent"
}
```
### Identifying Parallel Batches
Use the task-management CLI to identify parallel tasks:
Check subtask JSON files for `parallel: true`:
```bash
# Show which tasks can run in parallel
bash .opencode/skills/task-management/router.sh parallel user-dashboard
bash .opencode/skills/task-management/router.sh parallel {feature}
```
**Output**:
Output shows which tasks can run together:
```
Batch 1 (Ready now):
- subtask_01.json (parallel: true)
@ -146,60 +31,58 @@ Batch 2 (After Batch 1):
- subtask_03.json (depends_on: ["01", "02"])
```
### Execution Workflow
### Step 2: Execute Parallel Batch
**Step 1: Analyze Task Structure**
```markdown
Read .tmp/tasks/{feature}/task.json
Read all subtask_NN.json files
Identify parallel batches using dependency graph
```
Make multiple task() calls in SINGLE message:
**Step 2: Execute Parallel Batch**
```markdown
For Batch 1 (subtasks 01 and 02 are parallel):
I'll execute Batch 1 tasks in parallel:
task(
subagent_type="CoderAgent",
description="Execute subtask 01",
prompt="Read .tmp/tasks/user-dashboard/subtask_01.json and implement..."
prompt="Read .tmp/tasks/feature/subtask_01.json and implement..."
)
task(
subagent_type="OpenFrontendSpecialist",
description="Execute subtask 02",
prompt="Read .tmp/tasks/user-dashboard/subtask_02.json and implement..."
)
Wait for both to complete...
```
**Step 3: Verify Batch Completion**
```bash
bash .opencode/skills/task-management/router.sh status user-dashboard
```
**Step 4: Execute Next Batch**
```markdown
Once Batch 1 is complete, proceed to Batch 2:
task(
subagent_type="CoderAgent",
description="Execute subtask 03",
prompt="Read .tmp/tasks/user-dashboard/subtask_03.json and integrate..."
description="Execute subtask 02",
prompt="Read .tmp/tasks/feature/subtask_02.json and implement..."
)
```
## Practical Examples
**CRITICAL**: Both task() calls in SAME message—not separate messages.
### Example 1: Converting Multiple Subagents in Parallel
### Step 3: Wait for All to Complete
**Scenario**: Convert 5 subagent files from old format to new format
All tasks in batch must complete before proceeding to next batch.
### Step 4: Verify Batch Completion
```bash
bash .opencode/skills/task-management/router.sh status {feature}
```
Check all tasks in batch marked `status: "completed"`.
### Step 5: Execute Next Batch
Once Batch 1 complete, proceed to Batch 2:
```markdown
I'll convert these subagents in parallel:
task(
subagent_type="CoderAgent",
description="Execute subtask 03",
prompt="Read .tmp/tasks/feature/subtask_03.json and integrate..."
)
```
task(subagent_type="CoderAgent", description="Convert auth-agent",
## Example: Converting Multiple Files
```markdown
I'll convert these 5 subagent files in parallel:
task(subagent_type="CoderAgent", description="Convert auth-agent",
prompt="Convert .opencode/agent/subagents/auth-agent.md to new format...")
task(subagent_type="CoderAgent", description="Convert user-agent",
@ -215,270 +98,71 @@ task(subagent_type="CoderAgent", description="Convert analytics-agent",
prompt="Convert .opencode/agent/subagents/analytics-agent.md to new format...")
```
**Time savings**: 5 tasks × 10 min each = 50 min sequential → ~10 min parallel (80% faster)
**Time savings**: 5 tasks × 10 min = 50 min sequential → ~10 min parallel (80% faster)
### Example 2: Running Tests in Parallel
## Avoiding Conflicts
**Scenario**: Run unit tests, integration tests, and E2E tests simultaneously
```markdown
I'll run all test suites in parallel:
task(subagent_type="TestEngineer", description="Run unit tests",
prompt="Execute unit test suite for src/auth/...")
task(subagent_type="TestEngineer", description="Run integration tests",
prompt="Execute integration test suite for src/api/...")
task(subagent_type="TestEngineer", description="Run E2E tests",
prompt="Execute E2E test suite for user flows...")
```
**Time savings**: 3 suites × 5 min each = 15 min sequential → ~5 min parallel (67% faster)
### Example 3: Implementing Independent Features
**Scenario**: Build authentication system with parallel work streams
```markdown
I'll implement these independent components in parallel:
task(subagent_type="CoderAgent", description="JWT service",
prompt="Create JWT token generation and validation service...")
task(subagent_type="CoderAgent", description="Password hashing",
prompt="Implement bcrypt password hashing utilities...")
task(subagent_type="CoderAgent", description="Session storage",
prompt="Create Redis-based session storage layer...")
task(subagent_type="OpenFrontendSpecialist", description="Login UI",
prompt="Design and implement login form components...")
```
**Time savings**: 4 components × 30 min each = 120 min sequential → ~30 min parallel (75% faster)
## Best Practices
### 1. Avoid File Conflicts
**✅ Good** (isolated files):
**✅ GOOD (isolated files):**
```markdown
task(CoderAgent, "Create src/auth/service.ts")
task(CoderAgent, "Create src/user/service.ts")
task(CoderAgent, "Create src/payment/service.ts")
```
**❌ Bad** (same file):
**❌ BAD (same file):**
```markdown
task(CoderAgent, "Add auth function to src/utils/helpers.ts")
task(CoderAgent, "Add validation function to src/utils/helpers.ts")
```
This causes merge conflicts—run sequentially instead.
### 2. Size Tasks Appropriately
## Pre-Load Shared Context
**✅ Good** (balanced tasks):
```markdown
task(CoderAgent, "Implement user CRUD API (30 min)")
task(CoderAgent, "Implement auth middleware (30 min)")
```
**❌ Bad** (unbalanced):
```markdown
task(CoderAgent, "Implement entire backend (2 hours)")
task(CoderAgent, "Add one import statement (1 min)")
```
### 3. Monitor Progress
After delegating parallel tasks, track completion:
```bash
# Check status periodically
bash .opencode/skills/task-management/router.sh status {feature}
# Look for:
# - subtask_01.json: status: "completed" ✓
# - subtask_02.json: status: "completed" ✓
# - subtask_03.json: status: "in_progress" ...
```
### 4. Handle Failures Gracefully
If one parallel task fails:
Load context ONCE before parallel execution:
```markdown
Batch 1 Results:
- Task 01: ✅ Completed
- Task 02: ❌ Failed (missing dependency)
- Task 03: ✅ Completed
Action: Fix Task 02 before proceeding to Batch 2
```
### 5. Coordinate Shared Context
When tasks need shared information:
**✅ Good** (pre-load context):
```markdown
# Load context BEFORE parallel execution
Read .opencode/context/core/standards/code-quality.md
Read .opencode/context/core/standards/security-patterns.md
# Load context BEFORE parallel tasks
Read: .opencode/context/core/standards/code-quality.md
Read: .opencode/context/core/standards/security-patterns.md
# Now all parallel tasks have same context
task(CoderAgent, "Implement auth service...")
task(CoderAgent, "Implement user service...")
```
**❌ Bad** (each task discovers context):
```markdown
# Each task will call ContextScout separately (slower)
task(CoderAgent, "Discover context and implement auth...")
task(CoderAgent, "Discover context and implement user...")
```
DO NOT let each task discover context separately (slower).
## Troubleshooting
## Error Handling
### Issue: Tasks completing out of order
**Task fails during parallel execution:**
- Fix failed task before proceeding to next batch
- Other tasks in batch can still be used
**Problem**: Task 02 finishes before Task 01, but Task 03 depends on both
**Tasks completing out of order:**
- Don't start next batch until ALL current batch complete
- Use dependency tracking in subtask JSON
**Solution**: Use dependency tracking in subtask JSON:
```json
{
"id": "feature-03",
"depends_on": ["01", "02"],
"parallel": false
}
```
**File conflicts:**
- Review task breakdown—ensure true isolation
- If tasks MUST touch same file, mark `parallel: false`
Don't start Task 03 until BOTH 01 and 02 are marked `status: "completed"`.
## Remember
### Issue: File conflicts during parallel execution
- Make multiple task() calls in SINGLE message for parallel execution
- Tasks must be truly independent (no shared files/state)
- Pre-load shared context ONCE before parallel tasks
- Wait for ALL tasks in batch to complete before next batch
- Time savings: 50-80% reduction for multi-component features
- Optimal batch size: 2-4 tasks (up to 8 if truly independent)
- DO NOT parallelize tasks that modify same file
- DO NOT parallelize tasks with dependencies
**Problem**: Two tasks tried to modify the same file
## Related
**Solution**:
1. Review task breakdown - ensure true isolation
2. If tasks MUST touch same file, mark `parallel: false`
3. Sequence dependent tasks properly
### Issue: One task blocked waiting for another
**Problem**: Task 01 needs output from Task 02, but both marked parallel
**Solution**: Fix dependency graph:
```json
{
"id": "feature-01",
"depends_on": ["02"], // Add dependency
"parallel": false // Mark sequential
}
```
### Issue: Parallel tasks not actually running in parallel
**Problem**: Tasks executing sequentially despite parallel flags
**Solution**: Ensure you're making multiple `task()` calls in SAME message:
**✅ Correct**:
```markdown
I'll execute these in parallel:
task(...)
task(...)
task(...)
```
**❌ Wrong** (sequential):
```markdown
I'll execute task 1:
task(...)
[Wait for response]
Now I'll execute task 2:
task(...)
```
## Performance Impact
### Time Savings by Parallelization
| Scenario | Sequential | Parallel | Savings |
|----------|-----------|----------|---------|
| 3 independent components (30 min each) | 90 min | 30 min | 67% |
| 5 file conversions (10 min each) | 50 min | 10 min | 80% |
| 4 test suites (15 min each) | 60 min | 15 min | 75% |
| Frontend + Backend + Tests | 120 min | 40 min | 67% |
### Optimal Batch Sizes
- **2-4 tasks**: Ideal for most scenarios
- **5-8 tasks**: Good if truly independent
- **9+ tasks**: Consider breaking into multiple batches
## Related Skills
- `/task-breakdown` — Creates task structure with parallel flags
- `/context-discovery` — Load shared context before parallel execution
- `/code-review` — Review all parallel outputs together
## Advanced: Agent Teams
For complex features requiring tight coordination, use agent teams (experimental):
```markdown
team(
name="e-commerce-checkout",
agents=[
{
type: "CoderAgent",
role: "backend",
tasks: ["Payment API", "Order processing", "Inventory check"]
},
{
type: "OpenFrontendSpecialist",
role: "frontend",
tasks: ["Checkout UI", "Payment form", "Order confirmation"]
},
{
type: "TestEngineer",
role: "qa",
tasks: ["Integration tests", "E2E checkout flow"]
}
],
shared_context: ".tmp/sessions/checkout-context.md",
coordination: "async" // Agents coordinate via shared context file
)
```
**Benefits**:
- Agents can update shared context as they progress
- Enables async coordination without blocking
- Better for complex features with evolving requirements
**Drawbacks**:
- Experimental feature
- More complex to debug
- Requires careful context management
- task-breakdown
- context-discovery
- code-execution
---
## Summary
Parallel execution is a powerful technique for reducing implementation time when:
1. Tasks are truly independent (no shared files/state)
2. TaskManager marks tasks with `parallel: true`
3. You make multiple `task()` calls in same message
**Key takeaways**:
- ✅ Use for independent components, file conversions, test suites
- ✅ Pre-load shared context before parallel execution
- ✅ Monitor completion with task-management CLI
- ❌ Avoid for tasks with dependencies or shared files
- ❌ Don't parallelize tasks that modify same file
**Time savings**: 50-80% reduction in execution time for multi-component features.
**Key Pattern**: Multiple independent task() calls in SAME message = parallel execution.

View file

@ -1,101 +1,31 @@
---
name: task-breakdown
description: Break down complex features into atomic, verifiable subtasks with dependency tracking. Use when implementing multi-step workflows, complex features requiring multiple files, or when the user requests task planning.
description: Use when a feature touches 4 or more files, involves multiple components, or has subtasks that could run in parallel.
context: fork
agent: task-manager
---
# Task Breakdown
Break down this feature into atomic, verifiable subtasks: $ARGUMENTS
## Overview
Break down complex features into atomic, verifiable subtasks with dependency tracking. Each subtask gets its own JSON file with clear acceptance criteria and deliverables.
## Your Task
**Announce at start:** "I'm using the task-breakdown skill to create an execution plan for [feature]."
Create a structured task breakdown following the JSON schema:
## The Process
1. **Analyze the feature**:
- Identify core objective and scope
- Determine technical risks and dependencies
- Find natural task boundaries
- Identify which tasks can run in parallel
### Step 1: Analyze Feature
2. **Create task plan**:
- Feature ID (kebab-case)
- Objective (max 200 chars)
- Context files (standards to follow)
- Reference files (source material to study)
- Exit criteria (completion requirements)
Identify these elements:
- Core objective and scope
- Technical risks and dependencies
- Natural task boundaries
- Tasks that can run in parallel
3. **Generate subtasks**:
- Sequential numbering (01, 02, 03...)
- Clear title for each
- Dependencies mapped via `depends_on`
- Parallel flags set for isolated tasks
- Suggested agent assigned
- Acceptance criteria (binary pass/fail)
- Deliverables (specific file paths or endpoints)
### Step 2: Create Task Plan
4. **Create JSON files**:
- `.tmp/tasks/{feature}/task.json` - Feature metadata
- `.tmp/tasks/{feature}/subtask_01.json` - First subtask
- `.tmp/tasks/{feature}/subtask_02.json` - Second subtask
- ... (one file per subtask)
Write `.tmp/tasks/{feature}/task.json`:
5. **Validate structure**:
- All JSON files are valid
- Dependency references exist
- Context files vs reference files are separated
- Acceptance criteria are binary
- Deliverables are specific
## Critical Rules
- **Atomic tasks**: Each subtask completable in 1-2 hours
- **Context separation**:
- `context_files` = standards/conventions ONLY
- `reference_files` = project source files ONLY
- Never mix them
- **Binary criteria**: Pass/fail only, no ambiguity
- **Parallel identification**: Mark isolated tasks as `parallel: true`
- **Agent assignment**: Suggest appropriate agent for each subtask
- "CoderAgent" - Implementation tasks
- "TestEngineer" - Test creation
- "CodeReviewer" - Review tasks
- "OpenFrontendSpecialist" - UI/design tasks
## When to Use This Skill
Use task-breakdown when:
- Feature requires multiple files or components
- Implementation has clear sequential steps
- Tasks have dependencies that need tracking
- Work can be parallelized across isolated areas
- User explicitly requests task planning
- Feature is complex enough to benefit from structured breakdown
## Output Format
Return a summary:
```
## Tasks Created
Location: .tmp/tasks/{feature}/
Files: task.json + {N} subtasks
Subtasks:
- 01: {title} (parallel: {true/false}, agent: {suggested_agent})
- 02: {title} (parallel: {true/false}, agent: {suggested_agent})
...
Next Steps:
- Execute subtasks in order
- Parallel tasks can run simultaneously
- Use task-cli.ts for status tracking
```
## Example Task Structure
**task.json**:
```json
{
"id": "jwt-auth",
@ -119,7 +49,17 @@ Next Steps:
}
```
**subtask_01.json**:
**Rules:**
- Feature ID: kebab-case
- Objective: max 200 chars
- `context_files`: standards/conventions ONLY
- `reference_files`: project source files ONLY
- Exit criteria: binary pass/fail
### Step 3: Generate Subtasks
Write `.tmp/tasks/{feature}/subtask_01.json`, `subtask_02.json`, etc:
```json
{
"id": "jwt-auth-01",
@ -144,11 +84,76 @@ Next Steps:
}
```
## Quality Standards
**Rules:**
- Sequential numbering: 01, 02, 03...
- Atomic tasks: completable in 1-2 hours
- Dependencies: map via `depends_on` array
- Parallel tasks: set `parallel: true` for isolated work
- Agent assignment: CoderAgent, TestEngineer, CodeReviewer, OpenFrontendSpecialist
- Acceptance criteria: binary pass/fail only
- Deliverables: specific file paths or endpoints
- Clear objectives: Single, measurable outcome per task
- Explicit deliverables: Specific files or endpoints
- Context references: Reference paths, don't embed content
- Summary length: Max 200 characters for completion_summary
- Dependency tracking: Explicit `depends_on` arrays
- Parallelization: Mark isolated tasks for concurrent execution
### Step 4: Validate Structure
Verify:
- ✅ All JSON files valid
- ✅ Dependency references exist
- ✅ Context files separate from reference files
- ✅ Acceptance criteria are binary
- ✅ Deliverables are specific
### Step 5: Return Summary
```
## Tasks Created
Location: .tmp/tasks/jwt-auth/
Files: task.json + 3 subtasks
Subtasks:
- 01: Create JWT service (parallel: true, agent: CoderAgent)
- 02: Create password hashing util (parallel: true, agent: CoderAgent)
- 03: Integrate middleware (parallel: false, agent: CoderAgent)
Next Steps:
- Execute subtasks in dependency order
- Tasks 01 and 02 can run in parallel
- Task 03 depends on completion of 01 and 02
```
## Red Flags
If you think any of these, STOP and re-read this skill:
- "I can just implement it directly, it's not that complex"
- "The breakdown will take longer than just doing it"
- "I already know what needs to be done"
- "There's only really one task here"
## Common Rationalizations
| Excuse | Reality |
|--------|---------|
| "It's only 3-4 files, I don't need a breakdown" | 3-4 files = multiple subtasks with dependencies. Skipping tracking means losing progress on failure. |
| "I'll track it in my head" | Subagents don't share memory. JSON files are the only reliable state. |
| "The tasks are obvious, no need to document them" | Obvious tasks still need acceptance criteria. "Done" without binary criteria is not done. |
| "Parallel execution isn't worth it for this" | Parallel tasks cut execution time in half. The JSON overhead is 2 minutes. The time saving is 20+. |
## Remember
- Each subtask completable in 1-2 hours (atomic)
- `context_files` = standards ONLY, `reference_files` = source code ONLY
- Acceptance criteria must be binary (pass/fail)
- Mark isolated tasks as `parallel: true`
- Assign appropriate agent for each subtask
- Deliverables must be specific file paths
## Related
- context-discovery
- code-execution
- parallel-execution
---
**Task**: Break down this feature into atomic subtasks: **$ARGUMENTS**

View file

@ -1,399 +1,182 @@
---
name: test-generation
description: Generate comprehensive tests following TDD principles. Use when writing tests for new features, implementing TDD workflows, or adding test coverage to existing code.
description: Use when the user asks for tests, mentions TDD, or when new code has been written and needs test coverage.
context: fork
agent: test-engineer
---
# Test Generation
Generate comprehensive tests following TDD principles and project testing standards.
## Overview
Generate comprehensive tests following TDD principles and project testing standards. Runs in isolated test-engineer context with pre-loaded testing conventions.
## When to Use This Skill
**Announce at start:** "I'm using the test-generation skill to create tests for [feature/component]."
Invoke this skill when:
- **After implementation**: Writing tests for newly implemented features
- **TDD workflow**: Writing tests before implementation (test-first development)
- **Coverage gaps**: Adding tests to existing code that lacks coverage
- **Regression testing**: Adding tests to prevent bugs from reoccurring
- **Refactoring**: Ensuring behavior is preserved during code changes
## The Process
## How It Works
### Step 1: Specify Test Requirements
This skill runs in the **test-engineer** subagent with an isolated context. The main agent must:
1. **Pre-load testing standards** before invoking this skill
2. **Specify test requirements** clearly
3. **Review the test plan** before implementation
4. **Receive test results** and integrate them into the workflow
## Usage Pattern
### Step 1: Load Testing Context (Main Agent)
Before invoking this skill, load project testing standards:
```markdown
Read these files to understand testing requirements:
- .opencode/context/core/standards/tests.md
- .opencode/context/core/standards/test-coverage.md
- [project-specific test conventions]
```
### Step 2: Invoke Test Generation
Use this skill with clear requirements:
Provide clear requirements to test-engineer:
```markdown
/test-generation
Generate tests for [feature/component]:
Feature: JWT token validation middleware
**Feature**: [Brief description]
**Acceptance Criteria**:
- [Criterion 1]
- [Criterion 2]
- [Criterion 3]
**Behaviors to Test**:
1. [Behavior 1] - [expected outcome]
2. [Behavior 2] - [expected outcome]
3. [Error handling for X]
**Coverage Requirements**:
- Line coverage: [X]%
- Branch coverage: [X]%
- All critical paths tested
**Testing Standards** (pre-loaded):
- Test framework: [vitest/jest/pytest/etc.]
- Assertion library: [expect/chai/etc.]
- Mock library: [vi/jest.mock/etc.]
- File naming: [*.test.ts / *.spec.ts / test_*.py]
- Test structure: [AAA pattern required]
```
### Step 3: Review Test Plan
The test-engineer will propose a test plan:
```markdown
## Test Plan for [Feature]
### Behaviors to Test
1. [Behavior 1]
- ✅ Positive: [success case]
- ❌ Negative: [failure/edge case]
2. [Behavior 2]
- ✅ Positive: [success case]
- ❌ Negative: [failure/edge case]
### Mocking Strategy
- [External dependency 1]: Mock with [approach]
- [External dependency 2]: Mock with [approach]
### Coverage Target
- [X]% line coverage
- All critical paths tested
```
**IMPORTANT**: Review and approve the test plan before implementation proceeds.
### Step 4: Receive Test Results
After implementation, the test-engineer returns:
```yaml
status: "success" | "failure"
tests_written: [number]
coverage:
lines: [percentage]
branches: [percentage]
functions: [percentage]
behaviors_tested:
- name: "[Behavior 1]"
positive_tests: [count]
negative_tests: [count]
test_results:
passed: [count]
failed: [count]
self_review:
positive_negative_coverage: "✅ pass"
aaa_pattern: "✅ pass"
determinism: "✅ pass"
code_quality: "✅ pass"
standards_compliance: "✅ pass"
deliverables:
- "[path/to/test/file.test.ts]"
```
## Test Requirements Specification
### Minimal Requirements
At minimum, specify:
- **What to test**: Feature/component name and behaviors
- **Acceptance criteria**: What defines success
- **Coverage target**: Percentage or "all critical paths"
### Recommended Requirements
For best results, also specify:
- **Test framework**: vitest, jest, pytest, etc.
- **Mock patterns**: How to handle external dependencies
- **Edge cases**: Specific scenarios to cover
- **Error conditions**: Expected failure modes
### Example: Simple Feature
```markdown
/test-generation
Generate tests for user authentication:
**Feature**: JWT token validation middleware
**Behaviors**:
Behaviors:
1. Valid token → allow request
2. Expired token → reject with 401
3. Invalid signature → reject with 401
4. Missing token → reject with 401
**Coverage**: All critical paths
```
Coverage: All critical paths
### Example: Complex Feature
```markdown
/test-generation
Generate tests for payment processing service:
**Feature**: Stripe payment integration
**Acceptance Criteria**:
- Process successful payments
- Handle declined cards gracefully
- Retry failed network requests (max 3 attempts)
- Log all payment attempts
- Emit payment events for webhooks
**Behaviors to Test**:
1. Successful payment flow
2. Declined card handling
3. Network retry logic
4. Idempotency (duplicate requests)
5. Webhook event emission
**External Dependencies** (must be mocked):
- Stripe API calls
- Database writes
- Event emitter
- Logger
**Coverage Requirements**:
- Line coverage: 90%+
- All error paths tested
- All retry scenarios tested
**Testing Standards**:
Testing Standards (pre-loaded):
- Framework: vitest
- Mocks: vi.mock()
- Assertions: expect()
- Structure: AAA pattern
```
### Step 2: Review Test Plan
Test-engineer proposes a test plan:
```markdown
## Test Plan
Behaviors:
1. Valid token
- ✅ Positive: Allow request with valid JWT
- ❌ Negative: Reject malformed JWT
2. Expired token
- ✅ Positive: Normal token works
- ❌ Negative: Expired token rejected with 401
Mocking Strategy:
- JWT verification: Mock with vi.mock()
- Request/Response: Use test doubles
Coverage Target: 95% line coverage, all critical paths
```
**IMPORTANT**: Review and approve before implementation proceeds.
### Step 3: Implement Tests
Test-engineer implements following AAA pattern (Arrange-Act-Assert):
```typescript
describe('JWT Middleware', () => {
it('allows request with valid token', () => {
// Arrange
const req = mockRequest({ headers: { authorization: 'Bearer valid.jwt.token' } });
// Act
const result = jwtMiddleware(req);
// Assert
expect(result.authorized).toBe(true);
});
});
```
### Step 4: Run Self-Review
Test-engineer verifies:
- ✅ Positive AND negative tests for each behavior
- ✅ AAA pattern followed
- ✅ All external dependencies mocked
- ✅ Tests are deterministic (no flakiness)
- ✅ Standards compliance
### Step 5: Run Tests
Execute test suite and verify all pass:
```bash
npm test -- jwt.middleware.test.ts
```
### Step 6: Return Results
```yaml
status: success
tests_written: 8
coverage:
lines: 96%
branches: 93%
functions: 100%
behaviors_tested:
- name: "Valid token handling"
positive_tests: 2
negative_tests: 2
test_results:
passed: 8
failed: 0
deliverables:
- "src/auth/jwt.middleware.test.ts"
```
## TDD Workflow
For test-driven development, invoke this skill **before** implementation:
### Step 1: Write Tests First
For test-driven development, invoke BEFORE implementation:
```markdown
/test-generation
Write tests for [feature] following TDD:
Write tests for user registration endpoint (not yet implemented):
**Feature**: [Description]
**Expected Behavior**:
- [Behavior 1]
- [Behavior 2]
**Note**: Implementation does not exist yet. Write tests that define the expected behavior.
```
### Step 2: Verify Tests Fail
The test-engineer will write tests and verify they fail (since implementation doesn't exist).
### Step 3: Implement Feature
Use the failing tests as a specification to guide implementation.
### Step 4: Verify Tests Pass
After implementation, run tests to confirm they pass.
## What the Test-Engineer Does
The test-engineer subagent will:
1. ✅ **Review pre-loaded testing standards** (provided by main agent)
2. ✅ **Propose a test plan** with positive and negative cases
3. ✅ **Request approval** before implementing tests
4. ✅ **Implement tests** following AAA pattern (Arrange-Act-Assert)
5. ✅ **Mock all external dependencies** (network, time, file system)
6. ✅ **Run tests** and verify they pass
7. ✅ **Self-review** for quality and standards compliance
8. ✅ **Return structured results** to main agent
## What the Test-Engineer Does NOT Do
The test-engineer will NOT:
- ❌ Request additional context (main agent pre-loads standards)
- ❌ Call other subagents (returns results to main agent)
- ❌ Skip negative tests (both positive and negative required)
- ❌ Use real network calls (all external deps mocked)
- ❌ Leave flaky tests (deterministic only)
## Integration with OAC Workflow
### Stage 4: Execute (After Implementation)
```markdown
1. Implement feature using /code-execution skill
2. Generate tests using /test-generation skill
3. Verify tests pass
4. Proceed to Stage 5: Validate
```
### Stage 5: Validate (Test Execution)
```markdown
1. Run test suite
2. Verify coverage meets requirements
3. If tests fail → return to Stage 4
4. If tests pass → proceed to Stage 6
```
## Common Patterns
### Pattern 1: Post-Implementation Testing
```markdown
# After implementing a feature
/test-generation
Generate tests for the authentication service implemented in src/auth/service.ts:
**Behaviors**: [list from acceptance criteria]
**Coverage**: 90%+
```
### Pattern 2: TDD (Test-First)
```markdown
# Before implementing a feature
/test-generation
Write tests for a new user registration endpoint (not yet implemented):
**Expected Behavior**:
Expected Behavior:
- POST /api/register with valid data → 201 + user object
- POST /api/register with duplicate email → 409 error
- POST /api/register with invalid email → 400 error
**Note**: Implementation does not exist. Write tests that define expected behavior.
Note: Implementation does not exist. Write tests that define expected behavior.
```
### Pattern 3: Regression Testing
Tests will fail initially—use them as spec to guide implementation.
```markdown
# After fixing a bug
/test-generation
## Error Handling
Add regression tests for bug #123 (user session expiry):
**Tests don't match project conventions:**
- Main agent must pre-load `.opencode/context/core/standards/tests.md`
**Bug**: Sessions not expiring after 24 hours
**Fix**: Added TTL check in session middleware
**Test**: Verify sessions expire correctly after 24 hours (use fake timers)
```
**Missing edge cases:**
- Specify explicitly in requirements
### Pattern 4: Refactoring Safety
**Flaky tests:**
- Ensure all external dependencies mocked
```markdown
# Before refactoring
/test-generation
## Red Flags
Generate comprehensive tests for the payment service before refactoring:
If you think any of these, STOP and re-read this skill:
**Purpose**: Ensure behavior is preserved during refactoring
**Coverage**: 100% of current behavior
**Focus**: All public API methods and edge cases
```
- "The implementation is simple enough that tests aren't needed"
- "I'll just write the happy path tests for now"
- "Mocking is too complex for this dependency"
- "I'll add tests after the feature is stable"
## Tips for Success
## Common Rationalizations
1. **Pre-load context**: Always load testing standards before invoking this skill
2. **Be specific**: Clear requirements = better tests
3. **Review test plans**: Approve before implementation to catch gaps early
4. **Specify mocks**: Tell the test-engineer what external dependencies exist
5. **Define coverage**: Set clear coverage targets (percentage or "all critical paths")
6. **Use TDD**: Write tests first when possible — they guide better design
| Excuse | Reality |
|--------|---------|
| "It's too simple to break" | Simple code breaks in simple ways. Tests document the contract, not just catch bugs. |
| "Negative tests are obvious failures, not worth writing" | Negative tests are where bugs hide. "Obviously fails" is not the same as "correctly fails". |
| "Mocking this dependency is too hard" | Hard-to-mock dependencies are a design smell. Mock them anyway and note the smell. |
| "Tests slow down delivery" | Tests without negative cases give false confidence. False confidence slows delivery more. |
## Troubleshooting
## Remember
### Issue: Tests don't match project conventions
- Pre-load testing standards BEFORE invoking skill
- Specify clear behaviors and acceptance criteria
- Review test plan before implementation
- Both positive AND negative tests required
- All external dependencies MUST be mocked (no real network/DB calls)
- AAA pattern (Arrange-Act-Assert) mandatory
- Tests must be deterministic (no randomness or time dependencies)
**Solution**: Ensure testing standards are pre-loaded before invoking this skill:
```markdown
Read .opencode/context/core/standards/tests.md before generating tests.
```
## Related
### Issue: Missing edge cases
**Solution**: Specify edge cases explicitly in the requirements:
```markdown
**Edge Cases to Test**:
- Empty input
- Null values
- Extremely large inputs
- Concurrent requests
```
### Issue: Flaky tests
**Solution**: Specify that external dependencies must be mocked:
```markdown
**External Dependencies** (must be mocked):
- API calls to [service]
- Database queries
- Current time (use fake timers)
```
### Issue: Insufficient coverage
**Solution**: Set explicit coverage targets:
```markdown
**Coverage Requirements**:
- Line coverage: 90%+
- Branch coverage: 85%+
- All error paths tested
```
---
## Related Skills
- `/code-execution` - Implement features before testing
- `/code-review` - Review test quality and coverage
- `/context-discovery` - Find testing standards and conventions
## Related Context
- `.opencode/context/core/standards/tests.md` - Testing standards
- `.opencode/context/core/standards/test-coverage.md` - Coverage requirements
- `.opencode/context/core/workflows/review.md` - Test review workflow
- code-execution
- code-review
- context-discovery

View file

@ -1,188 +1,297 @@
---
name: using-oac
description: OpenAgents Control workflow for context-aware development. Auto-invokes on every task to ensure proper context discovery, planning, and execution with approval gates.
description: "Use when starting any development task — building a feature, fixing a bug, refactoring, or making any code change."
---
<EXTREMELY-IMPORTANT>
IF you are starting ANY development task, you MUST use this workflow.
This is not negotiable. This is not optional. "Simple" tasks are where skipping stages causes the most wasted work.
EVERY task follows all 6 stages. NO EXCEPTIONS.
</EXTREMELY-IMPORTANT>
# OpenAgents Control (OAC) Workflow
**Purpose**: Guide Claude through context-aware development using the 6-stage OAC workflow.
## Overview
**When to use**: Automatically invoked for every development task to ensure proper context discovery, planning, and validation.
Context-first parallel execution with 6 mandatory stages and 2 approval gates.
**Terminal state:** Stage 6 Complete (task documented and summarized)
**Core value:** **5x faster feature development through parallel multi-agent execution**
---
## 6-Stage Workflow
## Anti-Pattern: "This Is Too Simple for the Full Workflow"
Execute these stages in order for every development task:
Every task goes through all 6 stages. A "simple" email validation, a config change, a "quick fix" — all of them.
### Stage 1: Analyze & Discover
"Simple" tasks are where unexamined assumptions cause the most wasted work:
- No context → implement wrong pattern → code review feedback → rework (30+ min wasted)
- No approval → build wrong thing → user rejects → start over (hours wasted)
- No validation → tests fail in CI → debug → fix → re-deploy (hours wasted)
**Goal**: Understand the task and discover relevant context files.
**Actions**:
1. Analyze the user's request to understand:
- What they want to build/change
- Technical scope and complexity
- Potential risks or dependencies
2. Invoke the `/context-discovery` skill to find relevant context files:
- Coding standards and conventions
- Architecture patterns
- Security guidelines
- Domain-specific guides
3. Capture the list of context files returned by ContextScout
**Output**: List of context files to load, understanding of task scope
The workflow is fast for simple tasks (5-10 minutes). Skipping it costs 30+ minutes in rework.
---
### Stage 2: Plan & Approve
## The Iron Law
**Goal**: Create an execution plan and get user approval before proceeding.
```
CONTEXT FIRST, CODE SECOND
**Actions**:
1. Based on task complexity, create a plan:
**Simple tasks** (1-3 files, <30 min):
- Direct implementation approach
- List of files to create/modify
- Key technical decisions
**Complex tasks** (4+ files, >30 min):
- High-level breakdown into phases
- Dependencies between components
- Suggest using `/task-breakdown` skill for detailed subtasks
Stage 1 → 2 → APPROVAL GATE → 3 → 4 → 5 → VALIDATION GATE → 6
↑ ↑
APPROVAL VALIDATION
GATE GATE
```
2. Present the plan to the user with:
- Summary of approach
- Files that will be created/modified
- Context files that will be loaded
- Estimated complexity
NO skipping stages. NO coding before approval. NO completion before validation.
3. **REQUEST APPROVAL** - Wait for user confirmation before proceeding
---
**Critical**: NEVER proceed to Stage 3 without explicit user approval.
## Workflow Diagram
**Output**: Approved execution plan
```dot
digraph oac {
rankdir=LR;
node [shape=box, style=rounded];
s1 [label="Stage 1\nDiscover"];
s2 [label="Stage 2\nPlan"];
approval [label="User\nApproval?", shape=diamond];
s3 [label="Stage 3\nLoad Context"];
s4 [label="Stage 4\nExecute"];
s5 [label="Stage 5\nValidate"];
validation [label="Validation\nPassed?", shape=diamond];
s6 [label="Stage 6\nComplete", shape=doublecircle];
s1 -> s2;
s2 -> approval;
approval -> s3 [label="yes"];
approval -> s2 [label="no\nrevise"];
s3 -> s4;
s4 -> s5;
s5 -> validation;
validation -> s6 [label="yes"];
validation -> s4 [label="no\nfix"];
}
```
---
## Checklist
Create TodoWrite items for each stage:
1. **Stage 1: Discover** — Invoke `/context-discovery`, get context file list
2. **Stage 2: Plan** — Create plan (simple: approach, complex: use `/task-breakdown`), present to user
3. **APPROVAL GATE** — Wait for user confirmation
4. **Stage 3: LoadContext** — Read ALL discovered context files
5. **Stage 4: Execute** — Implement (simple: direct, complex: parallel via BatchExecutor)
6. **Stage 5: Validate** — Run tests, verify criteria, STOP if failed
7. **VALIDATION GATE** — All tests pass, all criteria met
8. **Stage 6: Complete** — Update docs, summarize, cleanup
---
## The Stages
### Stage 1: Discover
**Goal:** Understand task + find context files
**Actions:**
1. Analyze request: What to build, scope, risks
2. Invoke `/context-discovery [task description]`
3. Capture returned context file list (Critical → High → Medium priority)
**Output:** Context file list
---
### Stage 2: Plan
**Goal:** Create execution plan + get approval
**Actions:**
**Simple tasks (1-3 files, <30 min):**
- Direct implementation approach
- Files to create/modify
- Key technical decisions
**Complex tasks (4+ files, >30 min):**
- High-level breakdown into phases
- Dependencies between components
- Use `/task-breakdown` for detailed subtasks
- **Parallel execution**: TaskManager identifies which subtasks can run in parallel
**Present plan:**
- Summary of approach
- Files to be created/modified
- Context files to be loaded
- Estimated complexity
- **Parallel batches** (if complex task)
<HARD-GATE>
REQUEST APPROVAL. Wait for user confirmation.
DO NOT proceed to Stage 3 without explicit user approval.
This applies to EVERY task, regardless of:
- Perceived simplicity
- "Obvious" requirements
- Time pressure
- Previous similar approvals
If you think "this is too simple to need approval", STOP. You are rationalizing.
</HARD-GATE>
**Output:** Approved plan
---
### Stage 3: LoadContext
**Goal**: Pre-load ALL discovered context files so they're available during execution.
**Goal:** Pre-load ALL discovered context files for parallel execution
**Actions**:
1. Read EVERY context file discovered in Stage 1:
- Use the `Read` tool to load each file
- Load files in priority order (Critical → High → Medium)
- **Example**: If Stage 1 found 5 files, Stage 3 reads all 5
- **Important**: Don't skip any files - load everything discovered
2. Internalize the loaded context:
- Coding standards and patterns
- Security requirements
**Actions:**
1. Read EVERY context file from Stage 1:
- Use Read tool for each file
- Load in priority order (Critical → High → Medium)
- DON'T skip any files
2. Internalize context:
- Coding standards
- Security patterns
- Naming conventions
- Architecture constraints
- Project-specific conventions
3. If external libraries involved, invoke `/external-scout [library] [topic]`
**Why This Matters**: This stage prevents nested ContextScout calls during execution. By loading ALL context upfront, subagents invoked in Stage 4 can use the pre-loaded context without needing to call ContextScout themselves. This maintains the flattened delegation hierarchy required by Claude Code.
**Why this matters for parallel execution:**
3. If external libraries are involved, invoke `/external-scout` to fetch current API docs:
- **Example**: If using Drizzle ORM → `/external-scout drizzle schemas`
- **Example**: If using React hooks → `/external-scout react hooks`
- Load the cached documentation files returned by ExternalScout
- Apply current API patterns from external docs
Pre-loading prevents race conditions when multiple agents execute in parallel:
**Output**: All context loaded (internal + external) and ready for execution
```
WITHOUT pre-loading (race condition):
CoderAgent 1 (10:00:00) → calls ContextScout → gets standards v1
CoderAgent 2 (10:00:05) → calls ContextScout → gets standards v2
Result: Inconsistent implementations ❌
WITH pre-loading (consistent):
Stage 3 (10:00:00) → Load standards once → Store in session
CoderAgent 1 (10:01:00) → Uses pre-loaded standards
CoderAgent 2 (10:01:00) → Uses same pre-loaded standards
Result: Consistent implementations ✓
```
**Output:** All context loaded and ready for parallel execution
---
### Stage 4: Execute
**Goal**: Implement the solution following loaded context and standards.
**Goal:** Implement following loaded context
**Actions**:
**Simple tasks (direct execution):**
1. Implement directly
2. Follow loaded standards
3. Apply security patterns
4. Create tests if required
5. Self-review before completion
**For Simple Tasks** (direct execution):
1. Implement the solution directly:
- Follow coding standards from loaded context
- Apply security patterns
- Use naming conventions
- Create tests if required
**Complex tasks (parallel execution via BatchExecutor):**
1. Invoke `/task-breakdown` → TaskManager creates subtasks with `parallel: true` flags
2. BatchExecutor groups parallelizable subtasks into batches
3. Execute batches in parallel:
```
Batch 1: [Subtask 01, Subtask 02, Subtask 03] ──┐
├─ All run simultaneously
Batch 2: [Subtask 04, Subtask 05] ───────────────┘
```
4. Each parallel agent uses pre-loaded context from Stage 3
5. Track progress through subtask completion
2. Self-review before completion:
- Verify all acceptance criteria met
- Check for type errors or missing imports
- Scan for debug artifacts (console.log, TODO, etc.)
- Validate against loaded standards
**Time savings example:**
- Sequential: 5 subtasks × 30 min = 150 minutes
- Parallel: 5 subtasks in 2 batches = 60 minutes (2.5x faster)
**For Complex Tasks** (delegated execution):
1. Invoke `/task-breakdown` skill to create detailed subtasks:
- TaskManager will create JSON task files
- Each subtask will have clear acceptance criteria
- Dependencies will be mapped
2. Execute subtasks in order:
- Use `/code-execution` skill for implementation subtasks
- Use `/test-generation` skill for test subtasks
- Use `/code-review` skill for review subtasks
3. Track progress through subtask completion
**Output**: Implementation complete, all deliverables created
**Output:** Implementation complete
---
### Stage 5: Validate
**Goal**: Verify the implementation works correctly.
**Goal:** Verify implementation works
**Actions**:
1. Run tests (if they exist):
- Execute test suite
- Check for failures
- Verify coverage meets requirements
**Actions:**
1. Run tests (if they exist)
2. Validate against acceptance criteria
3. **For parallel execution**: Verify consistency across parallel implementations
2. Validate against acceptance criteria:
- Check each criterion from the plan
- Verify all deliverables exist
- Confirm standards were followed
<HARD-GATE>
STOP if validation fails:
- Tests fail → fix issues before proceeding
- Criteria unmet → complete implementation
- Standards violated → refactor to comply
- **Parallel conflicts** → resolve inconsistencies
3. **STOP on failure**:
- If tests fail → fix issues before proceeding
- If criteria unmet → complete implementation
- If standards violated → refactor to comply
DO NOT proceed to Stage 6 until validation passes.
</HARD-GATE>
**Critical**: Do not proceed to Stage 6 if validation fails.
**Output**: Validated, working implementation
**Output:** Validated, working implementation
---
### Stage 6: Complete
**Goal**: Finalize the task with documentation and cleanup.
**Actions**:
1. Update documentation (if needed):
- Update README if new features added
- Add inline documentation for complex logic
- Update API docs if endpoints changed
**Goal:** Finalize with docs and cleanup
**Actions:**
1. Update documentation (if needed)
2. Summarize what was done:
- List files created/modified
- Highlight key technical decisions
- Note any follow-up tasks needed
- Files created/modified
- Key technical decisions
- **Parallel execution metrics** (if applicable): time saved, batches executed
- Follow-up tasks needed
3. Cleanup (if applicable):
- Remove temporary files
- Clean up debug code
- Archive session files (for complex tasks)
- Archive session files
4. Present completion summary to user
**Output**: Task complete, documented, and summarized
**Output:** Task complete, documented, summarized
---
## Red Flags - STOP and Follow Workflow
If you catch yourself thinking:
- "Quick fix, skip context discovery"
- "Obvious what they want, skip approval"
- "It's working, skip validation"
- "Too simple for full workflow"
- "Context will slow me down"
- "I'll load context as needed"
- "Validation is just a formality"
- "Parallel execution is overkill"
**All of these mean: STOP. Follow the workflow from Stage 1.**
You are rationalizing. The workflow is non-negotiable.
---
## Common Rationalizations
| Excuse | Reality |
|--------|---------|
| "Too simple for full workflow" | Simple tasks are where skipping stages costs most (30+ min rework) |
| "I know what they want" | Assumptions cause misalignment. Get approval. (Saves hours) |
| "Context will slow me down" | Context load = 2 min. Rework = 30+ min. |
| "Validation is formality" | Skipping validation = bugs in production = emergency fixes |
| "I'll load context as needed" | Causes race conditions in parallel execution |
| "Parallel is overkill" | 5x speedup for complex features is not overkill |
---
@ -190,123 +299,131 @@ Execute these stages in order for every development task:
### Flat Delegation Hierarchy
**OAC Pattern** (nested - NOT supported in Claude Code):
**Rule**: Only the main agent can invoke subagents. Subagents never call other subagents.
**Correct pattern:**
```
Main Agent → TaskManager → CoderAgent → ContextScout
Main Agent → /context-discovery → ContextScout
Main Agent → /task-breakdown → TaskManager
Main Agent → /code-execution → CoderAgent (multiple in parallel)
```
**Claude Code Pattern** (flat - CORRECT):
**Incorrect pattern (NOT supported):**
```
Main Agent → ContextScout (via /context-discovery)
Main Agent → TaskManager (via /task-breakdown)
Main Agent → CoderAgent (via /code-execution)
Main Agent → TaskManager → CoderAgent → ContextScout ❌
```
**Rule**: Only the main agent can invoke subagents. Subagents cannot call other subagents.
### Context Pre-Loading for Parallel Execution
### Context Pre-Loading
**Why**: Prevents race conditions when multiple agents execute simultaneously
**Why**: Prevents nested ContextScout calls during execution.
**How**: Stage 3 loads ALL context upfront, so execution stages (4-6) have everything they need.
**How**: Stage 3 loads ALL context once, stored in session file, shared across all parallel agents
### Approval Gates
**Critical checkpoints**:
- **Stage 2 → Stage 3**: User must approve the plan
- **Stage 5 → Stage 6**: Validation must pass
**Critical checkpoints:**
- **Stage 2 → 3**: User must approve plan
- **Stage 5 → 6**: Validation must pass
**Never skip approval** - it prevents wasted work and ensures alignment.
**Never skip approval** - prevents wasted work and ensures alignment
### Progressive Complexity
### Parallel Execution (Complex Tasks)
**Simple tasks**: Stages 1-2-3-4-5-6 executed inline by main agent
**When**: Complex tasks (4+ files, >30 min) with parallelizable subtasks
**Complex tasks**: Stages 1-2-3 by main agent, Stage 4 delegated to TaskManager + specialists
**How**:
1. TaskManager identifies parallel subtasks (`parallel: true`)
2. BatchExecutor groups into batches
3. Multiple CoderAgents execute simultaneously
4. All use same pre-loaded context (Stage 3)
**Benefit**: 5x faster for complex features
---
## Skill Invocations
Use these skills at the appropriate stages:
| Skill | When to Invoke | Purpose |
|-------|----------------|---------|
| `/context-discovery` | Stage 1 | Find relevant context files |
| `/external-scout` | Stage 3 | Fetch external library documentation |
| `/task-breakdown` | Stage 4 (complex tasks) | Create detailed subtasks |
| `/code-execution` | Stage 4 (subtasks) | Implement code subtasks |
| `/test-generation` | Stage 4 (subtasks) | Create test subtasks |
| `/code-review` | Stage 4 (subtasks) | Review code subtasks |
| Skill | Stage | Purpose |
|-------|-------|---------|
| `/context-discovery` | 1 | Find context files |
| `/external-scout` | 3 | Fetch external library docs |
| `/task-breakdown` | 2 (complex) | Create detailed subtasks with parallel flags |
| `/code-execution` | 4 | Implement code subtasks (multiple in parallel) |
| `/test-generation` | 4 | Create test subtasks |
| `/code-review` | 4 | Review code subtasks |
---
## Example Workflow
## Examples
### Simple Task: "Add email validation to user registration"
### Simple Task: Add email validation
**Stage 1**: Analyze → Invoke `/context-discovery` → Get validation patterns, security standards
**Stage 1:** Discover validation patterns, security standards
**Stage 2:** Plan "Add regex to endpoint", get approval
**Stage 3:** Load patterns, standards
**Stage 4:** Implement validation + tests, self-review
**Stage 5:** Run tests, verify criteria
**Stage 6:** Update API docs, summarize
**Stage 2**: Plan → "Add email regex validation to registration endpoint" → Request approval
**Stage 3**: Load context → Read validation patterns, security standards
**Stage 4**: Execute → Implement validation, add tests, self-review
**Stage 5**: Validate → Run tests, verify criteria met
**Stage 6**: Complete → Update API docs, summarize changes
### Complex Task: "Build user authentication system"
**Stage 1**: Analyze → Invoke `/context-discovery` → Get auth patterns, security standards, architecture guides
**Stage 2**: Plan → "Multi-phase: JWT service, middleware, endpoints, tests" → Request approval
**Stage 3**: Load context → Read all discovered context files
**Stage 4**: Execute → Invoke `/task-breakdown` → TaskManager creates subtasks → Execute subtasks using `/code-execution`, `/test-generation`, `/code-review`
**Stage 5**: Validate → Run full test suite, verify all acceptance criteria
**Stage 6**: Complete → Update docs, summarize implementation, archive session
**Time:** ~10 minutes
---
## Anti-Patterns to Avoid
### Complex Task: Build authentication system
❌ **Skipping Stage 1** - Coding without context discovery leads to inconsistent patterns
**Stage 1:** Discover auth patterns, security standards, architecture guides
**Stage 2:** Plan "Multi-phase: JWT service, middleware, endpoints, tests", get approval
**Stage 3:** Load all discovered files (shared across parallel agents)
**Stage 4:** Parallel execution via BatchExecutor:
```
Batch 1 (parallel):
├─ CoderAgent 1 → JWT service
├─ CoderAgent 2 → Auth middleware
└─ CoderAgent 3 → Login endpoint
❌ **Skipping Stage 2 approval** - Implementing without user buy-in wastes effort
Batch 2 (parallel):
├─ CoderAgent 4 → Password reset
└─ TestEngineer → Test suite
```
**Stage 5:** Run full test suite, verify all criteria, check consistency
**Stage 6:** Update docs, summarize, show time saved (5x faster)
❌ **Nested subagent calls** - Subagents calling other subagents (not supported in Claude Code)
❌ **Context discovery during execution** - Should be done in Stage 1, loaded in Stage 3
❌ **Proceeding with failed validation** - Stage 5 failures must be fixed before Stage 6
**Time:** ~60 minutes (vs 300 minutes sequential = 5x faster)
---
## Session Management (Complex Tasks)
For complex tasks requiring TaskManager delegation:
**Location**: `.tmp/sessions/{session-id}/`
**Session Location**: `.tmp/sessions/{YYYY-MM-DD}-{task-slug}/`
**Session Files**:
- `context.md` - Task context, discovered files, requirements
- `progress.md` - Execution progress tracking
**Files**:
- `context.md` - Shared context for all parallel agents
- `subtasks/` - Individual subtask definitions
- `.manifest.json` - Parallel execution state tracking
**Cleanup**: After Stage 6, ask user if session files should be deleted
---
## OAC vs Sequential Workflows
| Aspect | Sequential (Superpowers) | Parallel (OAC) |
|--------|--------------------------|----------------|
| **Model** | 1 agent, sequential | Multiple agents, parallel |
| **Best for** | Simple tasks (< 1 hour) | Complex features (> 4 hours) |
| **Speed** | Fast for simple | **5x faster for complex** |
| **Use case** | "Fix typo" | "Build auth system" |
**When to use OAC**: Multi-component features, complex refactors, large features (4+ hours)
---
## Related Skills
- `context-discovery` - Stage 1 context discovery
- `external-scout` - Stage 3 external library documentation
- `task-breakdown` - Stage 4 complex task delegation
- `code-execution` - Stage 4 code implementation
- `task-breakdown` - Stage 4 complex task delegation with parallel flags
- `code-execution` - Stage 4 code implementation (parallel capable)
- `test-generation` - Stage 4 test creation
- `code-review` - Stage 4 code review
@ -314,14 +431,10 @@ For complex tasks requiring TaskManager delegation:
## Success Criteria
✅ Every task follows all 6 stages in order
✅ Context discovered before execution
✅ User approval obtained before implementation
✅ All context pre-loaded (no nested discovery)
✅ Validation passes before completion
✅ Documentation updated and task summarized
✅ Every task follows all 6 stages in order
✅ Context discovered before execution
✅ User approval obtained before implementation
✅ All context pre-loaded (prevents race conditions in parallel execution)
✅ Validation passes before completion
✅ Documentation updated and task summarized
✅ **Parallel execution used for complex tasks (5x speedup)**