diff --git a/plugins/claude-code/.claude-plugin/plugin.json b/plugins/claude-code/.claude-plugin/plugin.json index 0264355..c5a0aef 100644 --- a/plugins/claude-code/.claude-plugin/plugin.json +++ b/plugins/claude-code/.claude-plugin/plugin.json @@ -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"] } diff --git a/plugins/claude-code/FIRST-TIME-SETUP.md b/plugins/claude-code/FIRST-TIME-SETUP.md deleted file mode 100644 index bc452e2..0000000 --- a/plugins/claude-code/FIRST-TIME-SETUP.md +++ /dev/null @@ -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 diff --git a/plugins/claude-code/INSTALL.md b/plugins/claude-code/INSTALL.md deleted file mode 100644 index b2897f6..0000000 --- a/plugins/claude-code/INSTALL.md +++ /dev/null @@ -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 diff --git a/plugins/claude-code/QUICK-START.md b/plugins/claude-code/QUICK-START.md deleted file mode 100644 index 310ce9b..0000000 --- a/plugins/claude-code/QUICK-START.md +++ /dev/null @@ -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. diff --git a/plugins/claude-code/README.md b/plugins/claude-code/README.md index 7f77e8a..e73a40c 100644 --- a/plugins/claude-code/README.md +++ b/plugins/claude-code/README.md @@ -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=]` +**Usage**: `/install-context [--core|--all|--category=]` **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) diff --git a/plugins/claude-code/agents/code-reviewer.md b/plugins/claude-code/agents/code-reviewer.md index f101338..44a055a 100644 --- a/plugins/claude-code/agents/code-reviewer.md +++ b/plugins/claude-code/agents/code-reviewer.md @@ -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: + + 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." + Implementation is complete โ€” code-reviewer validates before commit. + + + 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." + Explicit review request on specific files โ€” code-reviewer is the right agent. + tools: Read, Glob, Grep +disallowedTools: Write, Edit, Bash, Task model: sonnet --- diff --git a/plugins/claude-code/agents/coder-agent.md b/plugins/claude-code/agents/coder-agent.md index 576965e..44a23c9 100644 --- a/plugins/claude-code/agents/coder-agent.md +++ b/plugins/claude-code/agents/coder-agent.md @@ -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: + + 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." + A subtask JSON file exists with clear criteria โ€” coder-agent is the right choice. + + + 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." + A concrete implementation task with a specific file โ€” coder-agent executes it. + tools: Read, Write, Edit, Glob, Grep model: sonnet --- diff --git a/plugins/claude-code/agents/context-scout.md b/plugins/claude-code/agents/context-scout.md index ff53f6a..ad9dc31 100644 --- a/plugins/claude-code/agents/context-scout.md +++ b/plugins/claude-code/agents/context-scout.md @@ -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: + + 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." + New feature starting โ€” context-scout finds the relevant standards first. + + + 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." + Standards needed before coding โ€” context-scout navigates the context system to find them. + 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`) diff --git a/plugins/claude-code/agents/external-scout.md b/plugins/claude-code/agents/external-scout.md index 90da11d..debc31e 100644 --- a/plugins/claude-code/agents/external-scout.md +++ b/plugins/claude-code/agents/external-scout.md @@ -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 --- diff --git a/plugins/claude-code/commands/install-context.md b/plugins/claude-code/commands/install-context.md new file mode 100644 index 0000000..2efc6a1 --- /dev/null +++ b/plugins/claude-code/commands/install-context.md @@ -0,0 +1,110 @@ +--- +name: install-context +description: Install OpenAgents Control context files from registry with interactive profile selection +argument-hint: [--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=` - 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=` - 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 \ No newline at end of file diff --git a/plugins/claude-code/commands/oac-add-context.md b/plugins/claude-code/commands/oac-add-context.md deleted file mode 100644 index 3c384e0..0000000 --- a/plugins/claude-code/commands/oac-add-context.md +++ /dev/null @@ -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=` - -**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=` - -**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 <] [--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=` - Target category (default: custom) -- `--priority=` - 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 diff --git a/plugins/claude-code/commands/oac-plan.md b/plugins/claude-code/commands/oac-plan.md deleted file mode 100644 index 062a45c..0000000 --- a/plugins/claude-code/commands/oac-plan.md +++ /dev/null @@ -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 diff --git a/plugins/claude-code/commands/oac-setup.md b/plugins/claude-code/commands/oac-setup.md deleted file mode 100644 index 3b20752..0000000 --- a/plugins/claude-code/commands/oac-setup.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -name: oac:setup -description: Download OpenAgents Control context files from GitHub repository -argument-hint: "[--core|--all|--category=]" -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=` - 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. diff --git a/plugins/claude-code/commands/oac-status.md b/plugins/claude-code/commands/oac-status.md index c307f32..21f3015 100644 --- a/plugins/claude-code/commands/oac-status.md +++ b/plugins/claude-code/commands/oac-status.md @@ -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 diff --git a/plugins/claude-code/hooks/hooks.json b/plugins/claude-code/hooks/hooks.json index 8db0a8c..176d050 100644 --- a/plugins/claude-code/hooks/hooks.json +++ b/plugins/claude-code/hooks/hooks.json @@ -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 } ] diff --git a/plugins/claude-code/hooks/session-start.sh b/plugins/claude-code/hooks/session-start.sh index 521523d..479478f 100644 --- a/plugins/claude-code/hooks/session-start.sh +++ b/plugins/claude-code/hooks/session-start.sh @@ -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\nIN 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." +if [[ ! -f "${PLUGIN_ROOT}/.context-manifest.json" ]]; then + warning_message="\n\nIN 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." fi warning_escaped=$(escape_for_json "$warning_message") -# Output context injection as JSON +# Build context string once, reuse in both output formats +OAC_CONTEXT="\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" + +# Output dual-format JSON for cross-tool compatibility +# - additionalContext: Claude Code (hookSpecificOutput) +# - additional_context: Cursor / OpenCode / other tools cat <\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" + "additionalContext": "${OAC_CONTEXT}" } } EOF diff --git a/plugins/claude-code/scripts/README.md b/plugins/claude-code/scripts/README.md new file mode 100644 index 0000000..a073714 --- /dev/null +++ b/plugins/claude-code/scripts/README.md @@ -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. diff --git a/plugins/claude-code/scripts/cleanup-tmp.sh b/plugins/claude-code/scripts/cleanup-tmp.sh old mode 100644 new mode 100755 index 64bac72..0ee0b73 --- a/plugins/claude-code/scripts/cleanup-tmp.sh +++ b/plugins/claude-code/scripts/cleanup-tmp.sh @@ -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 </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 <&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" </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 "$@" diff --git a/plugins/claude-code/scripts/install-context.js b/plugins/claude-code/scripts/install-context.js new file mode 100755 index 0000000..6caf763 --- /dev/null +++ b/plugins/claude-code/scripts/install-context.js @@ -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(); diff --git a/plugins/claude-code/scripts/install-context.ts b/plugins/claude-code/scripts/install-context.ts new file mode 100644 index 0000000..fc55096 --- /dev/null +++ b/plugins/claude-code/scripts/install-context.ts @@ -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 { + 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 { + 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) +}) diff --git a/plugins/claude-code/scripts/load-config.sh b/plugins/claude-code/scripts/load-config.sh deleted file mode 100644 index 8e4c2a9..0000000 --- a/plugins/claude-code/scripts/load-config.sh +++ /dev/null @@ -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 < { + 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) +}) diff --git a/plugins/claude-code/scripts/tsconfig.json b/plugins/claude-code/scripts/tsconfig.json new file mode 100644 index 0000000..f03bc52 --- /dev/null +++ b/plugins/claude-code/scripts/tsconfig.json @@ -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"] +} diff --git a/plugins/claude-code/scripts/types/manifest.ts b/plugins/claude-code/scripts/types/manifest.ts new file mode 100644 index 0000000..e20c581 --- /dev/null +++ b/plugins/claude-code/scripts/types/manifest.ts @@ -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 + +// 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 + +// Manifest creation options +export interface CreateManifestOptions { + profile: Profile | 'custom' + repository: string + branch: string + commit: string + components: ManifestComponent[] +} diff --git a/plugins/claude-code/scripts/types/registry.ts b/plugins/claude-code/scripts/types/registry.ts new file mode 100644 index 0000000..275a449 --- /dev/null +++ b/plugins/claude-code/scripts/types/registry.ts @@ -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 + +// 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 + +// 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 + }> +} diff --git a/plugins/claude-code/scripts/utils/git-sparse.ts b/plugins/claude-code/scripts/utils/git-sparse.ts new file mode 100644 index 0000000..a323818 --- /dev/null +++ b/plugins/claude-code/scripts/utils/git-sparse.ts @@ -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 { + 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 + } +} diff --git a/plugins/claude-code/scripts/utils/registry-fetcher.ts b/plugins/claude-code/scripts/utils/registry-fetcher.ts new file mode 100644 index 0000000..f8e6c12 --- /dev/null +++ b/plugins/claude-code/scripts/utils/registry-fetcher.ts @@ -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 { + 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 = { + 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() + + 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) +} diff --git a/plugins/claude-code/scripts/verify-context.sh b/plugins/claude-code/scripts/verify-context.sh deleted file mode 100644 index 82e8bae..0000000 --- a/plugins/claude-code/scripts/verify-context.sh +++ /dev/null @@ -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 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 < **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 ``` -**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. diff --git a/plugins/claude-code/skills/install-context/SKILL.md b/plugins/claude-code/skills/install-context/SKILL.md new file mode 100644 index 0000000..964f2ee --- /dev/null +++ b/plugins/claude-code/skills/install-context/SKILL.md @@ -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 diff --git a/plugins/claude-code/skills/parallel-execution/SKILL.md b/plugins/claude-code/skills/parallel-execution/SKILL.md index 37c6bcc..2e96a5c 100644 --- a/plugins/claude-code/skills/parallel-execution/SKILL.md +++ b/plugins/claude-code/skills/parallel-execution/SKILL.md @@ -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. diff --git a/plugins/claude-code/skills/task-breakdown/SKILL.md b/plugins/claude-code/skills/task-breakdown/SKILL.md index 0116b34..e352449 100644 --- a/plugins/claude-code/skills/task-breakdown/SKILL.md +++ b/plugins/claude-code/skills/task-breakdown/SKILL.md @@ -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** diff --git a/plugins/claude-code/skills/test-generation/SKILL.md b/plugins/claude-code/skills/test-generation/SKILL.md index e31c0b4..59f0d8f 100644 --- a/plugins/claude-code/skills/test-generation/SKILL.md +++ b/plugins/claude-code/skills/test-generation/SKILL.md @@ -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 diff --git a/plugins/claude-code/skills/using-oac/SKILL.md b/plugins/claude-code/skills/using-oac/SKILL.md index 4792b30..e82e7e5 100644 --- a/plugins/claude-code/skills/using-oac/SKILL.md +++ b/plugins/claude-code/skills/using-oac/SKILL.md @@ -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." --- + +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. + + # 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) + + +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. + + +**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 + +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. + -**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)**