feat(lint): resolve all ESLint errors and complete compatibility layer (Issue #141) (#176)

* feat: implement compatibility layer foundation (Issue #141)

- Add TypeScript project setup with strict mode and Vitest
- Implement 20+ Zod validation schemas for OpenAgent format
- Create BaseAdapter abstract class with template method pattern
- Add context documentation for compatibility layer workflow
- Setup ESLint, TypeScript, and test configuration

Phase 1 Foundation: 50% complete (subtasks 01-03)
Related: #141

* feat: implement AgentLoader with TypeScript (Issue #141)

- Add AgentLoader class for loading OAC agent files
- Implement parseFrontmatter() for YAML extraction
- Add extractSections() for markdown parsing (skills, examples, commands, workflow)
- Create custom error classes: AgentLoadError, FrontmatterParseError, ValidationError
- Support single file and recursive directory loading
- Add metadata merging from agent-metadata.json
- Export convenience functions: loadAgent(), loadAgents()
- Full Zod schema validation with descriptive error messages
- 386 lines, type-safe with strict mode

Phase 1 Foundation: 66.7% complete (subtask 04/06)
Related: #141

* feat: implement AdapterRegistry with TypeScript (Issue #141)

- Add AdapterRegistry class for managing tool adapters
- Implement type-safe registration with Map<string, BaseAdapter>
- Add alias support for adapter names (case-insensitive)
- Create custom error class: AdapterRegistryError
- Implement methods: register(), get(), list(), has(), getAll(), unregister(), clear()
- Add capability-based adapter discovery: getCapabilities(), findByFeature()
- Export singleton registry instance and convenience functions
- Support lazy loading of built-in adapters (placeholder for Phase 2)
- 416 lines, fully type-safe with strict mode

Features:
- Duplicate registration prevention
- Alias conflict detection
- O(1) adapter lookup
- Sorted adapter listings
- Comprehensive JSDoc documentation

Phase 1 Foundation: 83.3% complete (subtask 05/06)
Related: #141

* feat: create main entry point index.ts (Issue #141)

- Add comprehensive barrel exports for public API
- Export all Zod schemas and TypeScript types
- Export AgentLoader class and convenience functions
- Export AdapterRegistry, singleton, and helpers
- Export error classes: AgentLoadError, FrontmatterParseError, ValidationError, AdapterRegistryError
- Export BaseAdapter for custom adapter creation
- Add package VERSION constant
- Include JSDoc documentation with usage examples
- Organized exports by category (types, core, adapters)
- 168 lines with comprehensive documentation

All exports:
- Types: All Zod schemas and inferred TypeScript types
- Core: AgentLoader, AdapterRegistry, registry singleton
- Adapters: BaseAdapter abstract class
- Errors: All custom error classes
- Utilities: Convenience functions (loadAgent, getAdapter, etc.)

Phase 1 Foundation: 100% COMPLETE! 🎉 (6/6 subtasks)
Related: #141

* feat: implement ClaudeAdapter with bidirectional conversion (Issue #141)

- Implement ClaudeAdapter extending BaseAdapter
- Support toOAC() conversion from Claude Code format to OAC
- Support fromOAC() conversion from OAC to Claude Code format
- Handle .claude/config.json for primary agents
- Handle .claude/agents/*.md for subagents with YAML frontmatter
- Map Claude Skills system to/from OAC contexts
- Map hooks (PreToolUse, PostToolUse, etc.) bidirectionally
- Degrade granular OAC permissions to Claude permissionMode
- Add warnings for unsupported features (temperature, maxSteps)
- Export ClaudeAdapter from main index.ts

Capabilities:
- supportsMultipleAgents: true
- supportsSkills: true
- supportsHooks: true
- supportsGranularPermissions: false (binary only)
- supportsTemperature: false
- Model ID mapping (claude-sonnet-4 <-> claude-sonnet-4-20250514)
- Tool access mapping (OAC ToolAccess <-> Claude tools array)

Subtask: compatibility-layer-141-07
Phase: 2 (Adapters Migration)

* feat: implement CursorAdapter with single-file format support (Issue #141)

- Implement CursorAdapter extending BaseAdapter
- Support toOAC() conversion from .cursorrules to OAC
- Support fromOAC() conversion from OAC to .cursorrules format
- Handle single-file limitation (no multiple agents)
- Implement mergeAgents() for combining multiple OAC agents
- Parse optional YAML frontmatter in .cursorrules
- Inline context files into .cursorrules content
- Add comprehensive warnings for lost features

Key limitations:
- supportsMultipleAgents: false (single .cursorrules file)
- supportsSkills: false (must inline content)
- supportsHooks: false (not supported by Cursor)
- supportsGranularPermissions: false (binary only)
- supportsTemperature: true (limited support)

Features:
- Model ID mapping (gpt-4, claude-3-opus, etc.)
- Tool access parsing and generation
- Context file inlining with references
- Multi-agent merge capability
- Frontmatter parsing for metadata

Export CursorAdapter from main index.ts

Subtask: compatibility-layer-141-08
Phase: 2 (Adapters Migration)

* feat: implement WindsurfAdapter with bidirectional conversion (Issue #141)

- Add WindsurfAdapter.ts (514 lines) extending BaseAdapter
- Support bidirectional OAC ↔ Windsurf JSON conversion
- Implement toOAC() for Windsurf config → OpenAgent parsing
- Implement fromOAC() for OpenAgent → Windsurf config generation
- Add temperature ↔ creativity setting mapping (low/medium/high)
- Add model ID mapping (claude-sonnet-4 ↔ claude-4-sonnet)
- Support multi-agent configuration via .windsurf/agents/
- Support context files via .windsurf/context/
- Implement binary permission mapping with degradation warnings
- Add priority level normalization (critical/high/medium/low → high/low)
- Export WindsurfAdapter in index.ts
- All adapters now complete: Claude, Cursor, Windsurf
- Compilation successful: 0 errors, 0 warnings

Phase 2 (Adapters): 50% complete (3/6 subtasks)
Total progress: 28.13% (9/32 subtasks)
Code stats: 3,333 lines TypeScript (Foundation + Adapters)

* docs: add compatibility layer context files and progress tracking (Issue #141)

- Add baseadapter-implementation.md with detailed adapter pattern and testing examples
- Add compatibility-layer-development.md with development workflow and best practices
- Add compatibility-layer-adapters.md lookup table with adapter specifications
- Add compatibility-layer-progress.md tracking Phase 1 completion and Phase 2 status
- Add compatibility-learnings.md documenting implementation learnings
- Update compatibility-layer.md with latest architecture insights

These context files support Phase 2 adapter unit testing and future adapter development.

* test: implement comprehensive unit tests for ClaudeAdapter (Issue #141 - Subtask 10)

Implemented 80 test cases covering:
- toOAC() parsing of config.json and agent.md (YAML frontmatter)
- fromOAC() conversion to config.json and agent.md formats
- Capabilities and feature validation
- Model, tool, skill, hook, and permission mapping
- Skill generation from contexts
- Edge cases and error handling
- Roundtrip conversion validation

Coverage achieved:
- 96.32% statements (target: 80%+) ✅
- 100% functions (target: 80%+) ✅
- 82.14% branches (target: 75%+) ✅

All test cases follow AAA pattern (Arrange-Act-Assert) and test standards
from .opencode/context/core/standards/test-coverage.md

* test: implement comprehensive unit tests for CursorAdapter (Issue #141 - Subtask 11)

Implemented 78 test cases covering:
- toOAC() parsing of plain .cursorrules and YAML frontmatter
- fromOAC() conversion to .cursorrules format
- Capabilities and feature validation
- Agent merging (CURSOR-SPECIFIC - unique feature)
- Model, tool mapping
- Context inlining
- Temperature and configuration handling
- Edge cases and error handling
- Roundtrip conversion validation

Coverage achieved:
- 98.55% statements (target: 80%+) ✅
- 100% functions (target: 80%+) ✅
- 89.65% branches (target: 75%+) ✅

Key test areas:
- Plain text .cursorrules parsing (no frontmatter)
- YAML frontmatter parsing with type coercion
- Agent merging (single, two, three+ agents)
- Tool union and temperature MAX behavior
- Context inlining with proper formatting
- Model mapping (Cursor ↔ OAC)

All test cases follow AAA pattern and test standards.

* test: implement comprehensive unit tests for WindsurfAdapter (Issue #141 - Subtask 12)

* feat: implement Phase 3 mappers and translation engine with tests (Issue #141)

- Add ToolMapper: maps tool names between OAC and Claude/Cursor/Windsurf
- Add PermissionMapper: translates granular to binary permissions
- Add ModelMapper: maps AI model IDs between platforms
- Add ContextMapper: maps context file paths between platforms
- Add CapabilityMatrix: feature compatibility analysis across platforms
- Add TranslationEngine: orchestrates all mappers for complete translation

Test coverage:
- ToolMapper: 100% statements, 100% branches
- PermissionMapper: 98% statements, 96% branches
- ModelMapper: 99% statements, 90% branches
- ContextMapper: 97% statements, 94% branches
- CapabilityMatrix: 99% statements, 96% branches
- TranslationEngine: 99% statements, 93% branches

Total: 485 tests passing (249 new tests added)

* docs: update Issue #141 context files to reflect Phase 3 completion

- Update progress from 28% to 59.4% (19/32 subtasks)
- Mark Phases 1-3 as complete (Foundation, Adapters, Mappers)
- Update code stats: 5,799 source lines, 6,322 test lines
- Add test coverage metrics: 485 tests, 97-100% on Phase 3
- Update structure with all implemented files
- Add executive summary for token-efficient context loading
- Document next steps: Phase 4 CLI implementation

* docs(context): harvest Claude Code docs and fix MVI compliance (Phase 1)

- Harvest external Claude Code documentation into context system:
  - hooks-system, agent-skills, subagents-system concepts
  - hook-events, skill-metadata, builtin-subagents lookups
  - Example files for hooks, skills, and subagents
  - Plugin architecture and migration guides

- Fix 6 critical MVI violations (files > 200 lines):
  - Split adding-agent.md → adding-agent-basics.md + adding-agent-testing.md
  - Split adding-skill.md → 3 files (basics, implementation, example)
  - Split task-delegation.md → 3 files (basics, specialists, caching)
  - Split external-libraries.md → 3 files (workflow, scenarios, faq)
  - Split design-assets.md → 4 files (images, icons, fonts, cdn)
  - Split navigation-design.md → 2 files (basics, templates)

- Update navigation files with new references
- Remove consumed source docs from to-be-consumed/

Total: 17 new files created, 6 large files replaced, 5 source docs consumed

* docs(context): MVI compliance Phase 2 - split large workflow and UI files

Split 3 large files into MVI-compliant modules (< 200 lines each):

- design-iteration.md (1058 lines) → 9 files:
  - design-iteration-overview.md (overview, when to use)
  - design-iteration-plan-file.md (mandatory plan template)
  - design-iteration-stage-layout.md (Stage 1)
  - design-iteration-stage-theme.md (Stage 2)
  - design-iteration-stage-animation.md (Stage 3)
  - design-iteration-stage-implementation.md (Stage 4)
  - design-iteration-visual-content.md (Image Specialist)
  - design-iteration-best-practices.md (quality, troubleshooting)
  - design-iteration-plan-iterations.md (managing iterations)

- animation-patterns.md (753 lines) → 6 files:
  - animation-basics.md (fundamentals, timing, easing)
  - animation-components.md (buttons, cards, modals)
  - animation-chat.md (message, typing animations)
  - animation-loading.md (skeleton, spinner, progress)
  - animation-forms.md (focus, validation, scroll)
  - animation-advanced.md (recipes, best practices)

- premium-dark-ui-quick-start.md (638 lines) → 4 files:
  - premium-dark-ui-colors.md (palette, typography, spacing)
  - premium-dark-ui-components.md (core building blocks)
  - premium-dark-ui-layouts.md (hero, features, CTA)
  - premium-dark-ui-advanced.md (animations, accessibility)

Updated navigation files with new references.

* feat(cli): implement CLI scaffolding with Commander.js (Issue #141 - Subtask 20)

- Add src/cli/index.ts: CLI entry point with convert, validate, migrate, info commands
- Add src/cli/types.ts: TypeScript type definitions for CLI options
- Add src/cli/utils.ts: Logging, spinner, and formatting utilities
- Add "type": "module" to package.json for ESM support
- Global options: --verbose, --quiet, --output-format (json|text)
- Commands are placeholders pending implementation in subtasks 21-24

* feat(cli): implement convert command with full format support (Issue #141 - Subtask 21)

- Add src/cli/commands/convert.ts: Complete convert command implementation
- Auto-detect input format from file path and content
- Support bidirectional conversion: OAC <-> Cursor/Claude/Windsurf
- Output to stdout by default, file with --output flag
- Display warnings for feature loss during conversion
- Enable registerBuiltInAdapters in AdapterRegistry
- Add public constructors to all adapters (CursorAdapter, ClaudeAdapter, WindsurfAdapter)
- Fix ESM imports: add .js extensions to all relative imports across codebase

All 485 tests passing.

* feat(cli): implement validate and info commands (Issue #141 - Subtasks 22, 24)

- validate: Checks agent compatibility with target format
  - Reports compatibility score (0-100%)
  - Lists preserved/degraded/lost features
  - Provides suggestions for unsupported features
  - Exit codes: 0=compatible, 1=partial, 2=incompatible
  - Supports --strict and --output-format json

- info: Displays tool capabilities and feature parity
  - Shows feature matrix for all platforms
  - Detailed view for single platform
  - Platform comparison with --compare
  - Documentation links
  - Supports --output-format json

* feat(cli): implement migrate command and add migration guides (Issue #141)

- Add migrate command for full project migration with batch conversion
- Support --dry-run, --force, and --out-dir options
- Generate migration reports with success/failure summaries
- Preserve directory structure in output

Documentation:
- Add 5 migration guides (cursor↔oac, claude↔oac, oac→windsurf)
- Add comprehensive feature-matrices.md with platform comparisons
- Document lossless vs lossy conversion impacts

Completes subtasks: 23, 26, 27, 28, 29, 30, 31

* test(cli): add comprehensive integration tests for all CLI commands (Issue #141)

- Add convert.test.ts with 23 tests for format conversions
- Add validate.test.ts with 21 tests for compatibility validation
- Add migrate.test.ts with 25 tests for batch migration
- Add info.test.ts with 30 tests for capability queries
- Add test fixtures for OAC, Cursor, and Claude formats
- Fix empty directory warning in migrate command

All 584 tests passing with full coverage of CLI modules.

Completes subtask 25

* docs: update README with comprehensive CLI and API documentation (Issue #141)

- Add complete CLI command reference with all options
- Add programmatic API usage examples
- Add feature parity matrix summary
- Add links to all migration guides
- Add architecture overview
- Add custom adapter creation guide

Completes subtask 32 - Feature #141 fully implemented

* docs: add visual examples and format improvements to README

- Add Cursor IDE screenshot (contextscout-cursor.png)
- Add Claude Code validation screenshot (claude-code-validation.png)
- Format code examples with consistent double quotes
- Align feature parity matrix table
- Add .cursorrules and bun.lock to .gitignore

* fix(lint): resolve all ESLint errors in compatibility layer

- Remove async from methods with no await expressions (toOAC, fromOAC, loadFromFile)
- Wrap Promise-returning methods with Promise.resolve/reject
- Fix unsafe type assertions (replace 'as any' with proper type validation)
- Add missing getConfigPath() method to WindsurfAdapter
- Validate AgentCategory enum values before assignment
- Fix return type compatibility issues

All 584 tests passing, 0 ESLint errors (7 acceptable warnings for missing callback return types)

* chore: update package.json author and contributors metadata

- Update author from string to object format with name and GitHub URL
- Add Alexander Daza as contributor with email and GitHub profile
- Maintain npm package.json standard format for author/contributors fields
This commit is contained in:
Alexander Daza 2026-02-05 19:08:14 -05:00 committed by GitHub
parent 9c7f1c3099
commit ca2e35c30b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
146 changed files with 33248 additions and 7329 deletions

2
.gitignore vendored
View file

@ -207,3 +207,5 @@ tasks/
# Claude Code integration generated files # Claude Code integration generated files
integrations/claude-code/converter/generated/ integrations/claude-code/converter/generated/
.cursorrules
bun.lock

View file

@ -0,0 +1,131 @@
# Guide: Designing Navigation Files
**Purpose**: How to create token-efficient, scannable navigation files
---
## Prerequisites
- Understand MVI principle (`context-system/standards/mvi.md`)
- Know your category's organizational pattern
- Have content files already created
**Estimated time**: 15-20 min per navigation file
---
## Core Principles
### 1. Token Efficiency
**Goal**: 200-300 tokens per navigation file
**How**:
- Use ASCII trees (not verbose descriptions)
- Use tables (not paragraphs)
- Be concise (not comprehensive)
### 2. Scannable Structure
**Goal**: AI can find what it needs in <5 seconds
**Format**:
1. **Structure** (ASCII tree) - See what exists
2. **Quick Routes** (table) - Jump to common tasks
3. **By Concern/Type** (sections) - Browse by category
### 3. Self-Contained
**Include**: ✅ Paths | ✅ Brief descriptions (3-5 words) | ✅ When to use
**Exclude**: ❌ File contents | ❌ Detailed explanations | ❌ Duplicates
---
## Steps
### 1. Determine Navigation Type
| Type | Path | Purpose |
|------|------|---------|
| Category-level | `{category}/navigation.md` | Overview of category |
| Subcategory-level | `{category}/{sub}/navigation.md` | Files in subcategory |
| Specialized | `{category}/{domain}-navigation.md` | Cross-cutting (e.g., ui-navigation.md) |
### 2. Create Structure Section
```markdown
## Structure
```
openagents-repo/
├── navigation.md
├── quick-start.md
├── concepts/
│ └── subagent-testing-modes.md
├── guides/
│ ├── adding-agent.md
│ └── testing-agent.md
└── lookup/
└── commands.md
```
```
**Token count**: ~50-100 tokens
### 3. Create Quick Routes Table
```markdown
## Quick Routes
| Task | Path |
|------|------|
| **Add agent** | `guides/adding-agent.md` |
| **Test agent** | `guides/testing-agent.md` |
| **Find files** | `lookup/file-locations.md` |
```
**Guidelines**: Use **bold** for tasks | Relative paths | 5-10 common tasks
### 4. Create By Concern/Type Sections
```markdown
## By Type
**Concepts** → Core ideas and principles
**Guides** → Step-by-step workflows
**Lookup** → Quick reference tables
**Errors** → Troubleshooting
```
### 5. Add Related Context (Optional)
```markdown
## Related Context
- **Core Standards** → `../core/standards/navigation.md`
```
### 6. Validate Token Count
**Target**: 200-300 tokens
```bash
wc -w navigation.md # Multiply by 1.3 for token estimate
```
---
## Verification Checklist
- [ ] Token count 200-300?
- [ ] ASCII tree included?
- [ ] Quick routes table?
- [ ] By concern/type section?
- [ ] Relative paths?
- [ ] Descriptions 3-5 words?
- [ ] No duplicate information?
---
## Related
- `navigation-templates.md` - Ready-to-use templates
- `../standards/mvi.md` - MVI principle
- `../examples/navigation-examples.md` - More examples

View file

@ -1,431 +0,0 @@
# Guide: Designing Navigation Files
**Purpose**: How to create token-efficient, scannable navigation files
**Last Updated**: 2026-01-08
---
## Prerequisites
- Understand MVI principle (context-system/standards/mvi.md)
- Know your category's organizational pattern (function-based or concern-based)
- Have content files already created
**Estimated time**: 15-20 min per navigation file
---
## Core Principles
### 1. Token Efficiency
**Goal**: 200-300 tokens per navigation file
**Why**:
- Faster AI loading
- Lower costs
- Quicker decision-making
**How**:
- Use ASCII trees (not verbose descriptions)
- Use tables (not paragraphs)
- Be concise (not comprehensive)
---
### 2. Scannable Structure
**Goal**: AI can find what it needs in <5 seconds
**Format**:
1. **Structure** (ASCII tree) - See what exists
2. **Quick Routes** (table) - Jump to common tasks
3. **By Concern/Type** (sections) - Browse by category
---
### 3. Self-Contained
**Goal**: Navigation file answers "where do I go?"
**Include**:
- ✅ Paths to files
- ✅ Brief descriptions (3-5 words)
- ✅ When to use each file
**Exclude**:
- ❌ File contents (that's what the files are for)
- ❌ Detailed explanations
- ❌ Duplicate information
---
## Steps
### 1. Determine Navigation Type
**Category-level navigation** (`{category}/navigation.md`):
- Overview of entire category
- Points to subcategories
- Includes specialized navigation files
**Subcategory-level navigation** (`{category}/{subcategory}/navigation.md`):
- Overview of subcategory
- Lists files in this subcategory
- Points to related categories
**Specialized navigation** (`{category}/{domain}-navigation.md`):
- Cross-cutting concern (e.g., `ui-navigation.md`)
- Spans multiple subcategories
- Task-focused routes
---
### 2. Create Structure Section
**Format**: ASCII tree showing directory structure
**Example** (Function-based):
```markdown
## Structure
```
openagents-repo/
├── navigation.md
├── quick-start.md
│
├── concepts/
│ ├── navigation.md
│ └── subagent-testing-modes.md
│
├── guides/
│ ├── navigation.md
│ ├── adding-agent.md
│ └── testing-agent.md
│
└── lookup/
├── navigation.md
└── commands.md
```
```
**Example** (Concern-based):
```markdown
## Structure
```
development/
├── navigation.md
├── ui-navigation.md # Specialized
│
├── principles/
│ ├── clean-code.md
│ └── api-design.md
│
├── frontend/
│ ├── react/
│ │ ├── hooks-patterns.md
│ │ └── tanstack/
│ │ └── query-patterns.md
│ └── vue/
│
└── backend/
├── api-patterns/
│ ├── rest-design.md
│ └── graphql-design.md
└── nodejs/
```
```
**Token count**: ~50-100 tokens
---
### 3. Create Quick Routes Table
**Format**: Task → Path mapping
**Example**:
```markdown
## Quick Routes
| Task | Path |
|------|------|
| **Add agent** | `guides/adding-agent.md` |
| **Test agent** | `guides/testing-agent.md` |
| **Debug issue** | `guides/debugging-issues.md` |
| **Find files** | `lookup/file-locations.md` |
```
**Guidelines**:
- Use **bold** for task names
- Use relative paths
- 5-10 most common tasks
- Order by frequency of use
**Token count**: ~50-100 tokens
---
### 4. Create By Concern/Type Sections
**Format**: Group files by concern or type
**Example** (Function-based):
```markdown
## By Type
**Concepts** → Core ideas and principles
**Guides** → Step-by-step workflows
**Lookup** → Quick reference tables
**Errors** → Troubleshooting
```
**Example** (Concern-based):
```markdown
## By Concern
**Principles** → Universal development practices
**Frontend** → React, Vue, state management
**Backend** → APIs, Node.js, Python, auth
**Data** → SQL, NoSQL, ORMs
```
**Token count**: ~50-100 tokens
---
### 5. Add Related Context (Optional)
**Format**: Links to related categories
**Example**:
```markdown
## Related Context
- **Core Standards** → `../core/standards/navigation.md`
- **UI Patterns** → `../ui/navigation.md`
```
**Token count**: ~20-50 tokens
---
### 6. Validate Token Count
**Target**: 200-300 tokens
**Check**:
```bash
# Count tokens (rough estimate: words * 1.3)
wc -w navigation.md
# Multiply by 1.3 for token estimate
```
**If over 300 tokens**:
- Remove verbose descriptions
- Shorten table entries
- Remove less-used routes
---
## Templates
### Category Navigation Template
```markdown
# {Category} Navigation
**Purpose**: [1 sentence]
---
## Structure
```
{category}/
├── navigation.md
├── {subcategory}/
│ ├── navigation.md
│ └── {files}.md
```
---
## Quick Routes
| Task | Path |
|------|------|
| **{Task 1}** | `{path}` |
| **{Task 2}** | `{path}` |
| **{Task 3}** | `{path}` |
---
## By {Concern/Type}
**{Section 1}** → {description}
**{Section 2}** → {description}
**{Section 3}** → {description}
---
## Related Context
- **{Category}** → `../{category}/navigation.md`
```
**Token count**: ~200-250 tokens
---
### Specialized Navigation Template
```markdown
# {Domain} Navigation
**Scope**: [What this covers]
---
## Structure
```
{Relevant directories across multiple categories}
```
---
## Quick Routes
| Task | Path |
|------|------|
| **{Task 1}** | `{path}` |
| **{Task 2}** | `{path}` |
---
## By {Framework/Approach}
**{Tech 1}** → `{path}`
**{Tech 2}** → `{path}`
---
## Common Workflows
**{Workflow 1}**:
1. `{file1}` ({purpose})
2. `{file2}` ({purpose})
```
**Token count**: ~250-300 tokens
---
## Examples
### Good Navigation (Token-Efficient)
```markdown
# Development Navigation
**Purpose**: Software development across all stacks
---
## Structure
```
development/
├── navigation.md
├── ui-navigation.md
├── principles/
├── frontend/
├── backend/
└── data/
```
---
## Quick Routes
| Task | Path |
|------|------|
| **UI/Frontend** | `ui-navigation.md` |
| **Backend/API** | `backend-navigation.md` |
| **Clean code** | `principles/clean-code.md` |
---
## By Concern
**Principles** → Universal practices
**Frontend** → React, Vue, state
**Backend** → APIs, Node, auth
**Data** → SQL, NoSQL, ORMs
```
**Token count**: ~180 tokens ✅
---
### Bad Navigation (Too Verbose)
```markdown
# Development Navigation
**Purpose**: This navigation file helps you find software development patterns, standards, and best practices across all technology stacks including frontend, backend, databases, and infrastructure.
---
## Introduction
The development category contains comprehensive guides and patterns for building modern applications. Whether you're working on frontend user interfaces, backend APIs, database integrations, or infrastructure setup, you'll find relevant context here.
---
## Directory Structure
The development category is organized into several subcategories:
- **principles/** - This directory contains universal development principles that apply regardless of the technology stack you're using. Files include clean code practices, API design principles, and more.
- **frontend/** - This directory contains frontend development patterns including React, Vue, and state management solutions.
[... continues for 500+ tokens]
```
**Token count**: 500+ tokens ❌
---
## Verification
After creating navigation file:
- [ ] Token count 200-300?
- [ ] ASCII tree included?
- [ ] Quick routes table included?
- [ ] By concern/type section included?
- [ ] Paths are relative?
- [ ] Descriptions are 3-5 words?
- [ ] No duplicate information?
- [ ] Links to related context?
---
## Troubleshooting
| Issue | Solution |
|-------|----------|
| Too many tokens | Remove verbose descriptions, shorten table entries |
| Hard to scan | Use tables instead of paragraphs |
| Missing files | Add to structure section and quick routes |
| Unclear paths | Use relative paths, add brief descriptions |
---
## Related
- `../standards/mvi.md` - Minimal Viable Information principle
- `organizing-context.md` - How to choose organizational pattern
- `../examples/navigation-examples.md` - More examples

View file

@ -0,0 +1,183 @@
# Navigation File Templates
**Purpose**: Ready-to-use templates for navigation files
---
## Category Navigation Template
```markdown
# {Category} Navigation
**Purpose**: [1 sentence]
---
## Structure
```
{category}/
├── navigation.md
├── {subcategory}/
│ ├── navigation.md
│ └── {files}.md
```
---
## Quick Routes
| Task | Path |
|------|------|
| **{Task 1}** | `{path}` |
| **{Task 2}** | `{path}` |
| **{Task 3}** | `{path}` |
---
## By {Concern/Type}
**{Section 1}** → {description}
**{Section 2}** → {description}
**{Section 3}** → {description}
---
## Related Context
- **{Category}** → `../{category}/navigation.md`
```
**Token count**: ~200-250 tokens
---
## Specialized Navigation Template
```markdown
# {Domain} Navigation
**Scope**: [What this covers]
---
## Structure
```
{Relevant directories across multiple categories}
```
---
## Quick Routes
| Task | Path |
|------|------|
| **{Task 1}** | `{path}` |
| **{Task 2}** | `{path}` |
---
## By {Framework/Approach}
**{Tech 1}** → `{path}`
**{Tech 2}** → `{path}`
---
## Common Workflows
**{Workflow 1}**:
1. `{file1}` ({purpose})
2. `{file2}` ({purpose})
```
**Token count**: ~250-300 tokens
---
## Good Example (Token-Efficient)
```markdown
# Development Navigation
**Purpose**: Software development across all stacks
---
## Structure
```
development/
├── navigation.md
├── ui-navigation.md
├── principles/
├── frontend/
├── backend/
└── data/
```
---
## Quick Routes
| Task | Path |
|------|------|
| **UI/Frontend** | `ui-navigation.md` |
| **Backend/API** | `backend-navigation.md` |
| **Clean code** | `principles/clean-code.md` |
---
## By Concern
**Principles** → Universal practices
**Frontend** → React, Vue, state
**Backend** → APIs, Node, auth
**Data** → SQL, NoSQL, ORMs
```
**Token count**: ~180 tokens ✅
---
## Bad Example (Too Verbose)
```markdown
# Development Navigation
**Purpose**: This navigation file helps you find software development
patterns, standards, and best practices across all technology stacks
including frontend, backend, databases, and infrastructure.
---
## Introduction
The development category contains comprehensive guides and patterns
for building modern applications. Whether you're working on frontend
user interfaces, backend APIs, database integrations...
[... continues for 500+ tokens]
```
**Token count**: 500+ tokens ❌
---
## Troubleshooting
| Issue | Solution |
|-------|----------|
| Too many tokens | Remove verbose descriptions, shorten entries |
| Hard to scan | Use tables instead of paragraphs |
| Missing files | Add to structure and quick routes |
| Unclear paths | Use relative paths, add brief descriptions |
---
## Related
- `navigation-design-basics.md` - Core principles and steps
- `../standards/mvi.md` - MVI principle
- `../examples/navigation-examples.md` - More examples

View file

@ -0,0 +1,320 @@
# Guide: Resuming Multi-Session Tasks
**Purpose**: How to resume work from previous sessions using session context and task files
**Last Updated**: 2026-02-04
---
## When to Use This Guide
- Continuing work after a break or interruption
- Picking up a task from another agent or developer
- Understanding what was done in a previous session
- Avoiding duplicate work or lost progress
---
## Session File Structure
```
.tmp/
├── sessions/ # Session context
│ └── {YYYY-MM-DD}-{task-slug}/
│ ├── context.md # Full task context
│ └── PROGRESS.md # Progress report
│
└── tasks/ # Task breakdowns
└── {task-slug}/
├── task.json # Main task definition
└── subtask_NN.json # Individual subtasks
```
---
## Quick Resume Steps
### 1. Find Your Session (30 seconds)
```bash
# List recent sessions
ls -lt .tmp/sessions/ | head -5
# Most recent session
SESSION=$(ls -t .tmp/sessions/ | head -1)
echo "Latest session: $SESSION"
```
---
### 2. Read Progress Report (2 minutes)
```bash
# View progress
cat .tmp/sessions/$SESSION/PROGRESS.md
```
**Look for**:
- ✅ **Completed Work** - What's already done
- 🔥 **Next Steps** - What to do next
- 📊 **Overall Progress** - How much is complete
- ⚠️ **Blockers** - Any issues to resolve
---
### 3. Check Task Context (3 minutes)
```bash
# View full context
cat .tmp/sessions/$SESSION/context.md
```
**Key sections**:
- **Current Request** - What was asked for
- **Context Files** - Standards to follow (CRITICAL)
- **Reference Files** - Existing code to read
- **Components** - What needs to be built
- **Exit Criteria** - When you're done
---
### 4. Review Subtasks (2 minutes)
```bash
# Find task directory
TASK_DIR=.tmp/tasks/$(basename $SESSION | cut -d'-' -f4-)
# List subtasks
ls $TASK_DIR/subtask_*.json
# View next subtask
cat $TASK_DIR/subtask_04.json # Example
```
**Subtask format**:
```json
{
"id": "04",
"name": "Migrate AgentLoader",
"description": "Create src/core/AgentLoader.ts with load/parse functions",
"estimated_hours": 1.5,
"status": "pending",
"dependencies": ["02"],
"context_files": ["...standards to load..."],
"acceptance_criteria": ["...checklist..."]
}
```
---
## Resume Workflow
### Option 1: Continue from Last Checkpoint
```bash
# 1. Check what's done
grep "✅" .tmp/sessions/$SESSION/PROGRESS.md
# 2. Find next task
grep "🔥 NEXT" .tmp/sessions/$SESSION/PROGRESS.md
# 3. Tell the agent
"Continue with subtask 04 from session $SESSION"
```
---
### Option 2: Jump to Specific Phase
```bash
# 1. View phase structure
cat .tmp/tasks/$TASK_DIR/task.json | jq '.phases'
# 2. Find phase tasks
cat .tmp/tasks/$TASK_DIR/task.json | jq '.phases[1]' # Phase 2
# 3. Tell the agent
"Start Phase 2 - Adapters from session $SESSION"
```
---
### Option 3: Review and Decide
```bash
# 1. Quick status
cat .tmp/sessions/$SESSION/PROGRESS.md | grep -A5 "Overall Progress"
# 2. View completed work
cat .tmp/sessions/$SESSION/PROGRESS.md | grep -A20 "Completed Work"
# 3. Discuss with agent
"Show me the current status of session $SESSION and suggest next steps"
```
---
## Key Files to Read
### context.md (ALWAYS)
**Why**: Contains standards you MUST follow
```markdown
## Context Files (Standards to Follow)
- .opencode/context/core/standards/code-quality.md - CRITICAL
- .opencode/context/core/standards/test-coverage.md - CRITICAL
```
**Before writing any code**, load these standards!
---
### PROGRESS.md (RECOMMENDED)
**Why**: Shows exactly what's done and what's next
**Key sections**:
- **Overall Progress** - % complete, phases
- **Completed Work** - Files created, tasks done
- **Next Steps** - What to do immediately
- **Blockers** - Issues to resolve
---
### subtask_NN.json (WHEN NEEDED)
**Why**: Detailed task definition with acceptance criteria
**Use when**:
- Starting a new subtask
- Need to know exact requirements
- Want to see dependencies
---
## Common Scenarios
### Scenario 1: "I don't remember where I was"
```bash
# Quick catch-up
cat .tmp/sessions/$SESSION/PROGRESS.md | head -50
# Read: Overall Progress + Completed Work + Next Steps
```
**Time**: 2 minutes
---
### Scenario 2: "What was I supposed to build?"
```bash
# Read original request
cat .tmp/sessions/$SESSION/context.md | grep -A20 "Current Request"
# Read components
cat .tmp/sessions/$SESSION/context.md | grep -A30 "Components"
```
**Time**: 3 minutes
---
### Scenario 3: "What standards should I follow?"
```bash
# Read context files list
cat .tmp/sessions/$SESSION/context.md | grep -A15 "Context Files"
# Load the standards
cat .opencode/context/core/standards/code-quality.md
```
**Time**: 5 minutes
---
### Scenario 4: "How do I know when I'm done?"
```bash
# Read exit criteria
cat .tmp/sessions/$SESSION/context.md | grep -A20 "Exit Criteria"
```
**Time**: 1 minute
---
## Agent Instructions
When resuming a session, tell the agent:
```
"Resume session: {SESSION_ID}"
```
Or more specific:
```
"Continue with subtask 04 from session 2026-02-04-compatibility-layer-141"
```
The agent should:
1. ✅ Read context.md for standards
2. ✅ Read PROGRESS.md for current state
3. ✅ Load next subtask JSON
4. ✅ Load required context files (from subtask.context_files)
5. ✅ Propose next steps
6. ✅ Request approval before executing
---
## Session Lifecycle
### Active Session
- Created when task starts
- Updated after each subtask completes
- Contains live progress tracking
### Completed Session
- All subtasks marked complete
- Exit criteria met
- Ready for archival
### Archived Session
- Moved to `.tmp/archive/sessions/{date}/`
- Knowledge harvested to permanent context
- Task JSONs can be deleted
---
## Cleanup Checklist
After completing a session:
- [ ] All exit criteria met?
- [ ] Valuable knowledge harvested to context?
- [ ] Session files archived?
- [ ] Task JSONs cleaned up?
- [ ] Temporary files deleted?
---
## Best Practices
1. **Always read context.md first** - Contains critical standards
2. **Check PROGRESS.md before asking** - Likely has the answer
3. **Use subtask JSONs for detailed requirements** - Not just memory
4. **Update PROGRESS.md after each task** - Keep it current
5. **Archive when done** - Don't clutter workspace
---
## Reference
- **Session Template**: `.tmp/sessions/{YYYY-MM-DD}-{task-slug}/`
- **Task Template**: `.tmp/tasks/{task-slug}/`
- **Related**:
- guides/compatibility-layer-workflow.md (example session)
- standards/code-quality.md (what to follow)

View file

@ -28,6 +28,9 @@ core/
│ ├── session-management.md │ ├── session-management.md
│ └── design-iteration.md │ └── design-iteration.md
│ │
├── guides/
│ └── resuming-sessions.md # NEW: Multi-session task resumption
│
├── task-management/ # JSON-driven task tracking ├── task-management/ # JSON-driven task tracking
│ ├── navigation.md │ ├── navigation.md
│ ├── standards/ │ ├── standards/
@ -61,6 +64,7 @@ core/
| **Review code** | `workflows/code-review.md` | | **Review code** | `workflows/code-review.md` |
| **Delegate task** | `workflows/task-delegation.md` | | **Delegate task** | `workflows/task-delegation.md` |
| **Break down feature** | `workflows/feature-breakdown.md` | | **Break down feature** | `workflows/feature-breakdown.md` |
| **Resume session** | `guides/resuming-sessions.md` |
| **Manage tasks** | `task-management/navigation.md` | | **Manage tasks** | `task-management/navigation.md` |
| **Task CLI commands** | `task-management/lookup/task-commands.md` | | **Task CLI commands** | `task-management/lookup/task-commands.md` |
| **Context system** | `context-system.md` | | **Context system** | `context-system.md` |

View file

@ -0,0 +1,179 @@
<!-- Context: workflows/design-iteration-best-practices | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
# Design Iteration Best Practices
## Iteration Process
### When to Create Iterations
**Create new iteration** (`{name}_1_1.html`) when:
- User requests changes to existing design
- Refining based on feedback
- A/B testing variations
- Progressive enhancement
**Create new design** (`{name}_2.html`) when:
- Complete redesign requested
- Different approach/style
- Alternative layout structure
### Iteration Workflow
```
User: "Can you make the buttons larger and change the color?"
1. Read current file: dashboard_1.html
2. Make requested changes
3. Save as: dashboard_1_1.html
4. Present changes to user
User: "Perfect! Now can we add a sidebar?"
1. Read current file: dashboard_1_1.html
2. Add sidebar component
3. Save as: dashboard_1_2.html
4. Present changes to user
```
---
## File Management
### Folder Structure
```
design_iterations/
├── theme_1.css
├── theme_2.css
├── landing_1.html
├── landing_1_1.html
├── landing_1_2.html
├── dashboard_1.html
├── dashboard_1_1.html
└── README.md (optional: design notes)
```
### Version Control
**Track iterations**:
- Initial: `design_1.html`
- Iteration 1: `design_1_1.html`
- Iteration 2: `design_1_2.html`
- Iteration 3: `design_1_3.html`
**New major version**:
- Complete redesign: `design_2.html`
- Then iterate: `design_2_1.html`, `design_2_2.html`
---
## Communication Patterns
### Stage Transitions
**After Layout**:
```
"Here's the proposed layout structure. The design uses a [description].
Would you like to proceed with this layout, or should we make adjustments?"
```
**After Theme**:
```
"I've created a [style] theme with [key features]. The theme file is saved as theme_N.css.
Does this match your vision, or would you like to adjust colors/typography?"
```
**After Animation**:
```
"Here's the animation plan using [timing/style]. All animations are optimized for performance.
Are these animations appropriate, or should we adjust the timing/effects?"
```
**After Implementation**:
```
"I've created the complete design as {filename}.html. The design includes [key features].
Please review and let me know if you'd like any changes or iterations."
```
### Iteration Requests
**User requests change**:
```
"I'll update the design with [changes] and save it as {filename}_N.html.
This preserves the previous version for reference."
```
---
## Quality Checklist
Before presenting each stage:
**Layout Stage**:
- [ ] ASCII wireframe is clear and detailed
- [ ] Components are well-organized
- [ ] Responsive behavior is planned
- [ ] User approval requested
**Theme Stage**:
- [ ] Theme file created and saved
- [ ] Colors use OKLCH format
- [ ] Fonts loaded from Google Fonts
- [ ] Contrast ratios meet WCAG AA
- [ ] User approval requested
**Animation Stage**:
- [ ] Animations documented in micro-syntax
- [ ] Timing is appropriate (< 400ms)
- [ ] Performance optimized (transform/opacity)
- [ ] Accessibility considered
- [ ] User approval requested
**Implementation Stage**:
- [ ] Single HTML file created
- [ ] Theme CSS referenced
- [ ] Tailwind loaded via script tag
- [ ] Icons initialized
- [ ] Responsive design tested
- [ ] Accessibility attributes added
- [ ] Images use valid placeholder URLs
- [ ] Semantic HTML used
- [ ] User review requested
---
## Troubleshooting
### Common Issues
**Issue**: User wants to skip stages
**Solution**: Explain benefits of structured approach, but accommodate if insisted
**Issue**: Theme doesn't match user vision
**Solution**: Iterate on theme file, create theme_2.css with adjustments
**Issue**: Animations feel too slow/fast
**Solution**: Adjust timing in micro-syntax, regenerate with new values
**Issue**: Design doesn't work on mobile
**Solution**: Review responsive breakpoints, add mobile-specific styles
**Issue**: Colors have poor contrast
**Solution**: Use WCAG contrast checker, adjust OKLCH lightness values
---
## References
- [Design Systems Context](../../ui/web/design-systems.md)
- [UI Styling Standards](../../ui/web/ui-styling-standards.md)
- [Animation Patterns](../../ui/web/animation-patterns.md)
- [ASCII Art Generator](https://www.asciiart.eu/)
- [WCAG Contrast Checker](https://webaim.org/resources/contrastchecker/)
---
## Related Files
- [Overview](./design-iteration-overview.md)
- [Stage 4: Implementation](./design-iteration-stage-implementation.md)
- [Plan Iterations](./design-iteration-plan-iterations.md)

View file

@ -0,0 +1,91 @@
<!-- Context: workflows/design-iteration-overview | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
# Design Iteration Workflow - Overview
## Overview
A structured 4-stage workflow for creating and iterating on UI designs. This process ensures thoughtful design decisions with user approval at each stage.
## Quick Reference
**Stages**: Layout → Theme → Animation → Implementation
**Approval**: Required between each stage
**Output**: Single HTML file per design iteration
**Location**: `design_iterations/` folder
---
## When to Use This Workflow
### Delegate to OpenFrontendSpecialist When:
**✅ STRONGLY RECOMMENDED** to delegate for:
- **New UI/UX design work** - Landing pages, dashboards, app interfaces
- **Design system creation** - Component libraries, theme systems, style guides
- **Complex layouts** - Multi-column grids, responsive designs, intricate structures
- **Visual polish** - Animations, transitions, micro-interactions
- **Brand-focused work** - Marketing pages, product showcases, hero sections
- **Accessibility-critical UI** - Forms, navigation, interactive components
**Why delegate?**
- OpenFrontendSpecialist follows the 4-stage design workflow (Layout → Theme → Animation → Implementation)
- Ensures thoughtful design decisions with approval gates
- Produces polished, accessible, production-ready UI
- Handles responsive design, OKLCH colors, semantic HTML
- Creates single-file HTML prototypes for quick iteration
### Execute Directly When:
**⚠️ Simple cases only**:
- Minor text/content updates to existing UI
- Small CSS tweaks (colors, spacing, fonts)
- Adding simple utility classes
- Updating existing component props
- Bug fixes in existing UI code
### Delegation Pattern
```javascript
// For UI design work
task(
subagent_type="OpenFrontendSpecialist",
description="Design {feature} UI",
prompt="Design a {feature} following the 4-stage workflow:
Requirements:
- {requirement 1}
- {requirement 2}
Context: {what this UI is for}
Follow the design iteration workflow:
1. Layout (ASCII wireframe)
2. Theme (design system, colors)
3. Animation (micro-interactions)
4. Implementation (single HTML file)
Request approval between each stage."
)
```
### Example Scenarios
| Scenario | Action | Why |
|----------|--------|-----|
| "Create a landing page for our SaaS product" | ✅ Delegate to OpenFrontendSpecialist | Complex UI design, needs 4-stage workflow |
| "Design a user dashboard with charts" | ✅ Delegate to OpenFrontendSpecialist | Complex layout, visual design, interactions |
| "Build a component library with our brand" | ✅ Delegate to OpenFrontendSpecialist | Design system work, requires theme expertise |
| "Fix button color from blue to green" | ⚠️ Execute directly | Simple CSS change |
| "Update hero text content" | ⚠️ Execute directly | Content update only |
---
## Related Files
- [Design Plan File](./design-iteration-plan-file.md) - MANDATORY plan file template
- [Stage 1: Layout](./design-iteration-stage-layout.md)
- [Stage 2: Theme](./design-iteration-stage-theme.md)
- [Stage 3: Animation](./design-iteration-stage-animation.md)
- [Stage 4: Implementation](./design-iteration-stage-implementation.md)
- [Visual Content Generation](./design-iteration-visual-content.md)
- [Best Practices](./design-iteration-best-practices.md)
- [Plan Iterations](./design-iteration-plan-iterations.md)

View file

@ -0,0 +1,182 @@
<!-- Context: workflows/design-iteration-plan-file | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
# Design Plan File (MANDATORY)
**CRITICAL**: Before starting any design work, create a persistent design plan file.
**Location**: `.tmp/design-plans/{project-name}-{feature-name}.md`
**Purpose**:
- Preserve design decisions across stages
- Allow user to review and edit the plan
- Maintain context for subagent calls
- Track design evolution and iterations
**When to Create**:
- BEFORE Stage 1 (Layout Design)
- After understanding user requirements
- Before any design work begins
## Template
```markdown
---
project: {project-name}
feature: {feature-name}
created: {ISO timestamp}
updated: {ISO timestamp}
status: in_progress
current_stage: layout
---
# Design Plan: {Feature Name}
## User Requirements
{What the user asked for - verbatim or close paraphrase}
## Design Goals
- {goal 1}
- {goal 2}
- {goal 3}
## Target Audience
{Who will use this UI}
## Technical Constraints
- Framework: {Next.js, React, etc.}
- Responsive: {Yes/No}
- Accessibility: {WCAG level}
- Browser support: {Modern, IE11+, etc.}
---
## Stage 1: Layout Design
### Status
- [ ] Layout planned
- [ ] ASCII wireframe created
- [ ] User approved
### Layout Structure
{ASCII wireframe will be added here}
### Component Breakdown
{Component list will be added here}
### User Feedback
{User comments and requested changes}
---
## Stage 2: Theme Design
### Status
- [ ] Design system selected
- [ ] Color palette chosen
- [ ] Typography defined
- [ ] User approved
### Theme Details
{Theme specifications will be added here}
### User Feedback
{User comments and requested changes}
---
## Stage 3: Animation Design
### Status
- [ ] Micro-interactions defined
- [ ] Animation timing set
- [ ] User approved
### Animation Details
{Animation specifications will be added here}
### User Feedback
{User comments and requested changes}
---
## Stage 4: Implementation
### Status
- [ ] HTML structure complete
- [ ] CSS applied
- [ ] Animations implemented
- [ ] User approved
### Output Files
- HTML: {file path}
- CSS: {file path}
- Assets: {file paths}
### User Feedback
{Final comments and requested changes}
---
## Design Evolution
### Iteration 1
- Date: {timestamp}
- Changes: {what changed}
- Reason: {why it changed}
### Iteration 2
- Date: {timestamp}
- Changes: {what changed}
- Reason: {why it changed}
```
## Workflow Integration
1. **Create plan file** → Write to `.tmp/design-plans/{name}.md`
2. **Each stage** → Update plan file with decisions and user feedback
3. **User approval** → Edit plan file with approved decisions
4. **User requests changes** → Edit plan file with feedback, iterate
5. **Subagent calls** → Pass plan file path for context preservation
6. **Completion** → Plan file contains full design history
## Benefits
- ✅ Context preserved across subagent calls
- ✅ User can review and edit plan directly
- ✅ Design decisions documented
- ✅ Easy to iterate and refine
- ✅ Full design history tracked
---
## Stage 0: Create Design Plan (MANDATORY FIRST STEP)
**Purpose**: Create persistent plan file before any design work
**Process**:
1. Understand user requirements
2. Identify design goals and constraints
3. Create plan file at `.tmp/design-plans/{project-name}-{feature-name}.md`
4. Populate with user requirements and goals
5. Present plan file location to user
6. Proceed to Stage 1
**Deliverable**: Design plan file created and initialized
**Example**:
```
✅ Design plan created: .tmp/design-plans/saas-landing-page.md
You can review and edit this file at any time. All design decisions will be tracked here.
Ready to proceed to Stage 1 (Layout Design)?
```
**Approval Gate**: "Plan file created. Ready to start layout design?"
---
## Related Files
- [Overview](./design-iteration-overview.md)
- [Stage 1: Layout](./design-iteration-stage-layout.md)
- [Plan Iterations](./design-iteration-plan-iterations.md)

View file

@ -0,0 +1,153 @@
<!-- Context: workflows/design-iteration-plan-iterations | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
# Handling Plan File Edits and Iterations
## User Edits Plan File Directly
**Scenario**: User opens `.tmp/design-plans/{name}.md` and makes changes
**Process**:
1. User edits plan file (changes requirements, adds constraints, modifies goals)
2. User notifies agent: "I've updated the plan file"
3. Agent reads updated plan file
4. Agent identifies what changed
5. Agent proposes how to incorporate changes
6. Agent updates affected stages
**Example**:
```
User: "I've updated the plan file - changed the color scheme to dark mode"
Agent:
✅ Read updated plan: .tmp/design-plans/saas-landing-page.md
Changes detected:
- Color scheme: Light → Dark mode
- Primary color: Blue → Purple
This affects:
- Stage 2 (Theme) - needs regeneration
- Stage 4 (Implementation) - needs CSS update
Would you like me to:
1. Regenerate theme with dark mode
2. Update implementation with new theme
```
---
## Iteration Within a Stage
**Scenario**: User requests changes during a stage
**Process**:
1. Agent presents stage output (e.g., layout wireframe)
2. User requests changes: "Make the hero section taller"
3. Agent updates plan file with feedback
4. Agent makes changes
5. Agent updates plan file with new iteration
6. Agent presents updated output
**Example**:
```
Stage 1 - Layout Design
Agent: [presents wireframe]
User: "Make the hero section taller and move CTA above the fold"
Agent:
✅ Updated plan file with feedback
✅ Revised layout wireframe
✅ Updated plan file with Iteration 2
[presents updated wireframe]
```
---
## Tracking Iterations in Plan File
**Format**:
```markdown
## Design Evolution
### Iteration 1 - Initial Layout
- Date: 2026-01-30T10:00:00Z
- Stage: Layout
- Changes: Initial wireframe created
- User feedback: "Hero section too short, CTA below fold"
### Iteration 2 - Revised Layout
- Date: 2026-01-30T10:15:00Z
- Stage: Layout
- Changes: Increased hero height from 400px to 600px, moved CTA above fold
- User feedback: "Perfect! Approved."
- Status: ✅ Approved
### Iteration 3 - Theme Adjustment
- Date: 2026-01-30T10:30:00Z
- Stage: Theme
- Changes: Changed from light to dark mode, primary color blue → purple
- User feedback: "Love the dark mode!"
- Status: ✅ Approved
```
---
## Subagent Context Preservation
**Problem**: Subagents lose context between calls
**Solution**: Always pass plan file path
**Pattern**:
```javascript
// When delegating to subagent
task(
subagent_type="OpenFrontendSpecialist",
description="Implement Stage 4",
prompt="Load design plan from .tmp/design-plans/saas-landing-page.md
Read the plan file for:
- All approved decisions from Stages 1-3
- User requirements and constraints
- Design evolution and iterations
Implement Stage 4 (Implementation) following all approved decisions.
Update the plan file with:
- Output file paths
- Implementation status
- Any issues encountered"
)
```
---
## Plan File as Single Source of Truth
### Benefits
- ✅ All design decisions in one place
- ✅ User can review and edit anytime
- ✅ Subagents have full context
- ✅ Design history preserved
- ✅ Easy to iterate and refine
- ✅ No context loss between stages
### Best Practices
- Always read plan file at start of each stage
- Update plan file after every user interaction
- Track all iterations with timestamps
- Document user feedback verbatim
- Mark approved decisions clearly
- Pass plan file path to all subagents
---
## Related Files
- [Overview](./design-iteration-overview.md)
- [Design Plan File](./design-iteration-plan-file.md)
- [Best Practices](./design-iteration-best-practices.md)

View file

@ -0,0 +1,80 @@
<!-- Context: workflows/design-iteration-stage-animation | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
# Stage 3: Animation Design
**Purpose**: Define micro-interactions and transitions
## Process
1. Read design plan file from `.tmp/design-plans/{name}.md`
2. Review approved theme from Stage 2
3. Identify key interactions (hover, click, scroll)
4. Define animation timing and easing
5. Plan loading states and transitions
6. Document animations using micro-syntax
7. **Update plan file** with animation specifications
8. Present animation plan to user for approval
9. **Update plan file** with user feedback and approval status
## Deliverable
- Animation specification in micro-syntax format
- Updated plan file with Stage 3 complete
## Example Output
```
## Animation Design: Smooth & Professional
### Button Interactions
hover: 200ms ease-out [Y0→-2, shadow↗]
press: 100ms ease-in [S1→0.95]
ripple: 400ms ease-out [S0→2, α1→0]
### Card Interactions
cardHover: 300ms ease-out [Y0→-4, shadow↗]
cardClick: 200ms ease-out [S1→1.02]
### Page Transitions
pageEnter: 300ms ease-out [α0→1, Y+20→0]
pageExit: 200ms ease-in [α1→0]
### Loading States
spinner: 1000ms ∞ linear [R360°]
skeleton: 2000ms ∞ [bg: muted↔accent]
### Micro-Interactions
inputFocus: 200ms ease-out [S1→1.01, ring]
linkHover: 250ms ease-out [underline 0→100%]
**Philosophy**: Subtle, purposeful animations that enhance UX without distraction
**Performance**: All animations use transform/opacity for 60fps
**Accessibility**: Respects prefers-reduced-motion
```
## Best Practices
✅ **Do**:
- Use micro-syntax for documentation
- Keep animations under 400ms
- Use transform/opacity for performance
- Respect prefers-reduced-motion
- Make animations purposeful
❌ **Don't**:
- Animate width/height (use scale)
- Create distracting animations
- Ignore performance implications
- Skip accessibility considerations
## Approval Gate
"Are these animations appropriate for your design, or should we adjust?"
---
## Related Files
- [Overview](./design-iteration-overview.md)
- [Stage 2: Theme](./design-iteration-stage-theme.md)
- [Stage 4: Implementation](./design-iteration-stage-implementation.md)
- [Animation Patterns](../../ui/web/animation-patterns.md)

View file

@ -0,0 +1,157 @@
<!-- Context: workflows/design-iteration-stage-implementation | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
# Stage 4: Implementation
**Purpose**: Generate complete HTML file with all components
## Process
1. Read design plan file from `.tmp/design-plans/{name}.md`
2. Review all approved decisions from Stages 1-3
3. Build individual UI components
4. Integrate theme CSS
5. Add animations and interactions
6. Combine into single HTML file
7. Test responsive behavior
8. Save to design_iterations folder
9. **Update plan file** with output file paths
10. Present to user for review
11. **Update plan file** with user feedback and final approval status
## Deliverable
- Complete HTML file with embedded or linked CSS
- Updated plan file with Stage 4 complete and all output files documented
## File Organization
```
design_iterations/
├── theme_1.css # Theme file from Stage 2
├── dashboard_1.html # Initial design
├── dashboard_1_1.html # First iteration
├── dashboard_1_2.html # Second iteration
├── chat_ui_1.html # Different design
└── chat_ui_1_1.html # Iteration of chat UI
```
## Naming Conventions
| Type | Format | Example |
|------|--------|---------|
| Initial design | `{name}_1.html` | `table_1.html` |
| First iteration | `{name}_1_1.html` | `table_1_1.html` |
| Second iteration | `{name}_1_2.html` | `table_1_2.html` |
| New design | `{name}_2.html` | `table_2.html` |
## Implementation Checklist
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Design Name</title>
<!-- ✅ Preconnect to external resources -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<!-- ✅ Load fonts -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<!-- ✅ Load Tailwind (script tag, not stylesheet) -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- ✅ Load Flowbite if needed -->
<link href="https://cdn.jsdelivr.net/npm/flowbite@2.0.0/dist/flowbite.min.css" rel="stylesheet">
<!-- ✅ Load icons -->
<script src="https://unpkg.com/lucide@latest/dist/umd/lucide.min.js"></script>
<!-- ✅ Link theme CSS -->
<link rel="stylesheet" href="theme_1.css">
<!-- ✅ Custom styles with !important for overrides -->
<style>
body {
font-family: 'Inter', sans-serif !important;
color: var(--foreground) !important;
}
h1, h2, h3, h4, h5, h6 {
font-weight: 600 !important;
}
/* Custom animations */
@keyframes fadeIn {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
.animate-fade-in {
animation: fadeIn 300ms ease-out;
}
</style>
</head>
<body>
<!-- ✅ Semantic HTML structure -->
<header>
<!-- Header content -->
</header>
<main>
<!-- Main content -->
</main>
<footer>
<!-- Footer content -->
</footer>
<!-- ✅ Load Flowbite JS if needed -->
<script src="https://cdn.jsdelivr.net/npm/flowbite@2.0.0/dist/flowbite.min.js"></script>
<!-- ✅ Initialize icons -->
<script>
lucide.createIcons();
</script>
<!-- ✅ Custom JavaScript -->
<script>
// Interactive functionality
</script>
</body>
</html>
```
## Best Practices
✅ **Do**:
- Use single HTML file per design
- Load Tailwind via script tag
- Reference theme CSS file
- Use !important for framework overrides
- Test responsive behavior
- Provide alt text for images
- Use semantic HTML
❌ **Don't**:
- Split into multiple files
- Load Tailwind as stylesheet
- Inline all styles
- Skip accessibility attributes
- Use made-up image URLs
- Use div soup (non-semantic HTML)
## Approval Gate
"Please review the design. Would you like any changes or iterations?"
---
## Related Files
- [Overview](./design-iteration-overview.md)
- [Stage 3: Animation](./design-iteration-stage-animation.md)
- [Best Practices](./design-iteration-best-practices.md)
- [Iteration Process](./design-iteration-plan-iterations.md)

View file

@ -0,0 +1,115 @@
<!-- Context: workflows/design-iteration-stage-layout | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
# Stage 1: Layout Design
**Purpose**: Define the structure and component hierarchy before visual design
## Process
1. Read design plan file from `.tmp/design-plans/{name}.md`
2. Analyze user requirements from plan
3. Identify core UI components
4. Plan layout structure and responsive behavior
5. Create ASCII wireframe
6. **Update plan file** with layout structure and component breakdown
7. Present to user for approval
8. **Update plan file** with user feedback and approval status
## Deliverable
- ASCII wireframe with component breakdown
- Updated plan file with Stage 1 complete
## Example Output
```
## Core UI Components
**Header Area**
- Logo/brand (Top left)
- Navigation menu (Top center)
- User actions (Top right)
**Main Content Area**
- Hero section (Full width)
- Feature cards (3-column grid on desktop, stack on mobile)
- Call-to-action (Centered)
**Footer**
- Links (4-column grid)
- Social icons (Centered)
- Copyright (Bottom)
## Layout Structure
Desktop (1024px+):
┌─────────────────────────────────────────────────┐
│ [Logo] Navigation [User Menu] │
├─────────────────────────────────────────────────┤
│ │
│ HERO SECTION │
│ (Full width, centered text) │
│ │
├─────────────────────────────────────────────────┤
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ Card 1 │ │ Card 2 │ │ Card 3 │ │
│ │ │ │ │ │ │ │
│ └─────────┘ └─────────┘ └─────────┘ │
├─────────────────────────────────────────────────┤
│ [Call to Action] │
├─────────────────────────────────────────────────┤
│ Links Links Links Social │
│ Copyright │
└─────────────────────────────────────────────────┘
Mobile (< 768px):
┌─────────────────┐
│ ☰ Logo [👤] │
├─────────────────┤
│ │
│ HERO SECTION │
│ │
├─────────────────┤
│ ┌───────────┐ │
│ │ Card 1 │ │
│ └───────────┘ │
│ ┌───────────┐ │
│ │ Card 2 │ │
│ └───────────┘ │
│ ┌───────────┐ │
│ │ Card 3 │ │
│ └───────────┘ │
├─────────────────┤
│ [CTA] │
├─────────────────┤
│ Links │
│ Social │
│ Copyright │
└─────────────────┘
```
## Best Practices
✅ **Do**:
- Use ASCII wireframes for clarity
- Break down into component hierarchy
- Plan responsive behavior upfront
- Consider mobile-first approach
- Get approval before proceeding
❌ **Don't**:
- Skip wireframing and jump to code
- Ignore responsive considerations
- Proceed without user approval
- Over-complicate initial layout
## Approval Gate
"Would you like to proceed with this layout or need modifications?"
---
## Related Files
- [Overview](./design-iteration-overview.md)
- [Design Plan File](./design-iteration-plan-file.md)
- [Stage 2: Theme](./design-iteration-stage-theme.md)

View file

@ -0,0 +1,84 @@
<!-- Context: workflows/design-iteration-stage-theme | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
# Stage 2: Theme Design
**Purpose**: Define colors, typography, spacing, and visual style
## Process
1. Read design plan file from `.tmp/design-plans/{name}.md`
2. Review approved layout from Stage 1
3. Choose design system (neo-brutalism, modern dark, custom)
4. Select color palette (avoid Bootstrap blue unless requested)
5. Choose typography (Google Fonts)
6. Define spacing and shadows
7. Generate theme CSS file
8. **Update plan file** with theme specifications
9. Present theme to user for approval
10. **Update plan file** with user feedback and approval status
## Deliverable
- CSS theme file saved to `design_iterations/theme_N.css`
- Updated plan file with Stage 2 complete
## Theme Selection Criteria
| Style | Use When | Avoid When |
|-------|----------|------------|
| Neo-Brutalism | Creative/artistic projects, retro aesthetic | Enterprise apps, accessibility-critical |
| Modern Dark | SaaS, developer tools, professional dashboards | Playful consumer apps |
| Custom | Specific brand requirements | Time-constrained projects |
## Example Output
```
## Theme Design: Modern Professional
**Style Reference**: Vercel/Linear aesthetic
**Color Palette**: Monochromatic with accent
**Typography**: Inter (UI) + JetBrains Mono (code)
**Spacing**: 4px base unit
**Shadows**: Subtle, soft elevation
**Theme File**: design_iterations/theme_1.css
Key Design Decisions:
- Primary: Neutral gray for professional feel
- Accent: Subtle blue for interactive elements
- Radius: 0.625rem for modern, friendly feel
- Shadows: Soft, minimal elevation
- Fonts: System-like for familiarity
```
## File Naming
`theme_1.css`, `theme_2.css`, etc.
## Best Practices
✅ **Do**:
- Reference design system context files
- Use CSS custom properties
- Save theme to separate file
- Consider accessibility (contrast ratios)
- Avoid Bootstrap blue unless requested
❌ **Don't**:
- Hardcode colors in HTML
- Use generic/overused color schemes
- Skip contrast testing
- Mix color formats (stick to OKLCH)
## Approval Gate
"Does this theme match your vision, or would you like adjustments?"
---
## Related Files
- [Overview](./design-iteration-overview.md)
- [Stage 1: Layout](./design-iteration-stage-layout.md)
- [Stage 3: Animation](./design-iteration-stage-animation.md)
- [Design Systems Context](../../ui/web/design-systems.md)
- [UI Styling Standards](../../ui/web/ui-styling-standards.md)

View file

@ -0,0 +1,110 @@
<!-- Context: workflows/design-iteration-visual-content | Priority: medium | Version: 1.0 | Updated: 2025-12-09 -->
# Visual Content Generation
## When to Use Image Specialist
Delegate to **Image Specialist** subagent when users request:
- **Diagrams & Visualizations**: Architecture diagrams, flowcharts, system visualizations
- **UI Mockups & Wireframes**: Visual mockups, design concepts, interface previews
- **Graphics & Assets**: Social media graphics, promotional images, icons, illustrations
- **Image Editing**: Photo enhancement, image modifications, visual adjustments
## Invocation Pattern
```javascript
task(
subagent_type="Image Specialist",
description="Generate/edit visual content",
prompt="Context to load:
- .opencode/context/core/visual-development.md
Task: [Specific visual requirement]
Requirements:
- [Visual style/aesthetic]
- [Dimensions/format]
- [Key elements to include]
- [Color scheme/branding]
Output: [Expected deliverable]"
)
```
## Example Use Cases
### Architecture Diagram
```javascript
task(
subagent_type="Image Specialist",
description="Generate microservices architecture diagram",
prompt="Create a diagram showing:
- 5 microservices (API Gateway, Auth, Orders, Payments, Notifications)
- Database connections
- Message queue (RabbitMQ)
- External services (Stripe, SendGrid)
Style: Clean, professional, modern
Format: PNG, 1920x1080"
)
```
### UI Mockup
```javascript
task(
subagent_type="Image Specialist",
description="Generate dashboard mockup",
prompt="Create a mockup for an analytics dashboard:
- Header with navigation
- 4 metric cards (Users, Revenue, Conversion, Retention)
- Line chart showing trends
- Data table below
Style: Modern, dark theme, professional
Format: PNG, 1440x900"
)
```
### Social Media Graphic
```javascript
task(
subagent_type="Image Specialist",
description="Generate product launch graphic",
prompt="Create a social media graphic announcing new feature:
- Bold headline: 'Introducing Real-Time Collaboration'
- Subtext: 'Work together, ship faster'
- Brand colors: #6366f1 (primary), #1e293b (dark)
- Include abstract collaboration visual
Format: PNG, 1200x630 (Twitter/LinkedIn)"
)
```
## Tools Required
- **tool:gemini** - Gemini Nano Banana AI for image generation/editing
- Automatically available in Developer profile
## When NOT to Delegate
**Use design-iteration workflow instead** when:
- Creating interactive HTML/CSS designs
- Building complete UI implementations
- Iterating on existing HTML files
- Need responsive, production-ready code
**Use image-specialist** when:
- Need static visual assets
- Creating diagrams or illustrations
- Generating mockups for presentation
- Quick visual concepts without code
---
## Related Files
- [Overview](./design-iteration-overview.md)
- [Visual Development](../visual-development.md)

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,165 @@
<!-- Context: workflows/external-libraries-faq | Priority: medium | Version: 1.0 | Updated: 2026-02-05 -->
# External Libraries: FAQ
**Purpose**: Troubleshooting and common questions about ExternalScout
---
## When exactly should I use ExternalScout?
**ALWAYS when working with external packages.**
**Triggers:**
- User mentions library
- `import`/`require` statements
- package.json deps
- Build errors
- First-time setup
- Version upgrades
**Rule**: If it's not in `.opencode/context/`, use ExternalScout.
---
## What if I already know the library?
**DON'T rely on training data - it's outdated.**
Example: You think "I know Next.js, I'll use pages/"
Reality: Next.js 15 uses app/
Result: Broken code ❌
**Always fetch current docs, even if you "know" the library.**
---
## How do I know if something is external?
**External:** npm/pip/gem/cargo packages | Third-party frameworks | ORMs | Auth libraries | UI libraries
**NOT external:** Your project's code | Project utilities | Internal modules
**Check:** Is it in `package.json` dependencies? → External → Use ExternalScout
---
## Can I use both ContextScout and ExternalScout?
**YES! Use both for most features.**
```javascript
// 1. ContextScout: Project standards
task(subagent_type="ContextScout", ...)
// 2. ExternalScout: Library docs
task(subagent_type="ExternalScout", ...)
// 3. Combine: Implement using both
```
---
## What if ExternalScout doesn't have the library?
ExternalScout has two sources:
1. **Context7 API** (primary): 50+ popular libraries
2. **Official docs** (fallback): Any library with public docs
If library not in Context7: Auto-fallback to official docs via webfetch.
---
## How do I write a good ExternalScout prompt?
**Template:**
```javascript
task(
subagent_type="ExternalScout",
description="Fetch [Library] docs for [specific topic]",
prompt="Fetch current documentation for [Library]: [specific question]
Focus on:
- [What you need - be specific]
- [Related features/APIs]
Context: [What you're building]"
)
```
**Good:** ✅ Specific | ✅ Focused (3-5 things) | ✅ Contextual
**Bad:** ❌ Vague | ❌ Too broad | ❌ No context
---
## What if I get an error after using ExternalScout?
**Process:**
1. Read error message carefully
2. ExternalScout again with specific error:
```javascript
task(
subagent_type="ExternalScout",
description="Fetch docs for error resolution",
prompt="Fetch [Library] docs: [error message]
Error: [paste actual error]
Focus on: Common causes | Solutions"
)
```
3. Check install scripts (maybe setup incomplete)
4. Verify versions (package.json vs docs)
---
## Do I need approval to use ExternalScout?
**NO - ExternalScout is read-only, no approval required.**
**Approval required:** ❌ Write code | ❌ Run commands | ❌ Install packages
**No approval:** ✅ ContextScout | ✅ ExternalScout | ✅ Read files
---
## ContextScout vs ExternalScout?
| Aspect | ContextScout | ExternalScout |
|--------|--------------|---------------|
| **Searches** | Internal project files | External documentation |
| **Location** | `.opencode/context/` | Internet (Context7, docs) |
| **Returns** | Project standards | Library APIs |
| **Use for** | "How we do things here" | "How this library works" |
| **Speed** | Fast (local) | Slower (network) |
**Use both together for best results.**
---
## Quick Checklist
Before implementing with external libraries:
- [ ] Used ContextScout for project standards?
- [ ] Checked for install scripts first?
- [ ] Used ExternalScout for EACH external library?
- [ ] Asked for installation steps?
- [ ] Asked for current API patterns?
- [ ] Read returned docs before coding?
**All checked? → You're doing it right! ✅**
---
## Supported Libraries
**See**: `.opencode/skill/context7/library-registry.md`
**Categories:** Database/ORM | Auth | Frontend | Infrastructure | UI | State | Validation | Testing
Not listed? ExternalScout can still fetch from official docs.
---
## Related
- `external-libraries-workflow.md` - Core workflow
- `external-libraries-scenarios.md` - Common scenarios
- `.opencode/agent/subagents/core/externalscout.md` - ExternalScout agent

View file

@ -0,0 +1,130 @@
<!-- Context: workflows/external-libraries-scenarios | Priority: medium | Version: 1.0 | Updated: 2026-02-05 -->
# External Libraries: Common Scenarios
**Purpose**: Real-world examples of using ExternalScout
---
## Scenario 1: New Build with External Packages
**Example**: Next.js app with Drizzle + Better Auth
**Process:**
1. Check install scripts: `ls scripts/install/`
2. Identify packages: Next.js, Drizzle ORM, Better Auth
3. ExternalScout for each package
4. Check requirements: PostgreSQL? Env vars?
5. Verify version compatibility
6. Implement following current docs
7. Test integration points
**ExternalScout calls:**
```javascript
// Drizzle ORM
task(
subagent_type="ExternalScout",
description="Fetch Drizzle PostgreSQL setup",
prompt="Fetch Drizzle ORM docs: PostgreSQL setup w/ modular schemas
Focus on: Installation | DB connection | Schema patterns | Migrations
Context: Next.js commerce site w/ PostgreSQL"
)
// Next.js App Router
task(
subagent_type="ExternalScout",
description="Fetch Next.js App Router docs",
prompt="Fetch Next.js docs: App Router w/ Server Actions
Focus on: Installation | Directory structure | Server Actions
Context: Commerce site w/ order processing"
)
```
---
## Scenario 2: Package Error During Build
**Example**: `Error: Cannot find module 'drizzle-orm/pg-core'`
**Process:**
1. Identify package: Drizzle ORM
2. ExternalScout: "Fetch Drizzle docs: PostgreSQL imports"
3. Check current import patterns
4. Verify package.json has correct deps
5. Propose fix from current docs
6. Request approval → Apply fix
---
## Scenario 3: First-Time Package Setup
**Example**: Setting up TanStack Query in Next.js
**Process:**
1. Check install scripts
2. ExternalScout: "Fetch TanStack Query docs: Next.js App Router setup"
3. Get: Install steps | Peer deps | Config | Patterns
4. If install script exists: Review → Run
5. If no script: Follow docs for manual setup
6. Implement → Test
---
## Scenario 4: Version Upgrade
**Example**: Next.js 14 → 15
**Process:**
1. ExternalScout: "Fetch Next.js 15 docs: Breaking changes and migration"
2. Review breaking changes
3. Identify affected code
4. Plan migration steps
5. Request approval → Implement → Test
---
## Real-World Example: Auth Implementation
**Task**: "Add authentication with Better Auth to Next.js commerce"
```javascript
// 1. ContextScout: Project standards
task(
subagent_type="ContextScout",
description="Find auth standards",
prompt="Find context files: Auth patterns | Security standards"
)
// Returns: security-patterns.md, code-quality.md
// 2. ExternalScout: Better Auth docs (MANDATORY)
task(
subagent_type="ExternalScout",
description="Fetch Better Auth + Next.js docs",
prompt="Fetch Better Auth docs: Next.js App Router integration
Focus on: Installation | App Router setup | Drizzle adapter | Session mgmt
Context: Adding auth to Next.js commerce w/ Drizzle ORM"
)
// Returns: Installation | Integration patterns | Working examples
// 3. Combine and implement
// - Better Auth patterns (from ExternalScout)
// - Security standards (from ContextScout)
// = Secure, well-structured auth ✅
```
---
## Error Handling Patterns
| Error Type | Process |
|------------|---------|
| **Package Installation** | ExternalScout: installation docs → Verify package name/version → Check peer deps |
| **Import/Module** | ExternalScout: import patterns → Check current API exports |
| **API/Configuration** | ExternalScout: API docs → Check current signatures |
| **Build Errors** | Identify package → ExternalScout: relevant docs → Check known issues |
---
## Related
- `external-libraries-workflow.md` - Core workflow
- `external-libraries-faq.md` - Troubleshooting FAQ

View file

@ -0,0 +1,138 @@
<!-- Context: workflows/external-libraries | Priority: high | Version: 2.1 | Updated: 2026-02-05 -->
# Workflow: External Libraries
**Purpose**: Fetch current documentation for external packages before implementation
---
## Quick Start
**Golden Rule**: NEVER rely on training data for external libraries → ALWAYS fetch current docs
**Process**: Detect package → Check install scripts → Use ExternalScout → Implement
**When to use ExternalScout** (MANDATORY):
- New builds with external packages
- First-time package setup
- Package/dependency errors
- Version upgrades
- ANY external library work
---
## Core Principle
<rule id="external_docs_required" enforcement="strict">
Training data is OUTDATED for external libraries.
ALWAYS fetch current docs using ExternalScout before implementation.
</rule>
**Why:**
- APIs change (new methods, deprecated features)
- Configuration patterns evolve
- Breaking changes happen frequently
**Example:**
```
Training data (2023): Next.js 13 uses pages/ directory
Current (2025): Next.js 15 uses app/ directory
Training data = broken code ❌
ExternalScout = working code ✅
```
---
## Workflow Stages
### 1. Detect External Package
**Triggers**: User mentions library | package.json deps | import statements | build errors
### 2. Check Install Scripts
```bash
ls scripts/install/ scripts/setup/ bin/install* setup.sh
grep -r "postinstall\|preinstall" package.json
```
Read scripts if found: What does it do? Environment variables? Prerequisites?
### 3. Fetch Current Documentation (MANDATORY)
```javascript
task(
subagent_type="ExternalScout",
description="Fetch [Library] docs for [topic]",
prompt="Fetch current documentation for [Library]: [specific question]
Focus on:
- Installation and setup steps
- [Specific feature/API needed]
- Required environment variables
Context: [What you're building]"
)
```
### 4. Verify Compatibility
Check: Version compatibility | Peer dependencies | Breaking changes
### 5. Implement with Current Patterns
- Use exact API signatures from docs
- Follow current best practices
- Use recommended config patterns
### 6. Test Integration
Verify: Package installs | Imports work | API calls match docs
---
## Decision Flow: ContextScout + ExternalScout
```
User Request: "Build Next.js commerce w/ Drizzle"
↓
STEP 1: ContextScout → Search internal context
↓
Internal context found?
↓
YES → Use internal NO → Is it external library?
↓
YES → STEP 2: ExternalScout (MANDATORY)
↓
STEP 3: Combine internal + external → Implement
```
| Scenario | ContextScout | ExternalScout |
|----------|--------------|---------------|
| Project coding standards | ✅ | ❌ |
| External library setup | ❌ | ✅ MANDATORY |
| Feature with external lib | ✅ standards | ✅ lib docs |
---
## Best Practices
**Do ✅:**
- Check install scripts first
- Always fetch current docs
- Verify versions match
- Test integrations
**Don't ❌:**
- Assume APIs based on training data
- Skip version checks
- Ignore peer dependencies
- Run install scripts blindly
---
## Related
- `external-libraries-scenarios.md` - Common scenarios and examples
- `external-libraries-faq.md` - Troubleshooting FAQ
- `.opencode/agent/subagents/core/externalscout.md` - ExternalScout agent

View file

@ -1,531 +0,0 @@
<!-- Context: workflows/external-libraries | Priority: high | Version: 2.0 | Updated: 2026-01-28 -->
# Workflow: External Libraries
**Purpose**: Fetch current documentation for external packages before implementation
**Last Updated**: 2026-01-28
---
## Quick Start
**Golden Rule**: NEVER rely on training data for external libraries → ALWAYS fetch current docs
**Process**: Detect package → Check install scripts → Use ExternalScout → Implement
**When to use ExternalScout** (MANDATORY):
- New builds w/ external packages
- First-time package setup
- Package/dependency errors
- Version upgrades
- ANY external library work
---
## Core Principle
<rule id="external_docs_required" enforcement="strict">
Training data is OUTDATED for external libraries.
ALWAYS fetch current docs using ExternalScout before implementation.
</rule>
**Why**:
- APIs change (new methods, deprecated features)
- Configuration patterns evolve
- Breaking changes happen frequently
- Version-specific features differ
**Example**:
```
Training data (2023): Next.js 13 uses pages/ directory
Current (2025): Next.js 15 uses app/ directory (App Router)
Training data = broken code ❌
ExternalScout = working code ✅
```
---
## Workflow Stages
### 1. Detect External Package
**Triggers**: User mentions library | package.json deps | import statements | build errors | first-time setup
**Action**: Identify which external packages involved
---
### 2. Check Install Scripts (First-Time Builds)
**Check for**:
```bash
# Look for install scripts
ls scripts/install/ scripts/setup/ bin/install* setup.sh install.sh
# Check package-specific requirements
grep -r "postinstall\|preinstall" package.json
```
**Read scripts if found**:
- What does it do?
- Environment variables needed?
- Prerequisites (database, services)?
**Why**: Scripts may set up databases, generate files, configure services in specific order
---
### 3. Fetch Current Documentation (MANDATORY)
**Basic Pattern**:
```javascript
task(
subagent_type="ExternalScout",
description="Fetch [Library] docs for [topic]",
prompt="Fetch current documentation for [Library]: [specific question]
Focus on:
- Installation and setup steps
- [Specific feature/API needed]
- [Integration requirements]
- Required environment variables
- Database/service setup
Context: [What you're building]"
)
```
**Real Examples**:
**Drizzle ORM Setup**:
```javascript
task(
subagent_type="ExternalScout",
description="Fetch Drizzle PostgreSQL setup",
prompt="Fetch Drizzle ORM docs: PostgreSQL setup w/ modular schemas
Focus on: Installation | DB connection | Schema patterns | Migrations | TypeScript config
Context: Next.js commerce site w/ PostgreSQL"
)
```
**Next.js App Router**:
```javascript
task(
subagent_type="ExternalScout",
description="Fetch Next.js App Router docs",
prompt="Fetch Next.js docs: App Router w/ Server Actions
Focus on: Installation | Directory structure | Server Actions | Data fetching | Route handlers
Context: Commerce site w/ order processing"
)
```
**Better Auth Integration**:
```javascript
task(
subagent_type="ExternalScout",
description="Fetch Better Auth + Next.js integration",
prompt="Fetch Better Auth docs: Next.js App Router integration w/ Drizzle
Focus on: Installation | App Router setup | Drizzle adapter | Session mgmt | Route protection
Context: Adding auth to Next.js commerce w/ Drizzle ORM"
)
```
**ExternalScout Returns**:
- Current, version-specific docs
- Installation steps + required packages
- Official API references
- Working code examples
- Current best practices
- Integration patterns
- Setup prerequisites
- Environment variables
- Common pitfalls + solutions
---
### 4. Verify Compatibility
**Check**: Version compatibility | Peer dependencies | Breaking changes | Platform requirements
**If version mismatch**: Note in plan → Request approval for upgrade → Fetch docs for specific version
---
### 5. Implement with Current Patterns
**Apply docs**:
- Use exact API signatures from docs
- Follow current best practices
- Use recommended config patterns
- Implement error handling as documented
**Don't**:
- ❌ Assume API based on training data
- ❌ Use deprecated patterns
- ❌ Skip version-specific requirements
- ❌ Ignore breaking changes
---
### 6. Test Integration
**Verify**: Package installs | Imports work | API calls match docs | Error handling | Integration w/ other packages
---
## Decision Flow: ContextScout + ExternalScout
```
User Request: "Build Next.js commerce w/ Drizzle"
↓
┌──────────────────────────────────────────────────┐
│ STEP 1: ContextScout │
│ → Search internal context (.opencode/context/) │
│ → Find project standards, patterns, workflows │
└──────────────────────────────────────────────────┘
↓
Internal context found?
↓
┌───────────┴───────────┐
YES NO
│ │
↓ ↓
Use internal Is it external library?
context ↓
┌────────┴────────┐
YES NO
│ │
↓ ↓
┌─────────────────┐ Report: No context
│ STEP 2: │ available
│ ExternalScout │
│ (MANDATORY) │
└─────────────────┘
↓
Fetch: Next.js docs
Drizzle docs
Integration patterns
↓
┌─────────────────────────┐
│ STEP 3: Combine │
│ Internal: Standards │
│ External: Library docs │
│ → Implement w/ both │
└─────────────────────────┘
```
**When to Use Which**:
| Scenario | ContextScout | ExternalScout | Both |
|----------|--------------|---------------|------|
| Project coding standards | ✅ | ❌ | ❌ |
| External library setup | ❌ | ✅ MANDATORY | ❌ |
| Project-specific patterns | ✅ | ❌ | ❌ |
| External API usage | ❌ | ✅ MANDATORY | ❌ |
| Feature w/ external lib | ✅ standards | ✅ lib docs | ✅ |
| Package installation | ❌ | ✅ MANDATORY | ❌ |
| Security patterns | ✅ | ❌ | ❌ |
| External lib integration | ✅ project | ✅ lib docs | ✅ |
**Key Principle**: ContextScout + ExternalScout = Complete Context
- **ContextScout**: "How we do things in THIS project"
- **ExternalScout**: "How to use THIS library (current version)"
- **Combined**: "How to use THIS library following OUR standards"
---
## Common Scenarios
### Scenario 1: New Build w/ External Packages
**Example**: Next.js app w/ Drizzle + Better Auth
**Process**:
1. Check install scripts: `ls scripts/install/ scripts/setup/`
2. Identify packages: Next.js, Drizzle ORM, Better Auth
3. ExternalScout for each: Installation | Setup | Integration
4. Check requirements: PostgreSQL? Env vars? Services?
5. Verify version compatibility
6. Run install scripts (if exist) OR create setup from docs
7. Implement following current docs
8. Test integration points
---
### Scenario 2: Package Error During Build
**Example**: `Error: Cannot find module 'drizzle-orm/pg-core'`
**Process**:
1. Identify package: Drizzle ORM
2. ExternalScout: "Fetch Drizzle docs: PostgreSQL setup and imports"
3. Check current import patterns
4. Verify package.json has correct deps
5. Propose fix from current docs
6. Request approval → Apply fix
---
### Scenario 3: First-Time Package Setup
**Example**: Setting up TanStack Query in Next.js
**Process**:
1. Check install scripts: `ls scripts/install/` | `grep -r "tanstack\|react-query" scripts/`
2. ExternalScout: "Fetch TanStack Query docs: Installation, Next.js App Router setup w/ Server Components"
3. Get: Install steps | Peer deps | Config files | Current patterns | Best practices
4. If install script exists: Review → Run
5. If no script: Follow docs for manual setup
6. Implement → Test
---
### Scenario 4: Version Upgrade
**Example**: Next.js 14 → 15
**Process**:
1. ExternalScout: "Fetch Next.js 15 docs: Breaking changes and migration guide"
2. Review breaking changes
3. Identify affected code
4. Plan migration steps
5. Request approval → Implement → Test
---
## Real-World Example: Auth Implementation
**Task**: "Add authentication w/ Better Auth to Next.js commerce site"
```javascript
// 1. ContextScout: Project standards
task(
subagent_type="ContextScout",
description="Find auth and security standards",
prompt="Find context files: Auth patterns | Security standards | Code quality | Project structure"
)
// Returns: security-patterns.md, code-quality.md
// 2. ExternalScout: Better Auth docs (MANDATORY)
task(
subagent_type="ExternalScout",
description="Fetch Better Auth + Next.js docs",
prompt="Fetch Better Auth docs: Next.js App Router integration
Focus on: Installation | App Router setup | Session mgmt | Route protection | Drizzle adapter
Context: Adding auth to Next.js commerce w/ Drizzle ORM"
)
// Returns: Current installation | Integration patterns | Drizzle config | Working examples
// 3. Combine and implement
// - Better Auth patterns (from ExternalScout)
// - Security standards (from ContextScout)
// - Code quality standards (from ContextScout)
// = Secure, well-structured auth implementation ✅
```
---
## Error Handling
| Error Type | Process |
|------------|---------|
| **Package Installation** | ExternalScout: installation docs → Verify package name/version → Check peer deps → Propose fix w/ current steps |
| **Import/Module** | ExternalScout: import patterns → Check current API exports → Verify import paths → Propose fix w/ current imports |
| **API/Configuration** | ExternalScout: API docs → Check current signatures → Verify config format → Propose fix w/ current patterns |
| **Build Errors** | Identify package → ExternalScout: relevant docs → Check known issues/breaking changes → Propose fix from current docs |
---
## Best Practices
**Do** ✅:
- Check install scripts first on new builds
- Always fetch current docs before implementing
- Use ExternalScout proactively on new builds
- Verify versions match (package.json vs docs)
- Check breaking changes when upgrading
- Read install scripts before running
- Check prerequisites (databases, services, env vars)
- Test integrations between packages
- Cache useful docs in `.opencode/context/development/frameworks/` if frequently used
**Don't** ❌:
- Assume APIs based on training data
- Skip version checks (breaking changes are common)
- Ignore peer dependencies
- Mix patterns from different versions
- Run install scripts blindly
- Skip environment setup
---
## Troubleshooting FAQ
### "When exactly should I use ExternalScout?"
**ALWAYS use ExternalScout when working with external packages.**
**Triggers**: User mentions library | `import`/`require` statements | package.json deps | build errors | first-time setup | version upgrades
**Rule**: If it's not in `.opencode/context/`, use ExternalScout.
---
### "What if I already know the library?"
**DON'T rely on training data - it's outdated.**
Example: You think "I know Next.js, I'll use pages/" → Reality: Next.js 15 uses app/ → Result: Broken code ❌
**Always fetch current docs, even if you "know" the library.**
---
### "How do I know if something is external?"
**External libraries**: npm/pip/gem/cargo packages | Third-party frameworks | ORMs/databases | Auth libraries | UI libraries
**NOT external**: Your project's code | Project utilities | Internal modules
**Check**: Is it in `package.json` dependencies? → External → Use ExternalScout
---
### "Can I use both ContextScout and ExternalScout?"
**YES! Use both for most features.**
```javascript
// 1. ContextScout: Project standards
task(subagent_type="ContextScout", ...)
// Returns: code-quality.md, security-patterns.md
// 2. ExternalScout: Library docs
task(subagent_type="ExternalScout", ...)
// Returns: Current Next.js docs, Drizzle docs
// 3. Combine: Implement using both
```
---
### "What if ExternalScout doesn't have the library?"
**ExternalScout has two sources**:
1. **Context7 API** (primary): 50+ popular libraries
2. **Official docs** (fallback): Any library w/ public docs
**If library not in Context7**: Auto-fallback to official docs via webfetch
**You don't need to worry - ExternalScout handles it.**
---
### "How do I write a good ExternalScout prompt?"
**Template**:
```javascript
task(
subagent_type="ExternalScout",
description="Fetch [Library] docs for [specific topic]",
prompt="Fetch current documentation for [Library]: [specific question]
Focus on:
- [What you need - be specific]
- [Related features/APIs]
- [Integration requirements]
Context: [What you're building]"
)
```
**Good prompts**: ✅ Specific | ✅ Focused (3-5 things) | ✅ Contextual | ✅ Current
**Bad prompts**: ❌ Vague | ❌ Too broad | ❌ No context
---
### "What if I get an error after using ExternalScout?"
**Normal - errors happen. Process**:
1. Read error message carefully
2. ExternalScout again w/ specific error:
```javascript
task(
subagent_type="ExternalScout",
description="Fetch docs for error resolution",
prompt="Fetch [Library] docs: [error message]
Error: [paste actual error]
Focus on: Common causes | Solutions | Correct API usage"
)
```
3. Check install scripts (maybe setup incomplete)
4. Verify versions (package.json vs docs)
---
### "Do I need approval to use ExternalScout?"
**NO - ExternalScout is read-only, no approval required.**
**Approval required**: ❌ Write code | ❌ Run commands | ❌ Install packages
**Approval NOT required**: ✅ ContextScout | ✅ ExternalScout | ✅ Read files | ✅ Search code
---
### "ContextScout vs ExternalScout?"
| Aspect | ContextScout | ExternalScout |
|--------|--------------|---------------|
| **Searches** | Internal project files | External documentation |
| **Location** | `.opencode/context/` | Internet (Context7, official docs) |
| **Returns** | Project standards, patterns | Library APIs, installation |
| **Use for** | "How we do things here" | "How this library works" |
| **Tools** | glob, read, grep | webfetch, Context7 API |
| **Speed** | Fast (local) | Slower (network) |
| **Currency** | Static (project docs) | Live (current docs) |
**Use both together for best results.**
---
### "Quick Checklist: Am I doing it right?"
Before implementing w/ external libraries:
- [ ] Used ContextScout for project standards?
- [ ] Checked for install scripts first?
- [ ] Used ExternalScout for EACH external library?
- [ ] Asked for installation steps in ExternalScout prompt?
- [ ] Asked for current API patterns and examples?
- [ ] Specified what I'm building (context)?
- [ ] Read returned docs before coding?
- [ ] Following both project standards AND library docs?
**All checked? → You're doing it right! ✅**
---
## Supported Libraries
**See**: `.opencode/skill/context7/library-registry.md`
**Categories**: Database/ORM (Drizzle, Prisma) | Auth (Better Auth, NextAuth, Clerk) | Frontend (Next.js, React, TanStack) | Infrastructure (Cloudflare, AWS, Vercel) | UI (Shadcn/ui, Radix, Tailwind) | State (Zustand, Jotai) | Validation (Zod, React Hook Form) | Testing (Vitest, Playwright)
**Not listed?** ExternalScout can still fetch from official docs via webfetch
---
## References
- **ExternalScout Agent**: `.opencode/agent/subagents/core/externalscout.md`
- **Library Registry**: `.opencode/skill/context7/library-registry.md`
- **ContextScout Agent**: `.opencode/agent/subagents/core/contextscout.md`
- **Code Standards**: `.opencode/context/core/standards/code-quality.md`

View file

@ -9,10 +9,23 @@
| File | Topic | Priority | Load When | | File | Topic | Priority | Load When |
|------|-------|----------|-----------| |------|-------|----------|-----------|
| `code-review.md` | Code review process | ⭐⭐⭐⭐ | Reviewing code | | `code-review.md` | Code review process | ⭐⭐⭐⭐ | Reviewing code |
| `task-delegation.md` | Delegating to subagents | ⭐⭐⭐⭐ | Using task tool | | `task-delegation-basics.md` | Core delegation workflow | ⭐⭐⭐⭐ | Using task tool |
| `task-delegation-specialists.md` | When to delegate to whom | ⭐⭐⭐⭐ | Choosing specialist |
| `task-delegation-caching.md` | Context caching | ⭐⭐⭐ | Repeated tasks |
| `external-libraries-workflow.md` | External library process | ⭐⭐⭐⭐ | External packages |
| `external-libraries-scenarios.md` | Common scenarios | ⭐⭐⭐ | Examples needed |
| `external-libraries-faq.md` | Troubleshooting | ⭐⭐⭐ | Errors/questions |
| `feature-breakdown.md` | Breaking down features | ⭐⭐⭐⭐ | 4+ files, complex tasks | | `feature-breakdown.md` | Breaking down features | ⭐⭐⭐⭐ | 4+ files, complex tasks |
| `session-management.md` | Managing sessions | ⭐⭐⭐ | Session cleanup | | `session-management.md` | Managing sessions | ⭐⭐⭐ | Session cleanup |
| `design-iteration.md` | Design iteration process | ⭐⭐⭐ | Design work | | `design-iteration-overview.md` | Design workflow overview | ⭐⭐⭐⭐ | Starting design work |
| `design-iteration-plan-file.md` | Design plan template | ⭐⭐⭐⭐ | Creating design plan |
| `design-iteration-stage-layout.md` | Stage 1: Layout | ⭐⭐⭐ | Layout design |
| `design-iteration-stage-theme.md` | Stage 2: Theme | ⭐⭐⭐ | Theme design |
| `design-iteration-stage-animation.md` | Stage 3: Animation | ⭐⭐⭐ | Animation design |
| `design-iteration-stage-implementation.md` | Stage 4: Implementation | ⭐⭐⭐ | Implementation |
| `design-iteration-visual-content.md` | Visual content generation | ⭐⭐ | Image generation |
| `design-iteration-best-practices.md` | Best practices & troubleshooting | ⭐⭐⭐ | Quality check |
| `design-iteration-plan-iterations.md` | Plan file iterations | ⭐⭐⭐ | Managing iterations |
--- ---
@ -23,7 +36,12 @@
2. Depends on: `../standards/code-quality.md`, `../standards/security-patterns.md` 2. Depends on: `../standards/code-quality.md`, `../standards/security-patterns.md`
**For task delegation**: **For task delegation**:
1. Load `task-delegation.md` (high) 1. Load `task-delegation-basics.md` (high)
2. Load `task-delegation-specialists.md` (when choosing agent)
**For external libraries**:
1. Load `external-libraries-workflow.md` (high)
2. Reference `external-libraries-scenarios.md` for examples
**For complex features**: **For complex features**:
1. Load `feature-breakdown.md` (high) 1. Load `feature-breakdown.md` (high)

View file

@ -0,0 +1,138 @@
<!-- Context: workflows/delegation | Priority: high | Version: 3.1 | Updated: 2026-02-05 -->
# Delegation Context Template
## Quick Reference
**Process**: Discover → Propose → Approve → Init Session → Persist Context → Delegate → Cleanup
**Location**: `.tmp/sessions/{YYYY-MM-DD}-{task-slug}/context.md`
**Key Principle**: ContextScout discovers paths. The orchestrator persists them into context.md AFTER approval. Downstream agents read from context.md — no re-discovery.
---
## When to Create a Session
Only create a session when:
- User has **approved** the proposed approach (never before)
- Task requires delegation to TaskManager or working agents
- Task is complex enough to need shared context (4+ files, >60min)
For simple tasks (1-3 files, direct execution): skip session creation entirely.
---
## The Flow
```
Stage 1: DISCOVER → ContextScout finds paths (read-only, nothing written)
Stage 2: PROPOSE → Show user lightweight summary (nothing written)
Stage 3: APPROVE → User says yes. NOW we can write.
Stage 4: INIT → Create session dir + context.md (persist discovered paths here)
Stage 5: DELEGATE → Pass session path to TaskManager / working agents
Stage 6: CLEANUP → Ask user, then delete session dir
```
---
## Template Structure
**Location**: `.tmp/sessions/{YYYY-MM-DD}-{task-slug}/context.md`
```markdown
# Task Context: {Task Name}
Session ID: {YYYY-MM-DD}-{task-slug}
Created: {ISO timestamp}
Status: in_progress
## Current Request
{What user asked for — verbatim or close paraphrase}
## Context Files (Standards to Follow)
Paths ContextScout discovered. Downstream agents load these for coding standards.
- .opencode/context/core/standards/code-quality.md
- {other paths}
## Reference Files (Source Material)
Project files relevant to the task — NOT standards.
- {e.g. package.json}
- {e.g. src/existing-module.ts}
## External Context Fetched
Live docs fetched via ExternalScout. Read-only cache.
- `.tmp/external-context/{package}/{topic}.md` — {description}
## Components
- {Component 1} — {what it does}
- {Component 2} — {what it does}
## Constraints
{Technical constraints, preferences, version requirements}
## Exit Criteria
- [ ] {specific completion condition}
## Progress
- [ ] Session initialized
- [ ] Tasks created (if using TaskManager)
- [ ] Implementation complete
```
---
## Delegation Process
**Step 1-3: Discover, Propose, Approve** (before any writes)
- Call ContextScout, capture paths
- Call ExternalScout if external libraries involved
- Show user lightweight summary, wait for approval
**Step 4: Init Session** (first writes, after approval)
- Create `.tmp/sessions/{YYYY-MM-DD}-{task-slug}/`
- Write `context.md` with discovered paths
**Step 5: Delegate**
```javascript
task(
subagent_type="TaskManager",
description="{brief}",
prompt="Load context from .tmp/sessions/{session-id}/context.md
{specific instructions}"
)
```
**Step 6: Cleanup**
- Ask user: "Task complete. Clean up session files?"
- If approved: Delete session directory
---
## Semantic Rules for Task JSONs
| Field | Contains | Example |
|-------|----------|---------|
| `context_files` | **Standards only** | `.opencode/context/core/standards/code-quality.md` |
| `reference_files` | **Source material only** | `src/auth/service.ts` |
| `external_context` | **External docs only** (read-only) | `.tmp/external-context/drizzle/schemas.md` |
**Never mix them.** Standards vs source material vs external docs.
---
## What Downstream Agents Expect
| Agent | Reads | Does |
|-------|-------|------|
| **TaskManager** | `context.md` (full) | Extracts files, creates subtask JSONs |
| **CoderAgent** | subtask JSON | Loads standards, references source, implements |
| **TestEngineer** | session path | Writes tests against same standards |
| **CodeReviewer** | session path | Reviews against applied standards |
---
## Related
- `task-delegation-specialists.md` - When to delegate to which specialist
- `task-delegation-caching.md` - Context caching for repeated patterns
- `../context-system/standards/mvi.md` - MVI principle

View file

@ -0,0 +1,143 @@
<!-- Context: workflows/delegation-caching | Priority: medium | Version: 1.0 | Updated: 2026-02-05 -->
# Context Caching for Delegation
**Purpose**: Cache discovered context to avoid re-discovery overhead in repeated tasks
---
## When to Cache
Cache context when:
- Same task type appears multiple times in session
- Same context files needed repeatedly
- Multiple subtasks use identical standards
- Parallel tasks need same context
---
## Cache Structure
```
.tmp/sessions/{session-id}/
├── context.md (main session context)
├── .cache/
│ ├── test-coverage.md (cached from .opencode/context/)
│ ├── code-quality.md
│ └── code-review.md
└── .manifest.json (tracks cache status)
```
---
## Cache Manifest
```json
{
"session_id": "2026-01-28-parallel-tests",
"created_at": "2026-01-28T14:30:22Z",
"cache": {
"test-coverage.md": {
"source": ".opencode/context/core/standards/test-coverage.md",
"cached_at": "2026-01-28T14:30:25Z",
"used_by": ["subtask_01", "subtask_02"],
"status": "valid"
}
}
}
```
---
## Invalidation Rules
**Cache is INVALID when:**
- Source file modified (check timestamp)
- Session older than 24 hours
- Context file version changed
- User explicitly requests refresh
**Cache is VALID when:**
- Source timestamp matches
- Session less than 24 hours old
- No version changes
- Multiple tasks in same session
---
## Implementation Pattern
```javascript
// Before delegating to subagent
IF cache exists AND cache is valid:
USE cached context file
SKIP re-reading from .opencode/context/
ELSE:
READ from .opencode/context/
CACHE the file
```
---
## Example: Parallel Tasks
```javascript
session_id = "2026-01-28-parallel-tests"
// Task 1: Write component A (parallel)
task(
subagent_type="CoderAgent",
description="Write component A",
prompt="Load context from .tmp/sessions/{session_id}/context.md
Use cached context if available at .cache/"
)
// Task 2: Write component B (parallel)
task(
subagent_type="CoderAgent",
description="Write component B",
prompt="Load context from .tmp/sessions/{session_id}/context.md
Use cached context if available at .cache/"
)
// Result: Task 1 caches context, Task 2 uses cache (faster)
```
---
## Cache Effectiveness
Track metrics:
```json
{
"cache_stats": {
"total_reads": 15,
"cache_hits": 9,
"cache_misses": 6,
"hit_rate": "60%"
}
}
```
---
## Best Practices
✅ **Do:**
- Cache context for repeated task types
- Validate cache before using
- Invalidate when source changes
- Monitor hit rate
- Clean up cache with session
❌ **Don't:**
- Cache external context (always fetch fresh)
- Cache for single-task sessions (overhead not worth it)
- Ignore invalidation rules
- Mix cached and fresh context in same task
---
## Related
- `task-delegation-basics.md` - Core delegation workflow
- `task-delegation-specialists.md` - When to delegate

View file

@ -0,0 +1,130 @@
<!-- Context: workflows/delegation-specialists | Priority: high | Version: 1.0 | Updated: 2026-02-05 -->
# When to Delegate to Specialists
**Purpose**: Guidance on when to delegate to specific specialist agents
---
## OpenFrontendSpecialist - UI/UX Design
**✅ DELEGATE when:**
- Creating new UI/UX designs (landing pages, dashboards)
- Building design systems (components, themes, style guides)
- Complex layouts requiring responsive design
- Visual polish (animations, transitions, micro-interactions)
- Brand-focused pages (marketing, product showcases)
- Accessibility-critical UI
**Delegation pattern:**
```javascript
task(
subagent_type="OpenFrontendSpecialist",
description="Design {feature} UI",
prompt="Load context from .tmp/sessions/{session-id}/context.md
Design {feature} following 4-stage workflow:
1. Stage 0: Create design plan file (MANDATORY FIRST)
2. Stage 1: Layout (ASCII wireframe)
3. Stage 2: Theme (design system, colors)
4. Stage 3: Animation (micro-interactions)
5. Stage 4: Implementation (single HTML file)
Request approval between stages."
)
```
**Why?** Follows structured 4-stage workflow with approval gates, produces polished UI.
---
## TestEngineer - Test Authoring
**✅ DELEGATE when:**
- Writing comprehensive test suites
- TDD workflows (tests before implementation)
- Complex test scenarios (edge cases, error handling)
- Integration tests across multiple components
**Delegation pattern:**
```javascript
task(
subagent_type="TestEngineer",
description="Write tests for {feature}",
prompt="Load context from .tmp/sessions/{session-id}/context.md
Write comprehensive tests for {feature}
Files to test: {file list}
Follow test coverage standards from context."
)
```
---
## CodeReviewer - Quality Assurance
**✅ DELEGATE when:**
- Reviewing complex implementations
- Security-critical code review
- Pre-merge quality checks
- Architecture validation
**Delegation pattern:**
```javascript
task(
subagent_type="CodeReviewer",
description="Review {feature}",
prompt="Load context from .tmp/sessions/{session-id}/context.md
Review {feature} against standards
Files: {file list}
Focus: security, performance, maintainability"
)
```
---
## CoderAgent - Focused Implementation
**✅ DELEGATE when:**
- Implementing atomic subtasks from TaskManager
- Isolated feature work (single component/module)
- Following specific implementation specs
**Delegation pattern:**
```javascript
task(
subagent_type="CoderAgent",
description="Implement {subtask}",
prompt="Load context from .tmp/sessions/{session-id}/context.md
Implement subtask: {description}
Follow implementation spec exactly.
Mark subtask complete when done."
)
```
---
## Decision Matrix
| Scenario | Agent | Why |
|----------|-------|-----|
| New landing page | OpenFrontendSpecialist | 4-stage design workflow |
| Test suite for auth | TestEngineer | Comprehensive coverage |
| Security review | CodeReviewer | Security focus |
| Single API endpoint | CoderAgent | Focused implementation |
| Complex multi-file feature | TaskManager → CoderAgent | Breakdown then implement |
---
## Key Principle
**TestEngineer and CodeReviewer should ALWAYS receive session context path.** This ensures they review against the same standards used during implementation.
---
## Related
- `task-delegation-basics.md` - Core delegation workflow
- `task-delegation-caching.md` - Context caching
- `design-iteration.md` - OpenFrontendSpecialist workflow

View file

@ -1,460 +0,0 @@
<!-- Context: workflows/delegation | Priority: high | Version: 3.0 | Updated: 2026-01-28 -->
# Delegation Context Template
## Quick Reference
**Process**: Discover → Propose → Approve → Init Session → Persist Context → Delegate → Cleanup
**Location**: `.tmp/sessions/{YYYY-MM-DD}-{task-slug}/context.md`
**Key Principle**: ContextScout discovers paths. The orchestrator persists them into context.md AFTER approval. Downstream agents read from context.md — no re-discovery.
---
## When to Create a Session
Only create a session when:
- User has **approved** the proposed approach (never before)
- Task requires delegation to TaskManager or working agents
- Task is complex enough to need shared context (4+ files, >60min)
For simple tasks (1-3 files, direct execution): skip session creation entirely.
---
## The Flow
```
Stage 1: DISCOVER → ContextScout finds paths (read-only, nothing written)
Stage 2: PROPOSE → Show user lightweight summary (nothing written)
Stage 3: APPROVE → User says yes. NOW we can write.
Stage 4: INIT → Create session dir + context.md (persist discovered paths here)
Stage 5: DELEGATE → Pass session path to TaskManager / working agents
Stage 6: CLEANUP → Ask user, then delete session dir
```
---
## Template Structure
**Location**: `.tmp/sessions/{YYYY-MM-DD}-{task-slug}/context.md`
```markdown
# Task Context: {Task Name}
Session ID: {YYYY-MM-DD}-{task-slug}
Created: {ISO timestamp}
Status: in_progress
## Current Request
{What user asked for — verbatim or close paraphrase}
## Context Files (Standards to Follow)
These are the paths ContextScout discovered. Downstream agents load these for coding standards, patterns, and conventions.
- .opencode/context/core/standards/code-quality.md
- .opencode/context/core/standards/test-coverage.md
- {other paths discovered by ContextScout}
## Reference Files (Source Material to Look At)
These are project files relevant to the task — NOT standards. Downstream agents reference these to understand existing code, config, or structure.
- {e.g. package.json}
- {e.g. src/existing-module.ts}
## External Context Fetched
These are live documentation files fetched from external libraries via ExternalScout. Subagents should reference these instead of re-fetching.
- `.tmp/external-context/{package-name}/{topic}.md` — {description}
- `.tmp/external-context/{package-name}/{topic}.md` — {description}
**Important**: These files are read-only and cached for reference. Do not modify them.
## Components
{The functional units identified during proposal}
- {Component 1} — {what it does}
- {Component 2} — {what it does}
## Constraints
{Technical constraints, preferences, compatibility notes, version requirements}
## Exit Criteria
- [ ] {specific, measurable completion condition}
- [ ] {specific, measurable completion condition}
## Progress
- [ ] Session initialized
- [ ] Tasks created (if using TaskManager)
- [ ] Implementation complete
- [ ] Tests passing
- [ ] Handoff complete
```
---
## Delegation Process
**Step 1: Discover** (before approval)
- Call ContextScout. Capture the returned file paths.
- Call ExternalScout if external libraries involved.
- Do NOT write anything to disk.
**Step 2: Propose** (before approval)
- Show user a lightweight summary of approach + discovered context.
- Do NOT create session or plan docs.
**Step 3: Approve** (gate)
- Wait for explicit user approval.
- If rejected or redirected → back to Step 1.
**Step 4: Init Session** (first writes, only after approval)
- Create `.tmp/sessions/{YYYY-MM-DD}-{task-slug}/`
- Write `context.md` using the template above.
- **CRITICAL**: Populate `## Context Files` with the paths ContextScout discovered in Step 1. This is the handoff point — if you skip this, downstream agents lose the context.
- Populate `## Reference Files` with any project source files relevant to the task.
**Step 5: Delegate with context path**
```
task(
subagent_type="TaskManager", // or CoderAgent, TestEngineer, etc.
description="{brief description}",
prompt="Load context from .tmp/sessions/{session-id}/context.md
Read the context file for full requirements, standards, and constraints.
{specific instructions for this subagent}"
)
```
**Step 6: Cleanup after completion**
- Ask user: "Task complete. Clean up session files at `.tmp/sessions/{session-id}/`?"
- If approved: Delete session directory.
---
## Semantic Rules for Task JSONs
When TaskManager creates subtask JSONs, it MUST follow these rules:
| Field | Contains | Example |
|-------|----------|---------|
| `context_files` | **Standards only** — paths to coding conventions, patterns, security rules | `.opencode/context/core/standards/code-quality.md` |
| `reference_files` | **Source material only** — project files to look at for existing patterns | `src/auth/existing-service.ts`, `package.json` |
| `external_context` | **External docs only** — cached documentation from external libraries (read-only) | `.tmp/external-context/drizzle-orm/modular-schemas.md` |
**Never mix them.** A downstream agent reading `context_files` expects "rules to follow." A downstream agent reading `reference_files` expects "files to understand." A downstream agent reading `external_context` expects "cached external docs to reference" (read-only). Mixing them causes confusion about what to follow vs. what to reference vs. what to read.
---
## What Downstream Agents Expect
| Agent | What it reads | What it does with it |
|-------|---------------|---------------------|
| **TaskManager** | `context.md` (full session) | Extracts context_files + reference_files + external_context, puts them into subtask JSONs |
| **CoderAgent** | subtask JSON (`context_files` + `reference_files` + `external_context`) | Loads standards, references source files, reads external docs, implements |
| **TestEngineer** | session `context.md` path (passed in prompt) | Knows what standards were applied, reads external context, writes tests accordingly |
| **CodeReviewer** | session `context.md` path (passed in prompt) | Knows what standards were applied, reviews against them, considers external context |
| **OpenFrontendSpecialist** | session `context.md` path (passed in prompt) | Follows 4-stage design workflow (Layout → Theme → Animation → Implementation) |
**Key**:
- TestEngineer and CodeReviewer should ALWAYS receive the session context path when delegated. This way they review against the same standards that were used during implementation — not whatever they independently discover.
- All agents should read `external_context` files to understand external library patterns and requirements — this avoids re-fetching and ensures consistency.
- **OpenFrontendSpecialist should be used for UI/UX design work** - See `workflows/design-iteration.md` for when to delegate vs execute directly.
---
## When to Delegate to Specialists
### OpenFrontendSpecialist - UI/UX Design
**✅ STRONGLY RECOMMENDED to delegate when:**
- Creating new UI/UX designs (landing pages, dashboards, app interfaces)
- Building design systems (component libraries, themes, style guides)
- Complex layouts requiring responsive design
- Visual polish work (animations, transitions, micro-interactions)
- Brand-focused pages (marketing, product showcases)
- Accessibility-critical UI (forms, navigation, interactive components)
**Delegation pattern:**
```javascript
task(
subagent_type="OpenFrontendSpecialist",
description="Design {feature} UI",
prompt="Load context from .tmp/sessions/{session-id}/context.md
Design a {feature} following the 4-stage workflow:
CRITICAL: Create design plan file at .tmp/design-plans/{project}-{feature}.md BEFORE starting
Stages:
1. Stage 0: Create design plan file (MANDATORY FIRST)
2. Stage 1: Layout (ASCII wireframe) → Update plan file
3. Stage 2: Theme (design system, colors) → Update plan file
4. Stage 3: Animation (micro-interactions) → Update plan file
5. Stage 4: Implementation (single HTML file) → Update plan file
Requirements:
- {requirement 1}
- {requirement 2}
Plan file preserves context across stages and allows user to review/edit.
Request approval between each stage.
Update plan file after each stage and user feedback."
)
```
**Why delegate?**
- Follows structured 4-stage design workflow with approval gates
- Produces polished, accessible, production-ready UI
- Handles responsive design, OKLCH colors, semantic HTML
- Creates single-file HTML prototypes for quick iteration
**See**: `workflows/design-iteration.md` for full workflow details
### TestEngineer - Test Authoring
**Delegate when:**
- Writing comprehensive test suites
- TDD workflows (tests before implementation)
- Complex test scenarios (edge cases, error handling)
- Integration tests across multiple components
**Delegation pattern:**
```javascript
task(
subagent_type="TestEngineer",
description="Write tests for {feature}",
prompt="Load context from .tmp/sessions/{session-id}/context.md
Write comprehensive tests for {feature}
Files to test:
- {file 1}
- {file 2}
Follow test coverage standards from context."
)
```
### CodeReviewer - Quality Assurance
**Delegate when:**
- Reviewing complex implementations
- Security-critical code review
- Pre-merge quality checks
- Architecture validation
**Delegation pattern:**
```javascript
task(
subagent_type="CodeReviewer",
description="Review {feature} implementation",
prompt="Load context from .tmp/sessions/{session-id}/context.md
Review {feature} implementation against standards
Files to review:
- {file 1}
- {file 2}
Focus on: security, performance, maintainability"
)
```
### CoderAgent - Focused Implementation
**Delegate when:**
- Implementing atomic subtasks from TaskManager
- Isolated feature work (single component/module)
- Following specific implementation specs
**Delegation pattern:**
```javascript
task(
subagent_type="CoderAgent",
description="Implement {subtask}",
prompt="Load context from .tmp/sessions/{session-id}/context.md
Implement subtask: {subtask description}
Follow the implementation spec exactly.
Mark subtask as complete when done."
)
```
---
## Context Caching for Repeated Patterns
For repeated task types (e.g., "write tests", "code review", "documentation"), cache discovered context to avoid re-discovery overhead.
### When to Cache
Cache context when:
- Same task type appears multiple times in a session
- Same context files are needed repeatedly
- Multiple subtasks use identical standards
- Parallel tasks need the same context
### Cache Structure
```
.tmp/sessions/{session-id}/
├── context.md (main session context)
├── .cache/
│ ├── test-coverage.md (cached from .opencode/context/core/standards/test-coverage.md)
│ ├── code-quality.md (cached from .opencode/context/core/standards/code-quality.md)
│ └── code-review.md (cached from .opencode/context/core/workflows/code-review.md)
└── .manifest.json (tracks cache status)
```
### Cache Manifest
```json
{
"session_id": "2026-01-28-parallel-tests",
"created_at": "2026-01-28T14:30:22Z",
"cache": {
"test-coverage.md": {
"source": ".opencode/context/core/standards/test-coverage.md",
"cached_at": "2026-01-28T14:30:25Z",
"used_by": ["subtask_01", "subtask_02", "subtask_03"],
"status": "valid"
},
"code-quality.md": {
"source": ".opencode/context/core/standards/code-quality.md",
"cached_at": "2026-01-28T14:30:26Z",
"used_by": ["subtask_01", "subtask_02"],
"status": "valid"
}
}
}
```
### Cache Invalidation Rules
Cache is INVALID when:
- Source file has been modified (check timestamp)
- Session is older than 24 hours
- Context file version has changed
- User explicitly requests cache refresh
Cache is VALID when:
- Source file timestamp matches cached timestamp
- Session is less than 24 hours old
- No version changes detected
- Multiple tasks in same session use same context
### Implementation Pattern
**Step 1: Check Cache**
```javascript
// Before delegating to subagent
IF cache exists AND cache is valid:
USE cached context file
SKIP re-reading from .opencode/context/
ELSE:
READ from .opencode/context/
CACHE the file
```
**Step 2: Cache Hit Example**
```
Session: 2026-01-28-parallel-tests
Task 1: Write component A
→ Load test-coverage.md (CACHE MISS)
→ Cache it at .tmp/sessions/.../cache/test-coverage.md
Task 2: Write component B
→ Load test-coverage.md (CACHE HIT)
→ Use cached version (faster)
Task 3: Write tests
→ Load test-coverage.md (CACHE HIT)
→ Use cached version (faster)
```
**Step 3: Cache Miss Example**
```
Session: 2026-01-28-parallel-tests
Task 1: Write code
→ Load code-quality.md (CACHE MISS)
→ Cache it
Task 2: Code review
→ Load code-review.md (CACHE MISS)
→ Cache it
Task 3: Write more code
→ Load code-quality.md (CACHE HIT)
→ Use cached version
```
### Benefits
- **Faster execution**: Avoid re-reading same files
- **Reduced I/O**: Fewer file system operations
- **Better performance**: Especially for parallel tasks
- **Consistent context**: All tasks use same version
### Example: Parallel Tasks with Caching
```javascript
// Session initialization
session_id = "2026-01-28-parallel-tests"
context_cache = {}
// Task 1: Write component A (parallel)
task(
subagent_type="CoderAgent",
description="Write component A",
prompt="Load context from .tmp/sessions/{session_id}/context.md
Use cached context if available at .tmp/sessions/{session_id}/.cache/"
)
// Task 2: Write component B (parallel)
task(
subagent_type="CoderAgent",
description="Write component B",
prompt="Load context from .tmp/sessions/{session_id}/context.md
Use cached context if available at .tmp/sessions/{session_id}/.cache/"
)
// Task 3: Write tests (depends on 1+2)
task(
subagent_type="TestEngineer",
description="Write tests",
prompt="Load context from .tmp/sessions/{session_id}/context.md
Use cached context if available at .tmp/sessions/{session_id}/.cache/"
)
// Result: Tasks 1 & 2 cache context, Task 3 uses cache (faster)
```
### Monitoring Cache
Track cache effectiveness:
```json
{
"cache_stats": {
"total_reads": 15,
"cache_hits": 9,
"cache_misses": 6,
"hit_rate": "60%",
"time_saved": "2.3 seconds"
}
}
```
### Best Practices
✅ **Do**:
- Cache context for repeated task types
- Validate cache before using
- Invalidate cache when source changes
- Monitor cache hit rate
- Clean up cache with session
❌ **Don't**:
- Cache external context (always fetch fresh)
- Cache for single-task sessions (overhead not worth it)
- Ignore cache invalidation rules
- Mix cached and fresh context in same task

View file

@ -0,0 +1,59 @@
# Agent Skills
**Purpose**: Markdown files that teach Claude how to do specific tasks
---
## Core Concept
A Skill is a `SKILL.md` file that teaches Claude specialized knowledge. Skills are **model-invoked**: Claude automatically applies them based on task context matching the description field.
---
## Key Points
- Skills live in `~/.claude/skills/` (personal) or `.claude/skills/` (project)
- Each skill needs a directory with `SKILL.md` inside
- Name and description in YAML frontmatter are required
- Claude loads only name/description at startup (lazy loading)
- Full content loaded when skill is activated
---
## Skill File Format
```yaml
---
name: explaining-code
description: Explains code with diagrams and analogies. Use when explaining how code works.
---
When explaining code, always include:
1. **Start with an analogy**: Compare to everyday life
2. **Draw a diagram**: ASCII art for flow/structure
3. **Walk through the code**: Step-by-step
4. **Highlight a gotcha**: Common mistakes
```
---
## Where Skills Live
| Location | Path | Scope |
|----------|------|-------|
| Enterprise | Managed settings | All org users |
| Personal | `~/.claude/skills/` | You, all projects |
| Project | `.claude/skills/` | Anyone in repo |
| Plugin | Plugin's `skills/` | Plugin users |
Priority: Enterprise > Personal > Project > Plugin
---
## Related
- `../guides/creating-skills.md` - How to create skills
- `../lookup/skill-metadata.md` - Metadata fields
- `../lookup/skills-comparison.md` - Skills vs other options
**Reference**: https://docs.anthropic.com/en/docs/claude-code/skills

View file

@ -0,0 +1,128 @@
# Concept: Compatibility Layer Architecture
**Purpose**: Enable bidirectional translation between OpenAgents Control and other AI coding tools
**Last Updated**: 2026-02-04
---
## Core Idea
Adapter pattern that translates agent configurations between OAC format and tool-specific formats (Cursor IDE, Claude Code, Windsurf). Enables seamless migration and multi-tool workflows through bidirectional mapping with graceful degradation.
---
## Key Components
**Adapters**: Tool-specific translation classes inheriting from BaseAdapter
- ClaudeAdapter - Claude Code format (.claude/config.json + skills)
- CursorAdapter - Cursor IDE format (.cursorrules single file)
- WindsurfAdapter - Windsurf format (.windsurf/agents/)
**Mappers**: Pure functions for feature translation
- ToolMapper - Tool name mapping (bash → terminal, task → delegate)
- PermissionMapper - Permission translation with degradation
- ModelMapper - Model ID mapping with fallbacks
- ContextMapper - Context file path translation
**Core Services**:
- AgentLoader - Parse OAC markdown files with YAML frontmatter
- AdapterRegistry - Register and retrieve adapters
- TranslationEngine - Orchestrate bidirectional conversion
- CapabilityMatrix - Track feature parity across tools
---
## Architecture Pattern
```
OAC Agent File (.md)
↓ (parse)
AgentLoader → OpenAgent object (validated with Zod)
↓ (convert)
BaseAdapter.fromOAC()
↓ (map features)
Mappers (tools, permissions, models, contexts)
↓ (output)
Tool-specific config files
```
**Reverse direction**: Tool config → toOAC() → OpenAgent → OAC .md file
---
## Design Principles
- **Bidirectional**: Convert OAC → Tool AND Tool → OAC where possible
- **Graceful Degradation**: Map unsupported features to closest equivalent with warnings
- **Pure Mappers**: All mapping functions are pure (no side effects)
- **Template Method**: BaseAdapter defines algorithm, subclasses fill details
- **Validation First**: Zod schemas validate before/after conversion
---
## Feature Parity
| Feature | OAC | Claude | Cursor | Windsurf |
|---------|-----|--------|--------|----------|
| Multiple agents | ✅ | ✅ | ❌ Single | ✅ |
| Granular permissions | ✅ | ⚠️ Simplified | ❌ | ⚠️ Partial |
| Temperature | ✅ | ❌ | ⚠️ Partial | ⚠️ Partial |
| Skills | ✅ | ✅ | ❌ | ⚠️ Partial |
| Hooks | ✅ | ✅ | ❌ | ❌ |
| Context files | ✅ | ✅ Skills | ✅ .cursorrules | ✅ |
---
## Quick Example
```typescript
// Load OAC agent
const agent = await AgentLoader.loadAgent('.opencode/agent/openagent.md')
// Get Claude adapter
const adapter = AdapterRegistry.get('claude')
// Convert to Claude format
const result = await adapter.fromOAC(agent)
// Outputs: .claude/config.json, .claude/skills/[...]
console.log(result.configs) // Array of files to write
console.log(result.warnings) // Feature degradation warnings
```
---
## Common Challenges
**Single-File Tools** (Cursor): Merge multiple OAC agents into one .cursorrules file
**Permission Mapping**: OAC granular permissions → simplified tool permissions
**Model IDs**: Different tools use different model identifiers (requires mapping table)
**Context Paths**: OAC uses .opencode/context/, tools use various paths
---
## Implementation Status
**Issue #141**: https://github.com/darrenhinde/OpenAgentsControl/issues/141
**Progress**: 28.13% (9/32 subtasks)
- ✅ Phase 1 (Foundation): 100% complete - 1,475 lines
- ⬅️ Phase 2 (Adapters): 50% complete - 1,858 lines (implementations done, tests pending)
- 📝 Phase 3 (Mappers): 0% - Pending
- 📝 Phase 4 (CLI): 0% - Pending
- 📝 Phase 5 (Documentation): 0% - Pending
**Location**: `packages/compatibility-layer/src/`
---
## Reference
- **Related**:
- examples/baseadapter-implementation.md
- guides/compatibility-layer-development.md
- lookup/compatibility-layer-adapters.md
- lookup/compatibility-layer-progress.md
- lookup/compatibility-learnings.md
- lookup/tool-feature-parity.md

View file

@ -0,0 +1,64 @@
# Hooks System
**Purpose**: User-defined shell commands that execute at Claude Code lifecycle points
---
## Core Concept
Hooks provide **deterministic control** over Claude Code's behavior. Unlike prompting (which suggests), hooks **guarantee** certain actions happen at specific points in the workflow.
---
## Key Points
- Hooks are shell commands triggered by events
- Run automatically during agent loop with your credentials
- Can block operations (exit code 2), allow silently, or provide feedback
- Configure in `settings.json` or plugin's `hooks/hooks.json`
- Matchers filter which tools/events trigger the hook
---
## Common Use Cases
| Use Case | Event | Example |
|----------|-------|---------|
| Auto-format | `PostToolUse` | Run prettier after Edit/Write |
| Notifications | `Notification` | Desktop alert when input needed |
| File protection | `PreToolUse` | Block edits to .env files |
| Logging | `PreToolUse` | Track all bash commands |
| Feedback | `PostToolUse` | Lint check after code changes |
---
## Quick Example
```json
{
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "jq -r '.tool_input.command' >> ~/.claude/bash-log.txt"
}]
}]
}
}
```
---
## Security Warning
Hooks run with your credentials. Malicious hooks can exfiltrate data. Always review hook implementations before adding them.
---
## Related
- `../lookup/hook-events.md` - All hook events
- `../examples/hooks/` - Hook examples
**Reference**: https://docs.anthropic.com/en/docs/claude-code/hooks

View file

@ -0,0 +1,58 @@
# Subagents System
**Purpose**: Specialized AI assistants with own context window for task-specific workflows
---
## Core Concept
Subagents are isolated AI assistants that handle specific tasks. Each runs in its own context with custom system prompt, specific tool access, and independent permissions. When Claude encounters a matching task, it delegates to the subagent.
---
## Key Benefits
- **Preserve context**: Keep exploration/implementation out of main conversation
- **Enforce constraints**: Limit which tools subagent can use
- **Reuse configs**: User-level subagents work across projects
- **Specialize behavior**: Focused prompts for specific domains
- **Control costs**: Route to faster/cheaper models (Haiku)
---
## How Delegation Works
1. Claude analyzes task description and subagent descriptions
2. Matches task to appropriate subagent
3. Delegates work to subagent's isolated context
4. Subagent works independently
5. Returns results to main conversation
---
## Subagent Locations
| Location | Scope | Priority |
|----------|-------|----------|
| `--agents` CLI flag | Current session | 1 (highest) |
| `.claude/agents/` | Current project | 2 |
| `~/.claude/agents/` | All your projects | 3 |
| Plugin's `agents/` | Plugin users | 4 (lowest) |
---
## Key Constraints
- Subagents cannot spawn other subagents
- Background subagents auto-deny permissions not pre-approved
- MCP tools not available in background subagents
---
## Related
- `../lookup/builtin-subagents.md` - Built-in subagents
- `../guides/creating-subagents.md` - Creation guide
- `../lookup/subagent-frontmatter.md` - Configuration
**Reference**: https://docs.anthropic.com/en/docs/claude-code/sub-agents

View file

@ -0,0 +1,102 @@
# Skills Troubleshooting
**Purpose**: Common skill issues and solutions
---
## Skill Not Triggering
**Symptom**: Claude doesn't use your skill when expected
**Cause**: Description doesn't match user requests
**Solution**: Write specific descriptions with trigger terms:
```yaml
# Bad
description: Helps with documents
# Good
description: Extract text from PDF files, fill forms, merge documents. Use when working with PDFs, forms, or document extraction.
```
**Tip**: Include keywords users would naturally say
---
## Skill Doesn't Load
**Check file path**:
| Type | Correct Path |
|------|--------------|
| Personal | `~/.claude/skills/my-skill/SKILL.md` |
| Project | `.claude/skills/my-skill/SKILL.md` |
| Plugin | `skills/my-skill/SKILL.md` |
**Check YAML syntax**:
- First line must be `---` (no blank lines before)
- End frontmatter with `---`
- Use spaces, not tabs
**Debug**: Run `claude --debug` to see loading errors
---
## Skill Has Errors
**Dependencies not installed**:
- List required packages in description
- User must install before skill works
**Script permissions**:
```bash
chmod +x scripts/*.py
```
**Path format**: Use forward slashes (Unix style)
---
## Multiple Skills Conflict
**Symptom**: Claude uses wrong skill
**Cause**: Similar descriptions
**Solution**: Make descriptions distinct:
```yaml
# Skill 1
description: Analyze sales data in Excel files and CRM exports
# Skill 2
description: Analyze log files and system metrics
```
---
## Plugin Skills Not Appearing
**Solution**: Clear cache and reinstall
```bash
rm -rf ~/.claude/plugins/cache
# Restart Claude Code
/plugin install plugin-name@marketplace
```
**Verify structure**:
```
my-plugin/
├── .claude-plugin/
│ └── plugin.json
└── skills/
└── my-skill/
└── SKILL.md
```
---
## Related
- `../concepts/agent-skills.md` - Skills overview
- `../guides/creating-skills.md` - Creation guide
**Reference**: https://docs.anthropic.com/en/docs/claude-code/skills

View file

@ -0,0 +1,158 @@
# Example: BaseAdapter Implementation Pattern
**Purpose**: Template method pattern for AI tool adapters
**Last Updated**: 2026-02-04
---
## Core Pattern
**Template Method**: BaseAdapter defines algorithm structure, subclasses implement tool-specific details
---
## BaseAdapter Structure
```typescript
export abstract class BaseAdapter {
abstract name: string
abstract displayName: string
// Must implement
abstract toOAC(source: string): Promise<OpenAgent>
abstract fromOAC(agent: OpenAgent): Promise<ConversionResult>
abstract getConfigPath(): string
abstract getCapabilities(): ToolCapabilities
abstract validateConversion(agent: OpenAgent): string[]
// Shared utilities
supportsFeature(feature: keyof ToolCapabilities): boolean
warn(message: string): void
createSuccessResult(configs, warnings): ConversionResult
safeParseJSON(content, filename): unknown | null
unsupportedFeatureWarning(feature, value): string
degradedFeatureWarning(feature, from, to): string
}
```
---
## Implementation Example
```typescript
export class WindsurfAdapter extends BaseAdapter {
name = 'windsurf'
displayName = 'Windsurf'
async toOAC(source: string): Promise<OpenAgent> {
const config = this.safeParseJSON(source, 'config.json')
return {
frontmatter: {
name: config.name,
model: this.mapWindsurfModelToOAC(config.model),
tools: this.parseWindsurfTools(config.tools),
temperature: this.mapCreativityToTemperature(config.creativity)
},
systemPrompt: config.systemPrompt,
contexts: []
}
}
async fromOAC(agent: OpenAgent): Promise<ConversionResult> {
const warnings: string[] = []
// Warn on unsupported features
if (agent.frontmatter.hooks) {
warnings.push(this.unsupportedFeatureWarning('hooks', 'lost'))
}
const config = {
name: agent.frontmatter.name,
model: this.mapOACModelToWindsurf(agent.frontmatter.model),
creativity: this.mapTemperatureToCreativity(agent.frontmatter.temperature)
}
return this.createSuccessResult([
{ fileName: '.windsurf/config.json', content: JSON.stringify(config) }
], warnings)
}
getCapabilities(): ToolCapabilities {
return {
supportsMultipleAgents: true,
supportsHooks: false,
supportsTemperature: true // via creativity
}
}
}
```
---
## Key Methods
### toOAC()
Parse tool format → OpenAgent object
- Parse source (JSON/YAML)
- Map fields
- Validate with Zod
- Return OpenAgent
### fromOAC()
Convert OpenAgent → tool format
- Validate input
- Map fields
- Detect unsupported features → warnings
- Generate config files
### getCapabilities()
Declare supported features (used for validation)
---
## Utility Usage
```typescript
// Safe parsing
const config = this.safeParseJSON(content, 'config.json')
// Feature checks
if (this.supportsFeature('supportsTemperature')) {
config.temperature = agent.frontmatter.temperature
}
// Warnings
if (!this.supportsFeature('supportsHooks')) {
warnings.push(this.unsupportedFeatureWarning('hooks'))
}
// Results
return this.createSuccessResult([{ fileName, content }], warnings)
```
---
## Design Principles
1. **Template Method** - Base defines structure, subs fill details
2. **Pure toOAC/fromOAC** - Deterministic conversion
3. **Capabilities First** - Declare support upfront
4. **Graceful Degradation** - Warn, don't fail
5. **Validate Early** - Check before converting
---
## Reference
**Implementation**: `packages/compatibility-layer/src/adapters/BaseAdapter.ts`
**Concrete Adapters**:
- ClaudeAdapter.ts (600 lines)
- CursorAdapter.ts (554 lines)
- WindsurfAdapter.ts (514 lines)
**Related**:
- concepts/compatibility-layer.md
- guides/compatibility-layer-development.md
- lookup/compatibility-layer-adapters.md

View file

@ -0,0 +1,194 @@
# Example: BaseAdapter Implementation Pattern
**Purpose**: Template Method pattern for AI coding tool adapters
**Last Updated**: 2026-02-04
---
## Core Pattern
Template Method: BaseAdapter defines algorithm structure, subclasses implement tool-specific details.
---
## BaseAdapter Structure
```typescript
export abstract class BaseAdapter {
abstract name: string
abstract displayName: string
// Must implement
abstract toOAC(source: string): Promise<OpenAgent>
abstract fromOAC(agent: OpenAgent): Promise<ConversionResult>
abstract getConfigPath(): string
abstract getCapabilities(): ToolCapabilities
abstract validateConversion(agent: OpenAgent): string[]
// Shared utilities
supportsFeature(feature: keyof ToolCapabilities): boolean
warn(message: string): void
createSuccessResult(configs, warnings): ConversionResult
safeParseJSON(content, filename): unknown | null
}
```
---
## ClaudeAdapter Example
```typescript
export class ClaudeAdapter extends BaseAdapter {
name = 'claude'
displayName = 'Claude Code'
async toOAC(source: string): Promise<OpenAgent> {
const config = this.safeParseJSON(source, 'config.json')
return {
frontmatter: {
name: config.name,
mode: config.mode || 'primary',
model: this.mapModel(config.model),
tools: config.tools,
skills: config.skills?.map(s => ({ name: s }))
},
systemPrompt: config.systemPrompt || ''
}
}
async fromOAC(agent: OpenAgent): Promise<ConversionResult> {
const warnings: string[] = []
// Warn on unsupported features
if (agent.frontmatter.temperature) {
warnings.push(this.unsupportedFeatureWarning('temperature'))
}
const config = {
name: agent.frontmatter.name,
model: agent.frontmatter.model,
systemPrompt: agent.systemPrompt,
tools: agent.frontmatter.tools
}
return this.createSuccessResult([
{ fileName: '.claude/config.json', content: JSON.stringify(config) }
], warnings)
}
getConfigPath() { return '.claude/' }
getCapabilities(): ToolCapabilities {
return {
supportsMultipleAgents: true,
supportsSkills: true,
supportsHooks: true,
supportsTemperature: false
}
}
validateConversion(agent: OpenAgent): string[] {
return agent.frontmatter.name ? [] : ['Agent name required']
}
}
```
---
## Key Methods
### toOAC()
Parse tool format → OpenAgent object
**Steps**: Parse source → Map fields → Validate with Zod → Return
---
### fromOAC()
Convert OpenAgent → tool format
**Steps**: Validate → Map fields → Detect unsupported features → Generate warnings → Create files
---
### getCapabilities()
Declare supported features
```typescript
{
supportsMultipleAgents: boolean
supportsSkills: boolean
supportsHooks: boolean
supportsGranularPermissions: boolean
supportsTemperature: boolean
}
```
---
## Utility Usage
```typescript
// Safe parsing
const config = this.safeParseJSON(content, 'config.json')
// Feature checks
if (this.supportsFeature('supportsTemperature')) {
config.temperature = agent.frontmatter.temperature
}
// Warnings
if (!this.supportsFeature('supportsHooks')) {
warnings.push(this.unsupportedFeatureWarning('hooks'))
}
// Results
return this.createSuccessResult([{ fileName: 'config.json', content }], warnings)
```
---
## Design Principles
1. **Template Method** - Base defines structure, subs fill details
2. **Pure toOAC/fromOAC** - Deterministic conversion
3. **Capabilities First** - Declare support upfront
4. **Graceful Degradation** - Warn, don't fail
5. **Validate Early** - Check before converting
---
## Testing Pattern
```typescript
describe('ClaudeAdapter', () => {
it('converts OAC to Claude', async () => {
const agent: OpenAgent = { /* ... */ }
const result = await adapter.fromOAC(agent)
expect(result.success).toBe(true)
expect(result.configs[0].fileName).toBe('.claude/config.json')
})
it('warns on unsupported temperature', async () => {
const agent: OpenAgent = { frontmatter: { temperature: 0.7 } }
const result = await adapter.fromOAC(agent)
expect(result.warnings).toContainEqual(
expect.stringContaining('temperature')
)
})
})
```
---
## Reference
- **Implementation**: `packages/compatibility-layer/src/adapters/BaseAdapter.ts`
- **Adapters**: `ClaudeAdapter.ts`, `CursorAdapter.ts`, `WindsurfAdapter.ts`
- **Related**:
- concepts/compatibility-layer.md
- examples/zod-schema-migration.md
- guides/compatibility-layer-workflow.md

View file

@ -0,0 +1,58 @@
# Code Formatting Hook
**Purpose**: Auto-format files after Claude edits them
---
## TypeScript/Prettier Hook
```json
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit|Write",
"hooks": [{
"type": "command",
"command": "jq -r '.tool_input.file_path' | { read file_path; if echo \"$file_path\" | grep -q '\\.ts$'; then npx prettier --write \"$file_path\"; fi; }"
}]
}]
}
}
```
---
## How It Works
1. Triggers after Edit or Write tool completes
2. Extracts file path from JSON input via jq
3. Checks if file is `.ts` extension
4. Runs prettier on matching files
---
## Variations
**Go files**:
```bash
if echo "$file_path" | grep -q '\\.go$'; then gofmt -w "$file_path"; fi
```
**Python files**:
```bash
if echo "$file_path" | grep -q '\\.py$'; then black "$file_path"; fi
```
**Multiple extensions**:
```bash
if echo "$file_path" | grep -qE '\\.(ts|tsx|js|jsx)$'; then npx prettier --write "$file_path"; fi
```
---
## Related
- `../../lookup/hook-events.md` - Hook events reference
- `./protection-hook.md` - File protection example
**Reference**: https://docs.anthropic.com/en/docs/claude-code/hooks

View file

@ -0,0 +1,85 @@
# Markdown Formatter Hook
**Purpose**: Auto-fix markdown formatting issues after file edits
---
## Configuration
```json
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit|Write",
"hooks": [{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/markdown_formatter.py"
}]
}]
}
}
```
---
## Python Script
```python
#!/usr/bin/env python3
import json, sys, re, os
def detect_language(code):
s = code.strip()
if re.search(r'^\s*[{\[]', s):
try:
json.loads(s)
return 'json'
except: pass
if re.search(r'^\s*def\s+\w+\s*\(', s, re.M):
return 'python'
if re.search(r'\b(function\s+\w+|const\s+\w+\s*=)', s):
return 'javascript'
if re.search(r'\b(SELECT|INSERT|UPDATE)\s+', s, re.I):
return 'sql'
return 'text'
def format_markdown(content):
def add_lang(match):
indent, info, body, closing = match.groups()
if not info.strip():
return f"{indent}```{detect_language(body)}\n{body}{closing}\n"
return match.group(0)
pattern = r'(?ms)^([ \t]{0,3})```([^\n]*)\n(.*?)(\n\1```)\s*$'
content = re.sub(pattern, add_lang, content)
return re.sub(r'\n{3,}', '\n\n', content).rstrip() + '\n'
# Main
data = json.load(sys.stdin)
path = data.get('tool_input', {}).get('file_path', '')
if path.endswith(('.md', '.mdx')) and os.path.exists(path):
with open(path, 'r') as f:
content = f.read()
formatted = format_markdown(content)
if formatted != content:
with open(path, 'w') as f:
f.write(formatted)
print(f"✓ Fixed formatting in {path}")
```
---
## What It Fixes
- Unlabeled code blocks → detects language
- Excessive blank lines → max 2 consecutive
- Trailing whitespace
---
## Related
- `../../lookup/hook-events.md` - Hook events
- `./formatting-hook.md` - Code formatting
**Reference**: https://docs.anthropic.com/en/docs/claude-code/hooks

View file

@ -0,0 +1,72 @@
# File Protection Hook
**Purpose**: Block edits to sensitive files
---
## Configuration
```json
{
"hooks": {
"PreToolUse": [{
"matcher": "Edit|Write",
"hooks": [{
"type": "command",
"command": "python3 -c \"import json, sys; data=json.load(sys.stdin); path=data.get('tool_input',{}).get('file_path',''); sys.exit(2 if any(p in path for p in ['.env', 'package-lock.json', '.git/']) else 0)\""
}]
}]
}
}
```
---
## How It Works
1. Triggers BEFORE Edit or Write tool executes
2. Reads file path from JSON input
3. Checks against protected patterns
4. Exit code 2 blocks the operation
5. Claude receives feedback about blocked file
---
## Protected Patterns
Default patterns to block:
- `.env` - Environment secrets
- `package-lock.json` - Dependency locks
- `.git/` - Git internals
- `credentials.json` - API keys
- `*.pem`, `*.key` - Private keys
---
## Custom Protection Script
```python
#!/usr/bin/env python3
import json, sys
PROTECTED = ['.env', 'package-lock.json', '.git/',
'credentials', '.pem', '.key', 'secrets']
data = json.load(sys.stdin)
path = data.get('tool_input', {}).get('file_path', '')
if any(p in path for p in PROTECTED):
print(f"Blocked: {path} is protected", file=sys.stderr)
sys.exit(2)
sys.exit(0)
```
---
## Related
- `../../lookup/hook-events.md` - Hook events reference
- `./formatting-hook.md` - Auto-format example
**Reference**: https://docs.anthropic.com/en/docs/claude-code/hooks

View file

@ -0,0 +1,79 @@
# Multi-File Skill Structure
**Purpose**: Example of a skill with supporting files and scripts
---
## Directory Structure
```
pdf-processing/
├── SKILL.md # Overview and quick start
├── FORMS.md # Form field mappings
├── REFERENCE.md # API details
└── scripts/
├── fill_form.py # Utility to populate forms
└── validate.py # Check PDFs for required fields
```
---
## SKILL.md
```yaml
---
name: pdf-processing
description: Extract text, fill forms, merge PDFs. Use when working with PDF files.
allowed-tools: Read, Bash(python:*)
---
# PDF Processing
## Quick start
Extract text:
```python
import pdfplumber
with pdfplumber.open("doc.pdf") as pdf:
text = pdf.pages[0].extract_text()
```
For form filling, see [FORMS.md](FORMS.md).
For detailed API reference, see [REFERENCE.md](REFERENCE.md).
## Requirements
```bash
pip install pypdf pdfplumber
```
```
---
## Key Patterns
1. **Keep SKILL.md concise** (<500 lines)
2. **Reference supporting files** with markdown links
3. **One level deep** - link directly, avoid nested references
4. **Scripts are executed, not loaded** - saves context tokens
---
## Script Usage
In SKILL.md, tell Claude to run (not read):
```markdown
Run the validation script:
python scripts/validate.py input.pdf
```
Output goes to Claude, script content stays out of context.
---
## Related
- `../concepts/agent-skills.md` - Skills overview
- `../../lookup/skill-metadata.md` - Metadata fields
**Reference**: https://docs.anthropic.com/en/docs/claude-code/skills

View file

@ -0,0 +1,70 @@
# Code Reviewer Subagent
**Purpose**: Read-only subagent example for code review
---
## Configuration
```yaml
---
name: code-reviewer
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.
tools: Read, Grep, Glob, Bash
model: inherit
---
You are a senior code reviewer ensuring high standards of code quality and security.
When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately
Review checklist:
- Code is clear and readable
- Functions and variables are well-named
- No duplicated code
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented
- Good test coverage
- Performance considerations addressed
Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)
Include specific examples of how to fix issues.
```
---
## Key Design Decisions
| Decision | Rationale |
|----------|-----------|
| No Edit/Write | Read-only ensures review doesn't modify code |
| `model: inherit` | Uses same model as main conversation |
| Bash included | Allows running git diff |
| Proactive description | Claude uses it automatically after code changes |
---
## Usage
```
Use the code-reviewer subagent to review my recent changes
```
Or Claude delegates automatically when code is modified.
---
## Related
- `./debugger.md` - Debugger subagent (with edit access)
- `../../guides/creating-subagents.md` - Creation guide
**Reference**: https://docs.anthropic.com/en/docs/claude-code/sub-agents

View file

@ -0,0 +1,84 @@
# DB Query Validator Subagent
**Purpose**: Subagent with conditional tool validation via hooks
---
## Configuration
```yaml
---
name: db-reader
description: Execute read-only database queries. Use when analyzing data or generating reports.
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
---
You are a database analyst with read-only access. Execute SELECT queries to answer questions about the data.
When asked to analyze data:
1. Identify which tables contain the relevant data
2. Write efficient SELECT queries with appropriate filters
3. Present results clearly with context
You cannot modify data. If asked to INSERT, UPDATE, DELETE, or modify schema, explain that you only have read access.
```
---
## Validation Script
```bash
#!/bin/bash
# ./scripts/validate-readonly-query.sh
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
if [ -z "$COMMAND" ]; then
exit 0
fi
# Block write operations (case-insensitive)
if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE|REPLACE|MERGE)\b' > /dev/null; then
echo "Blocked: Write operations not allowed. Use SELECT queries only." >&2
exit 2
fi
exit 0
```
Make executable: `chmod +x ./scripts/validate-readonly-query.sh`
---
## How It Works
1. Subagent has Bash access
2. PreToolUse hook intercepts every Bash command
3. Script checks for SQL write keywords
4. Exit 2 blocks operation, stderr fed to Claude
5. Exit 0 allows operation
---
## Key Pattern
Use hooks for **conditional validation** when:
- Tool access is needed but constrained
- Rules are dynamic/complex
- You need finer control than `tools` field provides
---
## Related
- `../../lookup/hook-events.md` - Hook reference
- `../../concepts/hooks-system.md` - Hooks overview
**Reference**: https://docs.anthropic.com/en/docs/claude-code/sub-agents

View file

@ -0,0 +1,77 @@
# Debugger Subagent
**Purpose**: Full-access subagent for debugging and fixing issues
---
## Configuration
```yaml
---
name: debugger
description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.
tools: Read, Edit, Bash, Grep, Glob
---
You are an expert debugger specializing in root cause analysis.
When invoked:
1. Capture error message and stack trace
2. Identify reproduction steps
3. Isolate the failure location
4. Implement minimal fix
5. Verify solution works
Debugging process:
- Analyze error messages and logs
- Check recent code changes
- Form and test hypotheses
- Add strategic debug logging
- Inspect variable states
For each issue, provide:
- Root cause explanation
- Evidence supporting the diagnosis
- Specific code fix
- Testing approach
- Prevention recommendations
Focus on fixing the underlying issue, not the symptoms.
```
---
## Key Design Decisions
| Decision | Rationale |
|----------|-----------|
| Edit included | Debugger needs to fix code |
| Model not specified | Defaults to Sonnet |
| Proactive description | Auto-triggers on errors |
---
## Comparison with Code Reviewer
| Aspect | Code Reviewer | Debugger |
|--------|---------------|----------|
| Edit access | ❌ No | ✓ Yes |
| Purpose | Review quality | Fix issues |
| Output | Feedback | Fixes |
---
## Usage
```
Use the debugger subagent to fix this failing test
```
---
## Related
- `./code-reviewer.md` - Read-only reviewer
- `./db-validator.md` - Constrained access example
**Reference**: https://docs.anthropic.com/en/docs/claude-code/sub-agents

View file

@ -0,0 +1,188 @@
# Example: Zod Schema Migration Pattern
**Purpose**: Migrate TypeScript definitions to runtime-validated Zod schemas
**Last Updated**: 2026-02-04
---
## Why Zod?
**Benefits**: Runtime validation + single source of truth + better error messages
---
## Basic Pattern
```typescript
// BEFORE: .d.ts interface
interface AgentFrontmatter {
name: string
mode: 'primary' | 'subagent' | 'all'
temperature?: number
}
// AFTER: Zod schema
import { z } from 'zod'
export const AgentFrontmatterSchema = z.object({
name: z.string(),
mode: z.enum(['primary', 'subagent', 'all']),
temperature: z.number().min(0).max(2).optional()
})
export type AgentFrontmatter = z.infer<typeof AgentFrontmatterSchema>
```
---
## Complex Schema
```typescript
// Granular permissions
export const GranularPermissionSchema = z.object({
allow: z.array(z.string()).optional(),
deny: z.array(z.string()).optional(),
ask: z.array(z.string()).optional()
})
export const PermissionRuleSchema = z.union([
z.literal('allow'),
z.literal('deny'),
z.boolean(),
GranularPermissionSchema
])
export const ToolAccessSchema = z.object({
read: PermissionRuleSchema.optional(),
write: PermissionRuleSchema.optional(),
bash: PermissionRuleSchema.optional()
})
export type ToolAccess = z.infer<typeof ToolAccessSchema>
```
---
## Validation Usage
```typescript
// Strict parsing (throws on invalid)
const frontmatter = AgentFrontmatterSchema.parse(data)
// Safe parsing (returns result object)
const result = AgentFrontmatterSchema.safeParse(data)
if (result.success) {
console.log(result.data) // Typed correctly
} else {
console.error(result.error.errors) // Detailed errors
}
```
---
## Common Patterns
### Enums
```typescript
export const ModeSchema = z.enum(['primary', 'subagent']).default('primary')
```
### Arrays
```typescript
export const SkillSchema = z.union([
z.string(), // "skill-name"
z.object({ name: z.string() }) // { name, config }
])
export const SkillsSchema = z.array(SkillSchema).optional()
```
### Records
```typescript
export const MetadataSchema = z.record(z.unknown()) // { [key: string]: any }
```
### Optionals
```typescript
z.string().optional() // string | undefined
z.number().default(0.7) // number with default
```
---
## Full Example: OpenAgent
```typescript
export const OpenAgentSchema = z.object({
frontmatter: AgentFrontmatterSchema,
metadata: AgentMetadataSchema.optional(),
systemPrompt: z.string(),
contexts: z.array(ContextReferenceSchema).optional()
})
export type OpenAgent = z.infer<typeof OpenAgentSchema>
```
---
## Migration Checklist
- [ ] `interface` → `z.object()`
- [ ] `type X = Y | Z` → `z.union([...])`
- [ ] `?` optional → `.optional()`
- [ ] Add constraints (`.min()`, `.max()`)
- [ ] Export schema AND type
- [ ] Test with valid/invalid data
---
## Testing
```typescript
describe('AgentFrontmatterSchema', () => {
it('validates correct data', () => {
expect(() => AgentFrontmatterSchema.parse({
name: 'TestAgent',
mode: 'primary'
})).not.toThrow()
})
it('rejects invalid mode', () => {
expect(() => AgentFrontmatterSchema.parse({
name: 'Test',
mode: 'invalid'
})).toThrow()
})
it('rejects out-of-range temperature', () => {
expect(() => AgentFrontmatterSchema.parse({
name: 'Test',
temperature: 5.0 // Max 2.0
})).toThrow()
})
})
```
---
## Key Schemas (Compatibility Layer)
**20+ schemas migrated**:
- `OpenAgentSchema` - Complete agent
- `AgentFrontmatterSchema` - YAML frontmatter
- `ToolAccessSchema` - Tool permissions
- `PermissionRuleSchema` - Permission types
- `SkillReferenceSchema` - Skill definitions
- `HookDefinitionSchema` - Hook configs
---
## Reference
- **Implementation**: `packages/compatibility-layer/src/types.ts` (315 lines)
- **Original**: `packages/compatibility-layer/dist/src/types.d.ts` (679 lines)
- **Zod Docs**: https://zod.dev
- **Related**:
- examples/baseadapter-pattern.md
- concepts/compatibility-layer.md

View file

@ -0,0 +1,154 @@
# Guide: Adding a New Agent (Basics)
**Prerequisites**: Load `core-concepts/agents.md` first
**Purpose**: Create and register a new agent in 4 steps
---
## Overview
Adding a new agent involves:
1. Creating the agent file
2. Creating test structure
3. Updating the registry
4. Validating everything works
**Time**: ~15-20 minutes
---
## Step 1: Create Agent File
### Choose Category
```bash
# Available categories:
# - core/ (system agents)
# - development/ (dev specialists)
# - content/ (content creators)
# - data/ (data analysts)
# - product/ (product managers)
# - learning/ (educators)
```
### Create File with Frontmatter
```bash
touch .opencode/agent/{category}/{agent-name}.md
```
```markdown
---
description: "Brief description of what this agent does"
category: "{category}"
type: "agent"
tags: ["tag1", "tag2"]
dependencies: []
---
# Agent Name
**Purpose**: What this agent does
## Focus
- Key responsibility 1
- Key responsibility 2
## Workflow
1. Step 1
2. Step 2
## Constraints
- Constraint 1
- Constraint 2
```
---
## Step 2: Create Test Structure
```bash
# Create directories
mkdir -p evals/agents/{category}/{agent-name}/{config,tests}
# Create config
cat > evals/agents/{category}/{agent-name}/config/config.yaml << 'EOF'
agent: {category}/{agent-name}
model: anthropic/claude-sonnet-4-5
timeout: 60000
suites:
- smoke
EOF
# Create smoke test
cat > evals/agents/{category}/{agent-name}/tests/smoke-test.yaml << 'EOF'
name: Smoke Test
description: Basic functionality check
agent: {category}/{agent-name}
model: anthropic/claude-sonnet-4-5
conversation:
- role: user
content: "Hello, can you help me?"
expectations:
- type: no_violations
EOF
```
---
## Step 3: Update Registry
```bash
# Dry run first
./scripts/registry/auto-detect-components.sh --dry-run
# Add to registry
./scripts/registry/auto-detect-components.sh --auto-add
# Verify
cat registry.json | jq '.components.agents[] | select(.id == "{agent-name}")'
```
---
## Step 4: Validate
```bash
# Validate registry
./scripts/registry/validate-registry.sh
# Run smoke test
cd evals/framework
npm run eval:sdk -- --agent={category}/{agent-name} --pattern="smoke-test.yaml"
# Test installation
REGISTRY_URL="file://$(pwd)/registry.json" ./install.sh --list
```
---
## Checklist
- [ ] Agent file created with proper frontmatter
- [ ] Test structure created (config + smoke test)
- [ ] Registry updated via auto-detect
- [ ] Registry validation passes
- [ ] Smoke test passes
- [ ] Agent appears in `./install.sh --list`
---
## Next Steps
- **Add more tests** → `adding-agent-testing.md`
- **Test thoroughly** → `testing-agent.md`
- **Debug issues** → `debugging.md`
---
## Related
- `core-concepts/agents.md` - Agent concepts
- `adding-agent-testing.md` - Additional test patterns
- `testing-agent.md` - Testing guide
- `creating-subagents.md` - Claude Code subagents (different system)

View file

@ -0,0 +1,143 @@
# Guide: Adding Agent Tests
**Prerequisites**: Load `adding-agent-basics.md` first
**Purpose**: Additional test patterns for agents
---
## Additional Test Types
### Approval Gate Test
```yaml
# evals/agents/{category}/{agent-name}/tests/approval-gate.yaml
name: Approval Gate Test
description: Verify agent requests approval before execution
agent: {category}/{agent-name}
model: anthropic/claude-sonnet-4-5
conversation:
- role: user
content: "Create a new file called test.js"
expectations:
- type: specific_evaluator
evaluator: approval_gate
should_pass: true
```
### Context Loading Test
```yaml
# evals/agents/{category}/{agent-name}/tests/context-loading.yaml
name: Context Loading Test
description: Verify agent loads required context
agent: {category}/{agent-name}
model: anthropic/claude-sonnet-4-5
conversation:
- role: user
content: "Write a new function"
expectations:
- type: context_loaded
contexts: ["core/standards/code-quality.md"]
```
---
## Complete Example: API Specialist
```bash
# 1. Create agent file
cat > .opencode/agent/development/api-specialist.md << 'EOF'
---
description: "Expert in REST and GraphQL API design"
category: "development"
type: "agent"
tags: ["api", "rest", "graphql"]
dependencies: ["subagent:tester"]
---
# API Specialist
**Purpose**: Design and implement robust APIs
## Focus
- REST API design
- GraphQL schemas
- API documentation
- Authentication/authorization
## Workflow
1. Analyze requirements
2. Design API structure
3. Implement endpoints
4. Add tests
5. Document API
## Constraints
- Follow REST best practices
- Use proper HTTP methods
- Include error handling
- Add comprehensive tests
EOF
# 2. Create test structure
mkdir -p evals/agents/development/api-specialist/{config,tests}
cat > evals/agents/development/api-specialist/config/config.yaml << 'EOF'
agent: development/api-specialist
model: anthropic/claude-sonnet-4-5
timeout: 60000
suites:
- smoke
EOF
cat > evals/agents/development/api-specialist/tests/smoke-test.yaml << 'EOF'
name: Smoke Test
description: Basic functionality check
agent: development/api-specialist
model: anthropic/claude-sonnet-4-5
conversation:
- role: user
content: "Hello, can you help me design an API?"
expectations:
- type: no_violations
EOF
# 3. Update registry
./scripts/registry/auto-detect-components.sh --auto-add
# 4. Validate
./scripts/registry/validate-registry.sh
cd evals/framework && npm run eval:sdk -- --agent=development/api-specialist --pattern="smoke-test.yaml"
```
---
## Common Issues
| Problem | Solution |
|---------|----------|
| Auto-detect doesn't find agent | Check frontmatter is valid YAML |
| Registry validation fails | Verify file path is correct |
| Test fails unexpectedly | Load `debugging.md` for troubleshooting |
---
## Claude Code Subagent (Optional)
For Claude Code-only helpers, create a project subagent:
- **Path**: `.claude/agents/{subagent-name}.md`
- **Required**: `name`, `description` frontmatter
- **Optional**: `tools`, `disallowedTools`, `permissionMode`, `skills`, `hooks`
- **Reload**: restart Claude Code or run `/agents`
See `creating-subagents.md` for Claude Code subagent details.
---
## Related
- `adding-agent-basics.md` - Basic agent creation
- `testing-agent.md` - Testing guide
- `debugging.md` - Troubleshooting
- `creating-subagents.md` - Claude Code subagents

View file

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

View file

@ -0,0 +1,147 @@
# Guide: Adding an OpenCode Skill (Basics)
**Prerequisites**: Load `plugins/context/capabilities/events_skills.md` first
**Purpose**: Create an OpenCode skill directory and SKILL.md file
**Note**: This is for **OpenCode skills** (internal system). For **Claude Code Skills**, see `creating-skills.md`.
---
## Overview
Adding an OpenCode skill involves:
1. Creating skill directory structure
2. Creating SKILL.md file
3. Creating router script (optional)
4. Creating CLI implementation (optional)
5. Registering in registry (optional)
6. Testing
**Time**: ~10-15 minutes
---
## Step 1: Create Skill Directory
### Choose Skill Name
- **kebab-case**: `task-management`, `brand-guidelines`
- **Descriptive**: Clear indication of what skill provides
- **Short**: Max 3-4 words
### Create Structure
```bash
mkdir -p .opencode/skill/{skill-name}/scripts
```
**Standard structure**:
```
.opencode/skill/{skill-name}/
├── SKILL.md # Required: Main skill documentation
├── router.sh # Optional: CLI router script
└── scripts/
└── skill-cli.ts # Optional: CLI tool implementation
```
---
## Step 2: Create SKILL.md
### Frontmatter
```markdown
---
name: {skill-name}
description: Brief description of what the skill provides
---
# Skill Name
**Purpose**: What this skill helps users do
## What I do
- Feature 1
- Feature 2
- Feature 3
## How to use me
### Basic Commands
```bash
npx ts-node .opencode/skill/{skill-name}/scripts/skill-cli.ts command1
```
### Command Reference
| Command | Description |
|---------|-------------|
| `command1` | What command1 does |
| `command2` | What command2 does |
```
### Claude Code Skills (Optional)
For Claude Code Skills (`.claude/skills/`), add extra frontmatter:
- `allowed-tools` - Tool restrictions
- `context` + `agent` - Run in forked subagent
- `hooks` - Lifecycle events
- `user-invocable` - Hide from slash menu
See `creating-skills.md` for Claude Code Skills details.
---
## Step 3: Create Router Script (Optional)
For CLI-based skills:
```bash
#!/bin/bash
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [ $# -eq 0 ]; then
echo "Usage: bash router.sh <command> [options]"
exit 1
fi
COMMAND="$1"
shift
case "$COMMAND" in
help|--help|-h)
echo "{Skill Name} - Description"
echo "Commands: command1, command2, help"
;;
command1|command2)
npx ts-node "$SCRIPT_DIR/scripts/skill-cli.ts" "$COMMAND" "$@"
;;
*)
echo "Unknown command: $COMMAND"
exit 1
;;
esac
```
```bash
chmod +x .opencode/skill/{skill-name}/router.sh
```
---
## Next Steps
- **CLI Implementation** → `adding-skill-implementation.md`
- **Complete Example** → `adding-skill-example.md`
- **Claude Code Skills** → `creating-skills.md`
---
## Related
- `creating-skills.md` - Claude Code Skills (different system)
- `adding-skill-implementation.md` - CLI and registry
- `adding-skill-example.md` - Task-management example
- `plugins/context/capabilities/events_skills.md` - Skills Plugin

View file

@ -0,0 +1,167 @@
# Example: Task-Management Skill
**Purpose**: Complete example of creating an OpenCode skill
---
## Directory Structure
```bash
mkdir -p .opencode/skill/task-management/scripts
```
```
.opencode/skill/task-management/
├── SKILL.md
├── router.sh
└── scripts/
└── task-cli.ts
```
---
## SKILL.md
```markdown
---
name: task-management
description: Task management CLI for tracking feature subtasks
---
# Task Management Skill
**Purpose**: Track and manage feature subtasks
## What I do
- Track task progress
- Show next eligible tasks
- Identify blocked tasks
- Mark completion
- Validate task integrity
## Usage
```bash
# Show all task statuses
npx ts-node .opencode/skill/task-management/scripts/task-cli.ts status
# Show next eligible tasks
npx ts-node .opencode/skill/task-management/scripts/task-cli.ts next
# Mark complete
npx ts-node .opencode/skill/task-management/scripts/task-cli.ts complete <feature> <seq> "summary"
```
```
---
## router.sh
```bash
#!/bin/bash
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
case "$1" in
help|--help|-h)
echo "Task Management Skill"
echo "Usage: bash router.sh <command>"
echo "Commands: status, next, blocked, complete, validate"
;;
status|next|blocked|validate)
npx ts-node "$SCRIPT_DIR/scripts/task-cli.ts" "$@"
;;
complete)
npx ts-node "$SCRIPT_DIR/scripts/task-cli.ts" "$@"
;;
*)
echo "Unknown command: $1"
bash "$0" help
;;
esac
```
---
## task-cli.ts (Excerpt)
```typescript
#!/usr/bin/env ts-node
interface Task {
id: string
status: 'pending' | 'in_progress' | 'completed'
title: string
}
async function main() {
const command = process.argv[2] || 'help'
switch (command) {
case 'status':
await showStatus()
break
case 'next':
await showNext()
break
case 'complete':
const [, , , feature, seq, summary] = process.argv
await markComplete(feature, seq, summary)
break
default:
showHelp()
}
}
async function showStatus() {
// Implementation
console.log('Task status...')
}
async function showNext() {
// Implementation
console.log('Next tasks...')
}
async function markComplete(feature: string, seq: string, summary: string) {
// Implementation
console.log(`Completing ${feature} ${seq}: ${summary}`)
}
function showHelp() {
console.log(`
Task Management CLI
Commands:
status Show all task statuses
next Show next eligible tasks
blocked Show blocked tasks
complete <f> <s> Mark task complete
validate Validate task integrity
`)
}
main().catch(console.error)
```
---
## Integration with Agents
Skills integrate with agents via:
- Event hooks (`tool.execute.before`, `tool.execute.after`)
- Skill content injection into conversation
- Output enhancement
Example agent prompt invoking skill:
```
Use the task-management skill to show current task status
```
---
## Related
- `adding-skill-basics.md` - Directory and SKILL.md setup
- `adding-skill-implementation.md` - CLI and registry
- `plugins/context/capabilities/events_skills.md` - Skills Plugin

View file

@ -0,0 +1,167 @@
# Guide: OpenCode Skill Implementation
**Prerequisites**: Load `adding-skill-basics.md` first
**Purpose**: CLI implementation, registry, and testing for OpenCode skills
---
## CLI Implementation
### Basic Structure
```typescript
#!/usr/bin/env ts-node
// CLI implementation for {skill-name} skill
interface Args {
command: string
[key: string]: any
}
async function main() {
const args = parseArgs()
switch (args.command) {
case 'command1':
await handleCommand1(args)
break
case 'command2':
await handleCommand2(args)
break
case 'help':
default:
showHelp()
}
}
function parseArgs(): Args {
const args = process.argv.slice(2)
return {
command: args[0] || 'help',
...parseOptions(args.slice(1))
}
}
async function handleCommand1(args: Args) {
console.log('Running command1...')
}
function showHelp() {
console.log(`
{Skill Name}
Usage: npx ts-node scripts/skill-cli.ts <command> [options]
Commands:
command1 Description
command2 Description
help Show this help
`)
}
main().catch(console.error)
```
---
## Register in Registry (Optional)
### Add to Components
```json
{
"skills": [
{
"id": "{skill-name}",
"name": "Skill Name",
"type": "skill",
"path": ".opencode/skill/{skill-name}/SKILL.md",
"description": "Brief description",
"tags": ["tag1", "tag2"],
"dependencies": []
}
]
}
```
### Add to Profiles
```json
{
"profiles": {
"essential": {
"components": [
"skill:{skill-name}"
]
}
}
}
```
---
## Testing
### Test CLI Commands
```bash
# Test help
bash .opencode/skill/{skill-name}/router.sh help
# Test commands
bash .opencode/skill/{skill-name}/router.sh command1 --option value
# Test with npx
npx ts-node .opencode/skill/{skill-name}/scripts/skill-cli.ts help
```
### Test OpenCode Integration
1. Call skill via OpenCode
2. Verify event hooks fire correctly
3. Check conversation history for skill content
4. Verify output enhancement works
---
## Best Practices
### Keep Skills Focused
- ✅ Task management skill → Tracks tasks
- ❌ Task management + code generation + testing → Too broad
### Clear Documentation
- Provide usage examples
- Document all commands
- Include expected outputs
### Error Handling
- Handle missing arguments gracefully
- Provide helpful error messages
- Validate inputs before processing
### Performance
- Use efficient algorithms
- Cache when appropriate
- Avoid unnecessary file operations
---
## Checklist
- [ ] `.opencode/skill/{skill-name}/SKILL.md` created
- [ ] `.opencode/skill/{skill-name}/router.sh` created (if CLI-based)
- [ ] Router script is executable (`chmod +x`)
- [ ] Registry updated (if needed)
- [ ] Profile updated (if needed)
- [ ] All commands tested
- [ ] Documentation complete
---
## Related
- `adding-skill-basics.md` - Directory and SKILL.md setup
- `adding-skill-example.md` - Complete example
- `creating-skills.md` - Claude Code Skills
- `plugins/context/capabilities/events_skills.md` - Skills Plugin

View file

@ -1,456 +0,0 @@
# Guide: Adding a New Skill
**Prerequisites**: Load `plugins/context/capabilities/events_skills.md` first
**Purpose**: Step-by-step workflow for adding a new skill
**Related**: See `plugins/context/architecture/overview.md` for plugin concepts
---
## Overview
Adding a new skill involves:
1. Creating the skill directory structure
2. Creating the SKILL.md file
3. Creating the router script (for CLI-based skills)
4. Creating skill content/scripts
5. Registering the skill (if needed)
6. Testing the skill
**Time**: ~10-15 minutes
---
## Step 1: Create Skill Directory
### Choose Skill Name
Skill names should be:
- **kebab-case**: `task-management`, `brand-guidelines`, `api-reference`
- **Descriptive**: Clear indication of what the skill provides
- **Short**: Avoid overly long names (max 3-4 words)
### Create Directory Structure
```bash
# Create skill directory
mkdir -p .opencode/skill/{skill-name}
# Create subdirectories as needed
mkdir -p .opencode/skill/{skill-name}/scripts
```
### Standard Skill Structure
```
.opencode/skill/{skill-name}/
├── SKILL.md # Required: Main skill documentation
├── router.sh # Optional: CLI router script
└── scripts/
└── skill-cli.ts # Optional: CLI tool implementation
```
---
## Step 2: Create SKILL.md
The SKILL.md file is required and provides skill documentation and integration details.
### Optional: Claude Code Skills
Claude Code Skills live in `.claude/skills/{skill-name}/SKILL.md` and support extra frontmatter:
- `allowed-tools` for tool restrictions
- `context` + `agent` to run in a forked subagent
- `hooks` for lifecycle events
- `user-invocable` to hide from slash menu
Keep descriptions keyword-rich so auto-discovery triggers reliably. See `../to-be-consumed/claude-code-docs/agent-skills.md` for full details.
### SKILL.md Frontmatter
```markdown
---
name: {skill-name}
description: Brief description of what the skill provides
---
# Skill Name
**Purpose**: What this skill helps users do
## What I do
- Feature 1
- Feature 2
- Feature 3
## How to use me
### Basic Commands
```bash
# Example command 1
npx ts-node .opencode/skill/{skill-name}/scripts/skill-cli.ts command1
# Example command 2
npx ts-node .opencode/skill/{skill-name}/scripts/skill-cli.ts command2
```
### Command Reference
| Command | Description |
|---------|-------------|
| `command1` | What command1 does |
| `command2` | What command2 does |
## Examples
### Example 1
```
$ npx ts-node .opencode/skill/{skill-name}/scripts/skill-cli.ts example
Expected output or behavior
```
## Architecture
```
.opencode/
└── skill/
└── {skill-name}/
├── SKILL.md # This file
├── router.sh # CLI router
└── scripts/
└── skill-cli.ts # CLI implementation
```
## Integration
### With Agents
This skill integrates with agents by:
- Description of how agents use the skill
- Example agent prompt that invokes the skill
### With OpenCode Events
The skill uses OpenCode event hooks:
- `tool.execute.before` - For [what it does]
- `tool.execute.after` - For [what it does]
---
## Step 3: Create Router Script (Optional)
For CLI-based skills, create a router.sh script:
```bash
#!/bin/bash
# Router script for {skill-name} skill
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Default to help if no arguments
if [ $# -eq 0 ]; then
echo "Usage: bash router.sh <command> [options]"
echo "Run 'bash router.sh help' for more information"
exit 1
fi
COMMAND="$1"
shift
# Route to appropriate script
case "$COMMAND" in
help|--help|-h)
echo "{Skill Name} - Skill Description"
echo ""
echo "Usage: bash router.sh <command> [options]"
echo ""
echo "Commands:"
echo " command1 Description of command1"
echo " command2 Description of command2"
echo " help Show this help message"
;;
command1)
npx ts-node "$SCRIPT_DIR/scripts/skill-cli.ts" command1 "$@"
;;
command2)
npx ts-node "$SCRIPT_DIR/scripts/skill-cli.ts" command2 "$@"
;;
*)
echo "Unknown command: $COMMAND"
echo "Run 'bash router.sh help' for available commands"
exit 1
;;
esac
```
### Make Router Executable
```bash
chmod +x .opencode/skill/{skill-name}/router.sh
```
---
## Step 4: Create CLI Implementation
### Basic CLI Structure
```typescript
#!/usr/bin/env ts-node
// CLI implementation for {skill-name} skill
interface Args {
command: string
[key: string]: any
}
async function main() {
const args = parseArgs()
switch (args.command) {
case 'command1':
await handleCommand1(args)
break
case 'command2':
await handleCommand2(args)
break
case 'help':
default:
showHelp()
}
}
function parseArgs(): Args {
const args = process.argv.slice(2)
return {
command: args[0] || 'help',
...parseOptions(args.slice(1))
}
}
async function handleCommand1(args: Args) {
// Implementation
console.log('Running command1...')
}
function showHelp() {
console.log(`
{ Skill Name }
Usage: npx ts-node scripts/skill-cli.ts <command> [options]
Commands:
command1 Description of command1
command2 Description of command2
help Show this help message
Options:
--option1 Description of option1
--option2 Description of option2
`)
}
main().catch(console.error)
```
---
## Step 5: Register in Registry (Optional)
If the skill should be included in profiles, add it to `registry.json`:
### Add to Components
```json
{
"skills": [
{
"id": "{skill-name}",
"name": "Skill Name",
"type": "skill",
"path": ".opencode/skill/{skill-name}/SKILL.md",
"description": "Brief description",
"tags": ["tag1", "tag2"],
"dependencies": []
}
]
}
```
### Add to Profiles
```json
{
"profiles": {
"essential": {
"components": [
"skill:{skill-name}"
]
}
}
}
```
---
## Step 6: Test the Skill
### Test CLI Commands
```bash
# Test help
bash .opencode/skill/{skill-name}/router.sh help
# Test command1
bash .opencode/skill/{skill-name}/router.sh command1 --option value
# Test with npx
npx ts-node .opencode/skill/{skill-name}/scripts/skill-cli.ts help
```
### Test OpenCode Integration
If the skill uses OpenCode events:
1. Call the skill via OpenCode
2. Verify event hooks fire correctly
3. Check conversation history for skill content injection
4. Verify output enhancement works
---
## Example: Creating Task-Management Skill
### Directory Creation
```bash
mkdir -p .opencode/skill/task-management/scripts
```
### SKILL.md
```markdown
---
name: task-management
description: Task management CLI for tracking feature subtasks
---
# Task Management Skill
**Purpose**: Track and manage feature subtasks
## What I do
- Track task progress
- Show next eligible tasks
- Identify blocked tasks
- Mark completion
- Validate task integrity
## Usage
```bash
# Show all task statuses
npx ts-node .opencode/skill/task-management/scripts/task-cli.ts status
# Show next eligible tasks
npx ts-node .opencode/skill/task-management/scripts/task-cli.ts next
# Mark complete
npx ts-node .opencode/skill/task-management/scripts/task-cli.ts complete <feature> <seq> "summary"
```
### router.sh
```bash
#!/bin/bash
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
case "$1" in
help|--help|-h)
echo "Task Management Skill"
echo "Usage: bash router.sh <command>"
echo "Commands: status, next, blocked, complete, validate"
;;
status|next|blocked|validate)
npx ts-node "$SCRIPT_DIR/scripts/task-cli.ts" "$@"
;;
complete)
npx ts-node "$SCRIPT_DIR/scripts/task-cli.ts" "$@"
;;
*)
echo "Unknown command: $1"
bash router.sh help
;;
esac
```
---
## Best Practices
### 1. Keep Skills Focused
Each skill should do one thing well:
- ✅ Task management skill → Tracks tasks
- ❌ Task management + code generation + testing → Too broad
### 2. Clear Documentation
- Provide usage examples
- Document all commands
- Include expected outputs
- Explain integration points
### 3. Error Handling
- Handle missing arguments gracefully
- Provide helpful error messages
- Validate inputs before processing
### 4. Performance
- Use efficient algorithms
- Cache when appropriate
- Avoid unnecessary file operations
### 5. Testing
- Test all commands
- Test error conditions
- Verify integration with OpenCode
---
## Quick Reference
### File Checklist
- [ ] `.opencode/skill/{skill-name}/SKILL.md` created
- [ ] `.opencode/skill/{skill-name}/router.sh` created (if CLI-based)
- [ ] `.opencode/skill/{skill-name}/scripts/skill-cli.ts` created (if CLI-based)
- [ ] Router script is executable (`chmod +x`)
- [ ] Registry updated (if needed)
- [ ] Profile updated (if needed)
- [ ] All commands tested
- [ ] Documentation complete
### Command Reference
| Command | Purpose |
|---------|---------|
| `mkdir -p .opencode/skill/{name}` | Create skill directory |
| `chmod +x router.sh` | Make router executable |
| `npx ts-node scripts/cli.ts help` | Test CLI help |
---
## Related Documentation
- **Skills Plugin**: `plugins/context/capabilities/events_skills.md`
- **Plugin Overview**: `plugins/context/architecture/overview.md`
- **Event System**: `plugins/context/capabilities/events.md`
- **Adding Agents**: `guides/adding-agent.md`
- **Claude Code Skills**: `../to-be-consumed/claude-code-docs/agent-skills.md`

View file

@ -0,0 +1,165 @@
# Guide: Compatibility Layer Development Workflow
**Purpose**: Step-by-step workflow for developing compatibility layer features
**Last Updated**: 2026-02-04
---
## Core Workflow
Development follows a structured 6-stage approach:
```
1. Discover (Context)
↓
2. Propose (Approval)
↓
3. Init Session (Setup)
↓
4. Plan (Breakdown)
↓
5. Execute (Implement)
↓
6. Validate & Handoff
```
---
## Stage 1: Discover
**Goal**: Understand requirements before implementation
**Actions**:
1. Use `ContextScout` to discover relevant context files
2. For external packages: Check install scripts first, then use `ExternalScout`
3. Read context standards (code-quality.md is MANDATORY)
**No files created** - Read-only exploration
---
## Stage 2: Propose
**Goal**: Get user approval BEFORE any file creation
**Present lightweight summary**:
- What we're building (1-2 sentences)
- Components list
- Approach (direct execution vs delegation)
- Context discovered
**Wait for user approval** before proceeding
---
## Stage 3: Init Session
**Goal**: Create session and persist context (ONLY after approval)
**Actions**:
1. Create session directory: `.tmp/sessions/{YYYY-MM-DD}-{task-slug}/`
2. Write `context.md` with:
- Task requirements
- Context files (standards to follow)
- Reference files (source material)
- Components
- Exit criteria
**This becomes single source of truth for all agents**
---
## Stage 4: Plan
**Decision**: Simple vs Complex?
**Simple** (1-3 files, <30min):
- Skip TaskManager
- Execute directly in Stage 5
**Complex** (4+ files, >60min):
- Delegate to `TaskManager`
- Creates `.tmp/tasks/{feature}/task.json` + subtasks
- Present plan for confirmation
---
## Stage 5: Execute
**Incremental approach** (one component at a time):
1. **Plan Component** (if using component-planning):
- Create `component-{name}.md`
- Request approval for design
2. **Execute**:
- Load context from session
- Implement → Validate → Mark complete
- If delegating: Pass subtask JSON to `CoderAgent`
3. **Integrate**:
- Verify integration with previous components
**Critical**: Never implement entire plan at once
---
## Stage 6: Validate & Handoff
**Actions**:
1. Run full system integration tests
2. Delegate to `TestEngineer` or `CodeReviewer` (pass session context)
3. Summarize what was built
4. Ask user to clean up `.tmp` files
---
## Key Principles
**Context First**: Load standards BEFORE coding
**Approval Gates**: Never execute without approval
**Incremental**: One step at a time, validate each
**Stop on Failure**: Report → Propose fix → Request approval → Then fix
---
## Example: Adapter Implementation
```
1. Discover:
- ContextScout finds baseadapter-pattern.md
- Load code-quality.md standards
2. Propose:
"Implement WindsurfAdapter (514 lines)
- Bidirectional conversion
- Extends BaseAdapter
- JSON config format"
3. Init Session:
Create .tmp/sessions/2026-02-04-windsurf-adapter/
Write context.md with standards + references
4. Plan:
Simple (1 file) → Skip TaskManager
5. Execute:
- Create WindsurfAdapter.ts
- Implement toOAC(), fromOAC()
- Export in index.ts
- npm run build (validate)
6. Validate:
- Compilation: ✅ 0 errors
- Ready for unit tests (next phase)
```
---
## Reference
**Related**:
- standards/code-quality.md (MANDATORY before coding)
- concepts/compatibility-layer.md
- examples/baseadapter-implementation.md

View file

@ -0,0 +1,212 @@
# Guide: Compatibility Layer Development Workflow
**Purpose**: Step-by-step process for extending the compatibility layer to support new AI coding tools
**Last Updated**: 2026-02-05
---
## When to Use This Guide
- Adding support for a new AI coding tool (e.g., Codeium, GitHub Copilot)
- Extending existing adapter capabilities
- Understanding the development phases for compatibility work
---
## Development Phases
### Phase 1: Foundation ✅ COMPLETE
**Objective**: Set up project infrastructure and core types
1. **Project Setup** (1.5h) ✅
- Create `packages/compatibility-layer/package.json`
- Configure TypeScript with strict mode
- Set up Vitest with 80%+ coverage thresholds
2. **Type System** (1.5h) ✅
- Create `src/types.ts` with Zod schemas
- Define `OpenAgentSchema`, `AgentFrontmatterSchema`
- Export TypeScript types with `z.infer<>`
3. **Base Adapter** (1.5h) ✅
- Create `src/adapters/BaseAdapter.ts` abstract class
- Define abstract methods: `toOAC()`, `fromOAC()`, `getCapabilities()`
4. **Agent Loader** (1.5h) ✅
- Create `src/core/AgentLoader.ts`
- Use gray-matter for YAML frontmatter parsing
5. **Adapter Registry** (1h) ✅
- Create `src/core/AdapterRegistry.ts`
- Implement registry pattern with `Map<string, BaseAdapter>`
6. **Public API** (1h) ✅
- Create `src/index.ts`
- Export all public APIs
**Result**: 1,475 lines TypeScript, 0 compilation errors
---
### Phase 2: Adapter Migration ✅ COMPLETE
**Objective**: Migrate existing adapters to TypeScript
7. **Claude Adapter** (3h) ✅ - 600 lines
8. **Cursor Adapter** (3h) ✅ - 554 lines
9. **Windsurf Adapter** (3h) ✅ - 514 lines
10. **ClaudeAdapter Tests** ✅ - 80 tests, 96% coverage
11. **CursorAdapter Tests** ✅ - 78 tests, 99% coverage
12. **WindsurfAdapter Tests** ✅ - 78 tests, 99% coverage
**Result**: 1,858 lines TypeScript, 236 tests passing
---
### Phase 3: Mappers & Translation ✅ COMPLETE
**Objective**: Implement feature mapping logic
13. **Tool Mapper** ✅ - 308 lines, 34 tests, 100% coverage
14. **Permission Mapper** ✅ - 354 lines, 37 tests, 98% coverage
15. **Model Mapper** ✅ - 413 lines, 37 tests, 99% coverage
16. **Context Mapper** ✅ - 384 lines, 51 tests, 97% coverage
17. **Capability Matrix** ✅ - 559 lines, 43 tests, 99% coverage
18. **Translation Engine** ✅ - 453 lines, 47 tests, 99% coverage
19. **Mapper Tests** ✅ - 249 tests total
**Result**: 2,471 lines TypeScript, 249 tests passing
---
### Phase 4: CLI Tool ⬅️ NEXT
**Objective**: Build command-line interface
20. **CLI Scaffolding** (1.5h)
- Create `src/cli/index.ts` with Commander.js
- Define commands: convert, validate, migrate, info
- Set up chalk for colored output, ora for spinners
21. **Convert Command** (2h)
- Implement `commands/convert.ts`
- Usage: `oac-compat convert --from oac --to claude agent.md`
- Support batch conversion
22. **Validate Command** (1.5h)
- Implement `commands/validate.ts`
- Check compatibility before conversion
- Report warnings and incompatibilities
23. **Migrate Command** (2h)
- Implement `commands/migrate.ts`
- Migrate entire projects (all agents + context)
- Generate migration report
24. **Info Command** (1h)
- Implement `commands/info.ts`
- Show tool capabilities and feature matrices
- Display adapter list
25. **CLI Integration Tests** (2h)
- Test each command end-to-end
- Test error handling
- Test output formatting
---
### Phase 5: Documentation
**Objective**: Create migration guides and API docs
26-30. **Migration Guides** (4h total)
- `docs/migration-guides/cursor-to-oac.md`
- `docs/migration-guides/claude-to-oac.md`
- `docs/migration-guides/oac-to-cursor.md`
- `docs/migration-guides/oac-to-claude.md`
- `docs/migration-guides/oac-to-windsurf.md`
31. **Feature Matrices** (1h)
- Generate comparison tables
- Document degradation patterns
32. **API Documentation** (1h)
- Document programmatic API usage
- Add examples for each adapter
---
## Adding a New Tool Adapter
### Step-by-Step
1. **Research Tool Format**
- Study tool's configuration file structure
- Identify supported features
- Note limitations vs OAC
2. **Create Adapter Class**
```typescript
export class NewToolAdapter extends BaseAdapter {
name = 'newtool'
displayName = 'New Tool'
async toOAC(source: string): Promise<OpenAgent> { /* ... */ }
async fromOAC(agent: OpenAgent): Promise<ConversionResult> { /* ... */ }
getConfigPath(): string { /* ... */ }
getCapabilities(): ToolCapabilities { /* ... */ }
validateConversion(agent: OpenAgent): string[] { /* ... */ }
}
```
3. **Use Existing Mappers**
- ToolMapper for tool name translation
- PermissionMapper for permission translation
- ModelMapper for model ID translation
- ContextMapper for context path translation
4. **Register Adapter**
```typescript
AdapterRegistry.register(new NewToolAdapter())
```
5. **Write Tests** (Target: 80%+ coverage)
6. **Update Documentation**
---
## Success Criteria
**Phase 1-3** ✅ ACHIEVED:
- [x] All files compile without errors
- [x] Zod schemas validate correctly
- [x] All 3 adapters migrated to TypeScript
- [x] Unit tests pass with 80%+ coverage
- [x] All mappers are pure functions
- [x] Graceful degradation works
**Phase 4** (upcoming):
- [ ] CLI commands work end-to-end
- [ ] Error handling is comprehensive
- [ ] Output is user-friendly
**Phase 5** (upcoming):
- [ ] Migration guides cover all tools
- [ ] API docs are complete
- [ ] Examples demonstrate usage
---
## Reference
- **Issue**: https://github.com/darrenhinde/OpenAgentsControl/issues/141
- **Branch**: `devalexanderdaza/issue141`
- **Location**: `packages/compatibility-layer/`
**Related**:
- lookup/compatibility-layer-progress.md
- lookup/compatibility-layer-adapters.md
- lookup/compatibility-layer-structure.md

View file

@ -0,0 +1,81 @@
# Creating Skills
**Purpose**: Step-by-step guide to create Agent Skills
---
## Quickstart
1. **Create directory**:
```bash
mkdir -p ~/.claude/skills/my-skill
```
2. **Create SKILL.md** with frontmatter:
```yaml
---
name: my-skill
description: What it does and when to use it
---
Instructions for Claude...
```
3. **Verify**: Ask Claude "What Skills are available?"
4. **Test**: Ask Claude something matching the description
---
## Writing Good Descriptions
The description determines when Claude uses the skill. Include:
- **What it does**: List specific capabilities
- **When to use**: Include trigger terms users would say
```yaml
# Bad
description: Helps with documents
# Good
description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.
```
---
## Progressive Disclosure
Keep `SKILL.md` under 500 lines. Use supporting files for details:
```
my-skill/
├── SKILL.md # Overview (required)
├── reference.md # Detailed docs (loaded when needed)
├── examples.md # Usage examples
└── scripts/
└── helper.py # Utility script (executed, not loaded)
```
Reference in SKILL.md:
```markdown
For complete API details, see [reference.md](reference.md)
```
---
## Key Points
- Skills are loaded automatically (no restart needed)
- Use `claude --debug` to see loading errors
- Skills cannot spawn subagents
- Use allowed-tools to restrict capabilities
---
## Related
- `../concepts/agent-skills.md` - Skills overview
- `../lookup/skill-metadata.md` - All metadata fields
- `../examples/skills/` - Example skills
**Reference**: https://docs.anthropic.com/en/docs/claude-code/skills

View file

@ -0,0 +1,73 @@
# Creating Subagents
**Purpose**: Step-by-step guide to create custom subagents
---
## Interactive Method (/agents)
1. Run `/agents` in Claude Code
2. Select **Create new agent**
3. Choose scope: **User-level** or **Project-level**
4. Select **Generate with Claude** and describe the subagent
5. Select tools (or keep all)
6. Choose model
7. Pick a color
8. Save - available immediately
---
## Manual Method (Markdown File)
Create file at `~/.claude/agents/` (personal) or `.claude/agents/` (project):
```markdown
---
name: code-reviewer
description: Reviews code for quality and best practices
tools: Read, Glob, Grep
model: sonnet
---
You are a code reviewer. Analyze code and provide specific,
actionable feedback on quality, security, and best practices.
```
Restart session or use `/agents` to load.
---
## CLI Method (JSON)
```bash
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer",
"prompt": "You are a senior code reviewer...",
"tools": ["Read", "Grep", "Glob", "Bash"],
"model": "sonnet"
}
}'
```
Session-only, not saved to disk.
---
## Key Points
- Filename becomes subagent name (without `.md`)
- Description determines when Claude delegates
- Body becomes system prompt
- Subagents only get their system prompt, not full Claude Code prompt
- Include "use proactively" in description for automatic delegation
---
## Related
- `../concepts/subagents-system.md` - Subagents overview
- `../lookup/subagent-frontmatter.md` - All configuration fields
- `../examples/subagents/` - Example subagents
**Reference**: https://docs.anthropic.com/en/docs/claude-code/sub-agents

View file

@ -18,9 +18,12 @@ openagents-repo/guides/
| Task | Path | | Task | Path |
|------|------| |------|------|
| **Adding agents** | `./adding-agent.md` | | **Adding agents (basics)** | `./adding-agent-basics.md` |
| **Adding agents (tests)** | `./adding-agent-testing.md` |
| **Adding OpenCode skills** | `./adding-skill-basics.md` |
| **Creating Claude Code skills** | `./creating-skills.md` |
| **Creating Claude Code subagents** | `./creating-subagents.md` |
| **Testing subagents** | `./testing-subagents.md` | | **Testing subagents** | `./testing-subagents.md` |
| **View all guides** | `./` |
--- ---

View file

@ -0,0 +1,71 @@
# Built-in Subagents
**Purpose**: Quick reference for Claude Code's default subagents
---
## Explore
**Model**: Haiku (fast, low-latency)
**Tools**: Read-only (denied Write, Edit)
**Purpose**: File discovery, code search, codebase exploration
Thoroughness levels:
- `quick` - Targeted lookups
- `medium` - Balanced exploration
- `very thorough` - Comprehensive analysis
---
## Plan
**Model**: Inherits from main conversation
**Tools**: Read-only (denied Write, Edit)
**Purpose**: Codebase research for planning
Used during plan mode to gather context before presenting a plan. Cannot spawn other subagents.
---
## general-purpose
**Model**: Inherits from main conversation
**Tools**: All tools
**Purpose**: Complex research, multi-step operations, code modifications
Used when task requires both exploration AND modification, complex reasoning, or multiple dependent steps.
---
## Other Built-in Agents
| Agent | Model | Purpose |
|-------|-------|---------|
| Bash | Inherits | Terminal commands in separate context |
| statusline-setup | Sonnet | Configure status line (`/statusline`) |
| Claude Code Guide | Haiku | Questions about Claude Code features |
---
## Disabling Subagents
In settings or CLI:
```json
{
"permissions": {
"deny": ["Task(Explore)", "Task(my-custom-agent)"]
}
}
```
Or: `claude --disallowedTools "Task(Explore)"`
---
## Related
- `../concepts/subagents-system.md` - Subagents overview
- `../guides/creating-subagents.md` - Custom subagents
- `../lookup/subagent-frontmatter.md` - Configuration
**Reference**: https://docs.anthropic.com/en/docs/claude-code/sub-agents

View file

@ -0,0 +1,156 @@
# Lookup: Compatibility Layer Adapters
**Purpose**: Quick reference for implemented adapter details
**Last Updated**: 2026-02-05
---
## Adapter Summary
| Adapter | Lines | Tests | Coverage | Status |
|---------|-------|-------|----------|--------|
| **ClaudeAdapter** | 600 | 80 | 96% | ✅ Complete |
| **CursorAdapter** | 554 | 78 | 99% | ✅ Complete |
| **WindsurfAdapter** | 514 | 78 | 99% | ✅ Complete |
**Total**: 1,858 lines of TypeScript, 236 tests
---
## ClaudeAdapter
**Format**: `.claude/config.json` (primary), `.claude/agents/*.md` (subagents)
**Capabilities**:
- ✅ Multiple agents
- ✅ Skills system
- ✅ Hooks (5 types: PreToolUse, PostToolUse, PermissionRequest, AgentStart, AgentEnd)
- ⚠️ Binary permissions (granular → degraded)
- ❌ Temperature not supported
**Key Mappings**:
- Model: `claude-sonnet-4` ↔ `claude-sonnet-4-20250514`
- Permissions: Granular OAC → `permissionMode` (default/acceptEdits/dontAsk/bypassPermissions)
- Contexts → Skills system
**Tests**: 80 tests covering toOAC(), fromOAC(), roundtrip, error handling
---
## CursorAdapter
**Format**: `.cursorrules` (single file in project root)
**Capabilities**:
- ❌ Single agent only (multi-agent → merged)
- ❌ No Skills system (contexts → inlined)
- ❌ No Hooks
- ⚠️ Binary permissions only
- ✅ Temperature support (limited)
**Key Features**:
- `mergeAgents()` method for multi-agent → single-file conversion
- Optional YAML frontmatter
- Context inlining with references
**Key Mappings**:
- Model: `claude-sonnet-4` → `claude-3-sonnet` (fallback to v3)
- Multiple agents → Merged with section headers
**Tests**: 78 tests covering toOAC(), fromOAC(), merging, error handling
---
## WindsurfAdapter
**Format**: `.windsurf/config.json`, `.windsurf/agents/*.json`
**Capabilities**:
- ✅ Multiple agents (`.windsurf/agents/`)
- ⚠️ Partial Skills (→ context references)
- ❌ No Hooks
- ⚠️ Binary permissions only
- ✅ Temperature via creativity setting
**Key Mappings**:
- Model: `claude-sonnet-4` ↔ `claude-4-sonnet`
- Temperature ↔ Creativity: `≤0.4 → low`, `≤0.8 → medium`, `>0.8 → high`
- Priority: `critical/high → high`, `medium/low → low`
- Skills → Context file references in `.windsurf/context/`
**Tests**: 78 tests covering toOAC(), fromOAC(), creativity mapping, error handling
---
## Mappers (Phase 3 ✅)
All mappers are pure functions used by adapters and TranslationEngine:
| Mapper | Lines | Tests | Coverage | Purpose |
|--------|-------|-------|----------|---------|
| **ToolMapper** | 308 | 34 | 100% | Tool name mapping (bash↔terminal, etc.) |
| **PermissionMapper** | 354 | 37 | 98% | Granular↔binary permissions |
| **ModelMapper** | 413 | 37 | 99% | Model ID mapping with fallbacks |
| **ContextMapper** | 384 | 51 | 97% | Context path mapping between platforms |
---
## Core Services (Phase 3 ✅)
| Service | Lines | Tests | Coverage | Purpose |
|---------|-------|-------|----------|---------|
| **CapabilityMatrix** | 559 | 43 | 99% | Feature compatibility analysis |
| **TranslationEngine** | 453 | 47 | 99% | Orchestrates all mappers |
---
## Common Patterns
### Bidirectional Conversion
All 3 adapters support:
- `toOAC()`: Tool format → OpenAgent
- `fromOAC()`: OpenAgent → Tool format
### Graceful Degradation
All adapters warn when features are lost:
- Granular permissions → Binary on/off
- Unsupported features → Warning messages
- Feature loss → Clear user notifications
### Type Safety
- All extend `BaseAdapter`
- Full TypeScript strict mode
- Zod schema validation
- 0 compilation errors
---
## Feature Parity Matrix
| Feature | OAC | Claude | Cursor | Windsurf |
|---------|-----|--------|--------|----------|
| Multiple Agents | ✅ | ✅ | ❌ | ✅ |
| Granular Permissions | ✅ | ❌ | ❌ | ❌ |
| Ask Permissions | ✅ | ❌ | ❌ | ❌ |
| Hooks | ✅ | ✅ | ❌ | ❌ |
| Skills | ✅ | ✅ | ❌ | ⚠️ |
| External Context | ✅ | ✅ | ❌ | ✅ |
| Context Priority | ✅ | ❌ | ❌ | ❌ |
| Temperature | ✅ | ❌ | ⚠️ | ✅ |
| Model Selection | ✅ | ✅ | ✅ | ✅ |
| Task Delegation | ✅ | ✅ | ❌ | ⚠️ |
Legend: ✅ Full support, ⚠️ Partial support, ❌ Not supported
---
## Reference
**Implementation**: `packages/compatibility-layer/src/adapters/`
**Issue**: https://github.com/darrenhinde/OpenAgentsControl/issues/141
**Related**:
- lookup/compatibility-layer-progress.md
- lookup/compatibility-layer-structure.md
- guides/compatibility-layer-workflow.md

View file

@ -0,0 +1,161 @@
# Lookup: Compatibility Layer Progress
**Purpose**: Quick reference for Issue #141 development progress
**Last Updated**: 2026-02-05
---
## Current Status
**Overall Progress**: 59.4% (19/32 subtasks completed)
```
Phase 1 (Foundation): ████████████████████ 100% (6/6) ✅
Phase 2 (Adapters): ████████████████████ 100% (6/6) ✅
Phase 3 (Mappers): ████████████████████ 100% (7/7) ✅
Phase 4 (CLI): ░░░░░░░░░░░░░░░░░░░░ 0% (0/6) ⬅️ NEXT
Phase 5 (Documentation): ░░░░░░░░░░░░░░░░░░░░ 0% (0/7)
```
---
## Phase Breakdown
### Phase 1: Foundation (100% ✅)
**Time**: 7.5h / 8h estimated
- ✅ Subtask 01: Project Setup
- ✅ Subtask 02: Migrate types.ts (315 lines)
- ✅ Subtask 03: Create BaseAdapter (190 lines)
- ✅ Subtask 04: Migrate AgentLoader (386 lines)
- ✅ Subtask 05: Migrate AdapterRegistry (416 lines)
- ✅ Subtask 06: Create index.ts (168 lines)
**Total**: 1,475 lines TypeScript
---
### Phase 2: Adapters (100% ✅)
**Time**: ~12h
- ✅ Subtask 07: ClaudeAdapter (600 lines)
- ✅ Subtask 08: CursorAdapter (554 lines)
- ✅ Subtask 09: WindsurfAdapter (514 lines)
- ✅ Subtask 10: ClaudeAdapter tests (80 tests)
- ✅ Subtask 11: CursorAdapter tests (78 tests)
- ✅ Subtask 12: WindsurfAdapter tests (78 tests)
**Total**: 1,858 lines TypeScript (adapters) + 236 tests
---
### Phase 3: Mappers & Translation (100% ✅)
**Time**: ~10h
- ✅ Subtask 13: ToolMapper (308 lines, 34 tests)
- ✅ Subtask 14: PermissionMapper (354 lines, 37 tests)
- ✅ Subtask 15: ModelMapper (413 lines, 37 tests)
- ✅ Subtask 16: ContextMapper (384 lines, 51 tests)
- ✅ Subtask 17: CapabilityMatrix (559 lines, 43 tests)
- ✅ Subtask 18: TranslationEngine (453 lines, 47 tests)
- ✅ Subtask 19: Mapper & Core Tests (249 tests total)
**Total**: 2,471 lines TypeScript + 249 tests
---
### Phase 4: CLI (0% ⬅️ NEXT)
**Estimated**: 8h
- 📝 Subtask 20: CLI Scaffolding (Commander.js setup)
- 📝 Subtask 21: Convert Command
- 📝 Subtask 22: Validate Command
- 📝 Subtask 23: Migrate Command
- 📝 Subtask 24: Info Command
- 📝 Subtask 25: CLI Integration Tests
---
### Phase 5: Documentation (0%)
**Estimated**: 6h
- 📝 Subtask 26-30: Migration Guides (5 guides)
- 📝 Subtask 31: Feature Matrices
- 📝 Subtask 32: API Documentation
---
## Code Stats
| Category | Lines | Files |
|----------|-------|-------|
| Source Code | 5,799 | 14 |
| Test Code | 6,322 | 9 |
| **Total** | **12,121** | **23** |
### By Phase
| Phase | Source Lines | Tests |
|-------|-------------|-------|
| Phase 1 (Foundation) | 1,475 | - |
| Phase 2 (Adapters) | 1,858 | 236 |
| Phase 3 (Mappers) | 2,471 | 249 |
| **Total** | **5,804** | **485** |
---
## Test Coverage
**485 tests passing** ✅
| Module | Statements | Branches | Functions |
|--------|-----------|----------|-----------|
| Adapters | 97-99% | 82-93% | 95-100% |
| Mappers | 97-100% | 90-100% | 100% |
| Core (Matrix/Engine) | 98-99% | 93-96% | 100% |
---
## Commits (Issue #141)
| Commit | Phase | Description |
|--------|-------|-------------|
| `0b98cbd` | 1 | Foundation implementation |
| `340d144` | 1 | AgentLoader |
| `81c2f65` | 1 | AdapterRegistry |
| `175eac8` | 1 | index.ts entry point |
| `d38dc27` | 2 | ClaudeAdapter |
| `7695696` | 2 | CursorAdapter |
| `71fa384` | 2 | WindsurfAdapter |
| `a9176c9` | 2 | ClaudeAdapter tests |
| `713fd09` | 2 | CursorAdapter tests |
| `0b93a47` | 2 | WindsurfAdapter tests |
| `99eba67` | 3 | Mappers, Matrix, Engine + tests |
---
## Next Steps
1. **Phase 4**: CLI Tool Implementation
- Create `src/cli/index.ts` with Commander.js
- Implement convert, validate, migrate, info commands
- Add CLI integration tests
2. **Phase 5**: Documentation
- Migration guides for all tool combinations
- Feature matrices
- API documentation
---
## Reference
**Issue**: https://github.com/darrenhinde/OpenAgentsControl/issues/141
**Branch**: `devalexanderdaza/issue141`
**Location**: `packages/compatibility-layer/`
**Related**:
- lookup/compatibility-layer-adapters.md
- lookup/compatibility-layer-structure.md
- guides/compatibility-layer-workflow.md

View file

@ -0,0 +1,168 @@
# Lookup: Compatibility Layer File Structure
**Purpose**: Quick reference for where files go in the compatibility-layer package
**Last Updated**: 2026-02-05
---
## Package Location
```
packages/compatibility-layer/
```
---
## Directory Structure (Current State)
```
compatibility-layer/
├── package.json # Dependencies, scripts
├── tsconfig.json # TypeScript config (strict, ES2022)
├── vitest.config.ts # Test config (80% coverage threshold)
├── README.md # Package documentation
│
├── src/ # Source code (5,799 lines)
│ ├── types.ts # Zod schemas + type exports (315 lines) ✅
│ ├── index.ts # Public API exports (335 lines) ✅
│ │
│ ├── adapters/ # Tool adapters ✅ COMPLETE
│ │ ├── BaseAdapter.ts # Abstract base class (190 lines)
│ │ ├── ClaudeAdapter.ts # Claude Code adapter (600 lines)
│ │ ├── CursorAdapter.ts # Cursor IDE adapter (554 lines)
│ │ └── WindsurfAdapter.ts # Windsurf adapter (514 lines)
│ │
│ ├── core/ # Core services ✅ COMPLETE
│ │ ├── AgentLoader.ts # Load/parse OAC agents (386 lines)
│ │ ├── AdapterRegistry.ts # Adapter management (416 lines)
│ │ ├── CapabilityMatrix.ts # Feature parity tracking (559 lines)
│ │ └── TranslationEngine.ts # Conversion orchestration (453 lines)
│ │
│ ├── mappers/ # Feature mappers ✅ COMPLETE
│ │ ├── ToolMapper.ts # Tool name mapping (308 lines)
│ │ ├── PermissionMapper.ts # Permission translation (354 lines)
│ │ ├── ModelMapper.ts # Model ID mapping (413 lines)
│ │ └── ContextMapper.ts # Context path mapping (384 lines)
│ │
│ └── cli/ # Command-line interface 📝 TODO
│ ├── index.ts # CLI entry point
│ └── commands/
│ ├── convert.ts # Convert command
│ ├── validate.ts # Validate command
│ ├── migrate.ts # Migrate command
│ └── info.ts # Info command
│
├── tests/ # Test files (6,322 lines, 485 tests)
│ └── unit/
│ ├── adapters/ # Adapter tests ✅ COMPLETE
│ │ ├── ClaudeAdapter.test.ts (80 tests)
│ │ ├── CursorAdapter.test.ts (78 tests)
│ │ └── WindsurfAdapter.test.ts (78 tests)
│ ├── mappers/ # Mapper tests ✅ COMPLETE
│ │ ├── ToolMapper.test.ts (34 tests)
│ │ ├── PermissionMapper.test.ts (37 tests)
│ │ ├── ModelMapper.test.ts (37 tests)
│ │ └── ContextMapper.test.ts (51 tests)
│ └── core/ # Core tests ✅ COMPLETE
│ ├── CapabilityMatrix.test.ts (43 tests)
│ └── TranslationEngine.test.ts (47 tests)
│
├── docs/ # Documentation 📝 TODO
│ ├── migration-guides/ # Migration instructions
│ ├── feature-matrices/ # Feature comparison tables
│ └── api/ # API documentation
│
└── dist/ # Compiled output (auto-generated)
```
---
## Implementation Status
### ✅ Complete (Phases 1-3)
| File | Lines | Tests | Coverage |
|------|-------|-------|----------|
| types.ts | 315 | - | - |
| index.ts | 335 | - | - |
| BaseAdapter.ts | 190 | - | 92% |
| ClaudeAdapter.ts | 600 | 80 | 96% |
| CursorAdapter.ts | 554 | 78 | 99% |
| WindsurfAdapter.ts | 514 | 78 | 99% |
| AgentLoader.ts | 386 | - | 0%* |
| AdapterRegistry.ts | 416 | - | 0%* |
| CapabilityMatrix.ts | 559 | 43 | 99% |
| TranslationEngine.ts | 453 | 47 | 99% |
| ToolMapper.ts | 308 | 34 | 100% |
| PermissionMapper.ts | 354 | 37 | 98% |
| ModelMapper.ts | 413 | 37 | 99% |
| ContextMapper.ts | 384 | 51 | 97% |
*AgentLoader and AdapterRegistry are tested indirectly via adapters
### 📝 Pending (Phase 4-5)
| File | Purpose | Phase |
|------|---------|-------|
| cli/index.ts | CLI entry point | 4 |
| cli/commands/convert.ts | Convert command | 4 |
| cli/commands/validate.ts | Validate command | 4 |
| cli/commands/migrate.ts | Migrate command | 4 |
| cli/commands/info.ts | Info command | 4 |
| docs/migration-guides/*.md | Migration guides | 5 |
| docs/api/*.md | API documentation | 5 |
---
## Dependencies
### Production
| Package | Purpose | Version |
|---------|---------|---------|
| zod | Schema validation | ^3.22.0 |
| js-yaml | YAML parsing | ^4.1.0 |
| gray-matter | Frontmatter extraction | ^4.0.3 |
### Development
| Package | Purpose | Version |
|---------|---------|---------|
| typescript | TypeScript compiler | ^5.4.0 |
| vitest | Test framework | ^1.6.1 |
| @vitest/coverage-v8 | Coverage reporting | ^1.6.1 |
### CLI (Phase 4 - to be added)
| Package | Purpose | Version |
|---------|---------|---------|
| commander | CLI framework | ^11.1.0 |
| chalk | Terminal colors | ^5.3.0 |
| ora | Loading spinners | ^7.0.1 |
---
## Scripts
```json
{
"build": "tsc",
"build:watch": "tsc --watch",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage"
}
```
---
## Reference
- **Issue**: https://github.com/darrenhinde/OpenAgentsControl/issues/141
- **Branch**: `devalexanderdaza/issue141`
**Related**:
- lookup/compatibility-layer-progress.md
- lookup/compatibility-layer-adapters.md
- guides/compatibility-layer-workflow.md

View file

@ -0,0 +1,97 @@
# Compatibility Layer - Executive Summary
**Issue**: #141 | **Branch**: `devalexanderdaza/issue141` | **Updated**: 2026-02-05
---
## Quick Status
```
Progress: ████████████░░░░░░░░ 59.4% (19/32 subtasks)
✅ Phase 1: Foundation - 6/6 complete
✅ Phase 2: Adapters - 6/6 complete
✅ Phase 3: Mappers - 7/7 complete
⬅️ Phase 4: CLI - 0/6 pending (NEXT)
📝 Phase 5: Documentation - 0/7 pending
```
---
## Codebase Stats
| Metric | Value |
|--------|-------|
| Source Lines | 5,799 (14 files) |
| Test Lines | 6,322 (9 files) |
| Tests | 485 passing |
| Coverage | 97-100% on Phase 3 |
---
## What's Implemented
### Adapters (3)
- `ClaudeAdapter` - .claude/ format ↔ OAC
- `CursorAdapter` - .cursorrules ↔ OAC
- `WindsurfAdapter` - .windsurf/ ↔ OAC
### Mappers (4)
- `ToolMapper` - bash↔terminal, task↔delegate
- `PermissionMapper` - granular↔binary
- `ModelMapper` - model IDs with fallbacks
- `ContextMapper` - context paths between platforms
### Core (2)
- `CapabilityMatrix` - feature compatibility analysis
- `TranslationEngine` - orchestrates all mappers
---
## What's Next
**Phase 4: CLI Tool** (8h estimated)
1. CLI scaffolding (Commander.js)
2. `convert` command
3. `validate` command
4. `migrate` command
5. `info` command
6. Integration tests
---
## Key Commands
```bash
# Work directory
cd packages/compatibility-layer
# Build & Test
npm run build # Compile TypeScript
npx vitest run # Run all tests
npx vitest run --coverage # With coverage
# Git
git log --oneline -5 # Recent commits
```
---
## Feature Parity
| Feature | OAC | Claude | Cursor | Windsurf |
|---------|:---:|:------:|:------:|:--------:|
| Multi-Agent | ✅ | ✅ | ❌ | ✅ |
| Hooks | ✅ | ✅ | ❌ | ❌ |
| Granular Perms | ✅ | ❌ | ❌ | ❌ |
| Skills | ✅ | ✅ | ❌ | ⚠️ |
| Temperature | ✅ | ❌ | ⚠️ | ✅ |
---
## Reference Files
- Progress: `lookup/compatibility-layer-progress.md`
- Structure: `lookup/compatibility-layer-structure.md`
- Adapters: `lookup/compatibility-layer-adapters.md`
- Workflow: `guides/compatibility-layer-workflow.md`

View file

@ -0,0 +1,161 @@
# Lookup: Compatibility Layer Key Learnings
**Purpose**: Important insights from Phase 1-3 development
**Last Updated**: 2026-02-05
---
## TypeScript & Architecture
**TypeScript strict mode works perfectly**
- Zero compilation errors across all 14 source files
- Type safety catches conversion errors early
- Zod + TypeScript prevent runtime issues
**Adapter pattern scales beautifully**
- 3 adapters, 0 duplication, consistent API
- Template method pattern enables reuse
- BaseAdapter provides robust foundation
**Project structure is clean**
- Modular organization enables parallel development
- Function-based folders improve discoverability
- Barrel exports provide clean public API
---
## Code Quality
**Zod schemas are comprehensive**
- All 20+ schemas validated and working
- Runtime validation prevents bad data
- Type inference from schemas reduces duplication
**Pure functions enable testing**
- All mappers are pure functions (ToolMapper, PermissionMapper, etc.)
- Easy to test in isolation
- Deterministic conversion
- 97-100% coverage achieved on mappers
**Registry pattern is powerful**
- Map-based storage + aliases = great DX
- O(1) adapter lookup
- Type-safe registration
---
## Development Process
**Context loading matters**
- Reading standards BEFORE coding prevents rework
- ContextScout saves discovery time
- Persistent session context enables handoffs
**Approval gates prevent mistakes**
- User confirmation before destructive ops
- Incremental execution catches issues early
- Stop on failure prevents cascading errors
**Phase completion tracking**
- Phase 1: ✅ 100% (Foundation)
- Phase 2: ✅ 100% (Adapters + Tests)
- Phase 3: ✅ 100% (Mappers + Tests)
- Overall: 59.4% complete (19/32 subtasks)
---
## Feature Implementation
**Bidirectional conversion is achievable**
- All 3 adapters support roundtrip (OAC ↔ Tool ↔ OAC)
- Lossy conversions handled with clear warnings
- Feature parity matrix guides expectations
**Graceful degradation works**
- Clear warnings guide users on feature loss
- Binary permissions instead of failing
- Temperature ↔ Creativity mapping (approximate but functional)
**Translation Engine orchestration**
- Coordinates all mappers for complete translation
- Collects warnings from all components
- Provides preview/compatibility analysis
---
## Technical Wins
**Type-safe mappers prevent bugs**
- Model ID mapping with fallbacks
- Permission degradation with warnings
- Priority normalization handles edge cases
**Error handling is robust**
- Custom error classes per module
- Descriptive error messages
- Validation at boundaries
**Build system is solid**
- TypeScript compilation fast (~1s)
- All 485 tests pass
- Coverage exceeds 80% on tested modules
---
## Test Coverage Summary
| Category | Tests | Coverage |
|----------|-------|----------|
| Adapters | 236 | 97-99% |
| Mappers | 159 | 97-100% |
| Core | 90 | 98-99% |
| **Total** | **485** | **>80%** |
---
## What Worked Well
✅ Loading context before implementation
✅ Approval gates for safety
✅ Incremental execution (one step at a time)
✅ Template method pattern for adapters
✅ Pure functions for all mappers
✅ Zod validation throughout
✅ Comprehensive test coverage
✅ Conventional commits tracking
---
## What to Improve
⚠️ Could add integration tests earlier
⚠️ Feature parity matrix could be auto-generated
⚠️ CLI tool would help during development
⚠️ AgentLoader/AdapterRegistry need direct unit tests
---
## Remaining Work
**Phase 4 (CLI)**: 6 subtasks
- CLI scaffolding with Commander.js
- convert, validate, migrate, info commands
- Integration tests
**Phase 5 (Documentation)**: 7 subtasks
- 5 migration guides
- Feature matrices
- API documentation
---
## Reference
**Issue**: https://github.com/darrenhinde/OpenAgentsControl/issues/141
**Branch**: `devalexanderdaza/issue141`
**Related**:
- lookup/compatibility-layer-progress.md
- lookup/compatibility-layer-structure.md
- guides/compatibility-layer-workflow.md

View file

@ -0,0 +1,64 @@
# Hook Events Reference
**Purpose**: Quick reference for all Claude Code hook events
---
## Available Events
| Event | When It Fires | Can Block? |
|-------|---------------|------------|
| `PreToolUse` | Before tool calls | Yes (exit 2) |
| `PostToolUse` | After tool calls complete | No |
| `PermissionRequest` | Permission dialog shown | Yes (allow/deny) |
| `UserPromptSubmit` | User submits prompt | No |
| `Notification` | Claude sends notification | No |
| `Stop` | Claude finishes responding | No |
| `SubagentStop` | Subagent task completes | No |
| `PreCompact` | Before compact operation | No |
| `SessionStart` | New/resumed session | No |
| `SessionEnd` | Session ends | No |
---
## Matcher Syntax
- `"Bash"` - Match specific tool
- `"Edit|Write"` - Match multiple tools (OR)
- `"*"` - Match all tools
- `""` - Match all (for Notification)
---
## Exit Codes
| Code | Behavior |
|------|----------|
| 0 | Success, continue execution |
| 1 | Error logged, continue execution |
| 2 | **Block operation**, feed stderr to Claude |
---
## Input/Output
Hooks receive JSON via stdin:
```json
{
"tool_name": "Bash",
"tool_input": { "command": "ls -la" },
"session_id": "...",
"transcript_path": "..."
}
```
Output to stderr is fed back to Claude when blocking (exit 2).
---
## Related
- `../concepts/hooks-system.md` - Hooks overview
- `../examples/hooks/` - Hook examples
**Reference**: https://docs.anthropic.com/en/docs/claude-code/hooks

View file

@ -0,0 +1,74 @@
# Skill Metadata Fields
**Purpose**: Quick reference for SKILL.md frontmatter fields
---
## Required Fields
| Field | Description |
|-------|-------------|
| `name` | Unique identifier (lowercase, hyphens, max 64 chars) |
| `description` | What skill does and when to use (max 1024 chars) |
---
## Optional Fields
| Field | Default | Description |
|-------|---------|-------------|
| `allowed-tools` | All | Tools Claude can use without permission |
| `model` | Conversation | Model to use (e.g., `claude-sonnet-4-20250514`) |
| `context` | - | Set to `fork` for isolated sub-agent context |
| `agent` | `general-purpose` | Agent type when `context: fork` |
| `hooks` | - | Lifecycle hooks (`PreToolUse`, `PostToolUse`, `Stop`) |
| `user-invocable` | `true` | Show in slash command menu |
| `disable-model-invocation` | `false` | Block programmatic invocation |
---
## allowed-tools Syntax
```yaml
# Comma-separated
allowed-tools: Read, Grep, Glob
# YAML list
allowed-tools:
- Read
- Grep
- Glob
```
---
## hooks Syntax
```yaml
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate.sh"
once: true # Run only once per session
```
---
## Visibility Control
| Setting | Slash Menu | Skill Tool | Auto-discovery |
|---------|------------|------------|----------------|
| Default | ✓ | ✓ | ✓ |
| `user-invocable: false` | ✗ | ✓ | ✓ |
| `disable-model-invocation: true` | ✓ | ✗ | ✓ |
---
## Related
- `../concepts/agent-skills.md` - Skills overview
- `../guides/creating-skills.md` - Creation guide
**Reference**: https://docs.anthropic.com/en/docs/claude-code/skills

View file

@ -0,0 +1,64 @@
# Skills vs Other Options
**Purpose**: When to use Skills versus other Claude Code customizations
---
## Comparison Table
| Option | When It Runs | Best For |
|--------|--------------|----------|
| **Skills** | Claude chooses when relevant | Specialized knowledge (review standards, patterns) |
| **Slash commands** | You type `/command` | Reusable prompts (`/deploy staging`) |
| **CLAUDE.md** | Every conversation | Project-wide instructions |
| **Subagents** | Claude delegates or you invoke | Isolated context, different tools |
| **Hooks** | Specific tool events | Auto-format, logging, protection |
| **MCP servers** | Claude calls as needed | External tools and data sources |
---
## Key Distinctions
### Skills vs Slash Commands
- **Skills**: Claude decides when to use based on task
- **Commands**: You explicitly type `/command`
### Skills vs Subagents
- **Skills**: Add knowledge to current conversation
- **Subagents**: Separate context with own tools/permissions
### Skills vs MCP
- **Skills**: Tell Claude *how* to use tools
- **MCP**: *Provide* the tools themselves
### Skills vs CLAUDE.md
- **Skills**: Loaded only when relevant
- **CLAUDE.md**: Always loaded into every conversation
---
## Decision Guide
**Use Skills when**:
- Teaching domain-specific knowledge
- Defining review/coding standards
- Want Claude to decide when to apply
**Use Subagents when**:
- Need tool isolation
- Task produces verbose output
- Want separate context window
**Use CLAUDE.md when**:
- Rules apply to ALL interactions
- Project-wide coding standards
---
## Related
- `../concepts/agent-skills.md` - Skills overview
- `../concepts/subagents-system.md` - Subagents overview
- `../../standards/subagent-structure.md` - Subagent patterns
**Reference**: https://docs.anthropic.com/en/docs/claude-code/skills

View file

@ -0,0 +1,83 @@
# Subagent Frontmatter
**Purpose**: Quick reference for subagent configuration fields
---
## Required Fields
| Field | Description |
|-------|-------------|
| `name` | Unique identifier (lowercase, hyphens) |
| `description` | When Claude should delegate to this subagent |
---
## Optional Fields
| Field | Default | Description |
|-------|---------|-------------|
| `tools` | All | Tools subagent can use |
| `disallowedTools` | - | Tools to deny (removed from list) |
| `model` | `sonnet` | Model: `sonnet`, `opus`, `haiku`, `inherit` |
| `permissionMode` | `default` | Permission handling mode |
| `skills` | - | Skills to load into context |
| `hooks` | - | Lifecycle hooks for this subagent |
---
## Permission Modes
| Mode | Behavior |
|------|----------|
| `default` | Standard permission checking |
| `acceptEdits` | Auto-accept file edits |
| `dontAsk` | Auto-deny permission prompts |
| `bypassPermissions` | Skip all permission checks |
| `plan` | Read-only exploration |
⚠️ `bypassPermissions` is dangerous - skips all checks
---
## Hooks Syntax
```yaml
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate.sh"
PostToolUse:
- matcher: "Edit|Write"
hooks:
- type: command
command: "./scripts/lint.sh"
```
---
## Example
```yaml
---
name: debugger
description: Debugging specialist for errors and test failures
tools: Read, Edit, Bash, Grep, Glob
model: inherit
permissionMode: default
---
You are an expert debugger...
```
---
## Related
- `../concepts/subagents-system.md` - Subagents overview
- `../guides/creating-subagents.md` - Creation guide
- `../lookup/builtin-subagents.md` - Built-in subagents
**Reference**: https://docs.anthropic.com/en/docs/claude-code/sub-agents

View file

@ -0,0 +1,133 @@
# Lookup: Tool Feature Parity Matrix
**Purpose**: Quick reference for feature support across AI coding tools
**Last Updated**: 2026-02-04
---
## Feature Comparison
### Core Features
| Feature | OAC | Claude Code | Cursor IDE | Windsurf | Notes |
|---------|-----|-------------|------------|----------|-------|
| **Multiple agents** | ✅ Yes | ✅ Yes | ❌ Single only | ✅ Yes | Cursor requires merged config |
| **Agent modes** | ✅ primary/subagent | ✅ Yes | ❌ No | ⚠️ Partial | OAC has explicit mode field |
| **Temperature control** | ✅ 0.0-2.0 | ❌ No | ⚠️ Limited | ⚠️ Limited | Maps to creativity settings |
| **Model selection** | ✅ Full control | ✅ Yes | ✅ Yes | ✅ Yes | Different ID formats |
| **Context files** | ✅ .opencode/context/ | ✅ Skills system | ✅ .cursorrules | ✅ Yes | Path mapping required |
### Tool Permissions
| Tool Access | OAC | Claude Code | Cursor IDE | Windsurf |
|-------------|-----|-------------|------------|----------|
| **read** | ✅ Granular | ⚠️ Binary on/off | ⚠️ Binary | ⚠️ Binary |
| **write** | ✅ Granular | ⚠️ Binary | ⚠️ Binary | ⚠️ Binary |
| **edit** | ✅ Granular | ⚠️ Binary | ⚠️ Binary | ⚠️ Binary |
| **bash** | ✅ Granular | ✅ Yes | ✅ Yes | ✅ Yes |
| **task** | ✅ Delegation | ✅ Yes | ❌ No | ⚠️ Limited |
| **grep/glob** | ✅ Separate | ✅ Yes | ✅ Yes | ✅ Yes |
**Legend**: ✅ Full support | ⚠️ Partial/degraded | ❌ Not supported
### Advanced Features
| Feature | OAC | Claude Code | Cursor IDE | Windsurf |
|---------|-----|-------------|------------|----------|
| **Skills system** | ✅ Yes | ✅ Yes | ❌ No | ⚠️ Partial |
| **Hooks** | ✅ 5 types | ✅ Yes | ❌ No | ❌ No |
| **Dependencies** | ✅ Explicit | ✅ Yes | ❌ No | ⚠️ Partial |
| **Priority levels** | ✅ 4 levels | ⚠️ 2 levels | ❌ No | ⚠️ 2 levels |
| **Agent categories** | ✅ 8 types | ⚠️ Limited | ❌ No | ⚠️ Limited |
---
## Hook Event Support
| Event | OAC | Claude Code | Cursor | Windsurf |
|-------|-----|-------------|--------|----------|
| PreToolUse | ✅ | ✅ | ❌ | ❌ |
| PostToolUse | ✅ | ✅ | ❌ | ❌ |
| PermissionRequest | ✅ | ✅ | ❌ | ❌ |
| AgentStart | ✅ | ✅ | ❌ | ❌ |
| AgentEnd | ✅ | ✅ | ❌ | ❌ |
---
## Permission Granularity Mapping
### OAC → Other Tools (Degradation)
```
OAC Granular Permission:
{
allow: ["src/**/*.ts"],
deny: ["src/secrets/**"],
ask: ["package.json"]
}
↓ Maps to ↓
Claude: tools.write = true (with warnings in skills)
Cursor: Full write access (no granularity)
Windsurf: Basic allow/deny (ask → deny)
```
---
## Model ID Mapping
| OAC Model ID | Claude Code | Cursor IDE | Windsurf |
|--------------|-------------|------------|----------|
| claude-sonnet-4 | claude-sonnet-4-20250514 | claude-sonnet-4 | claude-4-sonnet |
| gpt-4 | N/A | gpt-4 | gpt-4 |
| gpt-4-turbo | N/A | gpt-4-turbo | gpt-4-turbo |
---
## Configuration File Paths
| Tool | Primary Config | Context/Skills | Agents |
|------|----------------|----------------|--------|
| **OAC** | .opencode/agent/ | .opencode/context/ | .opencode/agent/*.md |
| **Claude** | .claude/config.json | .claude/skills/ | .claude/agents/ |
| **Cursor** | .cursorrules | (inline) | Single file only |
| **Windsurf** | .windsurf/config.json | .windsurf/context/ | .windsurf/agents/ |
---
## Conversion Compatibility
### OAC → Claude Code
- ✅ Full feature preservation
- ⚠️ Temperature ignored (not supported)
- ✅ Hooks preserved
- ✅ Skills map 1:1
### OAC → Cursor IDE
- ⚠️ Multiple agents → merged single file
- ❌ Hooks lost
- ❌ Skills → inline context
- ⚠️ Granular permissions → binary
### OAC → Windsurf
- ✅ Multiple agents preserved
- ⚠️ Temperature → creativity setting
- ❌ Hooks lost
- ⚠️ Skills → partial mapping
### Reverse Conversions
- Claude → OAC: ✅ High fidelity
- Cursor → OAC: ⚠️ Limited (single agent)
- Windsurf → OAC: ⚠️ Partial feature loss
---
## Reference
- **Implementation**: `packages/compatibility-layer/src/mappers/`
- **Related**:
- concepts/compatibility-layer.md
- examples/baseadapter-pattern.md
- guides/compatibility-layer-workflow.md

View file

@ -2,7 +2,7 @@
**Purpose**: Context files specific to the OpenAgents Control repository **Purpose**: Context files specific to the OpenAgents Control repository
**Last Updated**: 2026-01-31 **Last Updated**: 2026-02-04
--- ---
@ -11,11 +11,11 @@
| Function | Files | Purpose | | Function | Files | Purpose |
|----------|-------|---------| |----------|-------|---------|
| **Standards** | 2 files | Agent creation standards | | **Standards** | 2 files | Agent creation standards |
| **Concepts** | 2 files | Core ideas and principles | | **Concepts** | 6 files | Core ideas and principles |
| **Examples** | 1 file | Working code samples | | **Examples** | 9 files | Working code samples |
| **Guides** | 10 files | Step-by-step workflows | | **Guides** | 14 files | Step-by-step workflows |
| **Lookup** | 4 files | Quick reference tables | | **Lookup** | 11 files | Quick reference tables |
| **Errors** | 1 file | Common issues + solutions | | **Errors** | 2 files | Common issues + solutions |
--- ---
@ -34,9 +34,13 @@
| File | Topic | Priority | | File | Topic | Priority |
|------|-------|----------| |------|-------|----------|
| `concepts/compatibility-layer.md` | Adapter pattern for AI coding tools | ⭐⭐⭐⭐⭐ |
| `concepts/subagent-testing-modes.md` | Standalone vs delegation testing | ⭐⭐⭐⭐⭐ | | `concepts/subagent-testing-modes.md` | Standalone vs delegation testing | ⭐⭐⭐⭐⭐ |
| `concepts/hooks-system.md` | User-defined lifecycle commands | ⭐⭐⭐⭐ |
| `concepts/agent-skills.md` | Skills that teach Claude tasks | ⭐⭐⭐⭐ |
| `concepts/subagents-system.md` | Specialized AI assistants | ⭐⭐⭐⭐ |
**When to read**: Before testing any subagent **When to read**: Before testing any subagent or working with tool adapters
--- ---
@ -44,9 +48,11 @@
| File | Topic | Priority | | File | Topic | Priority |
|------|-------|----------| |------|-------|----------|
| `examples/baseadapter-pattern.md` | Template Method pattern for tool adapters | ⭐⭐⭐⭐⭐ |
| `examples/zod-schema-migration.md` | Migrating TypeScript to Zod schemas | ⭐⭐⭐⭐ |
| `examples/subagent-prompt-structure.md` | Optimized subagent prompt template | ⭐⭐⭐⭐ | | `examples/subagent-prompt-structure.md` | Optimized subagent prompt template | ⭐⭐⭐⭐ |
**When to read**: When creating or optimizing subagent prompts **When to read**: When creating adapters, schemas, or optimizing subagent prompts
--- ---
@ -54,8 +60,13 @@
| File | Topic | Priority | | File | Topic | Priority |
|------|-------|----------| |------|-------|----------|
| `guides/compatibility-layer-workflow.md` | Developing compatibility layer for AI tools | ⭐⭐⭐⭐⭐ |
| `guides/testing-subagents.md` | How to test subagents standalone | ⭐⭐⭐⭐⭐ | | `guides/testing-subagents.md` | How to test subagents standalone | ⭐⭐⭐⭐⭐ |
| `guides/adding-agent.md` | How to add new agents | ⭐⭐⭐⭐ | | `guides/adding-agent-basics.md` | How to add new agents (basics) | ⭐⭐⭐⭐ |
| `guides/adding-agent-testing.md` | How to add agent tests | ⭐⭐⭐⭐ |
| `guides/adding-skill-basics.md` | How to add OpenCode skills | ⭐⭐⭐⭐ |
| `guides/creating-skills.md` | How to create Claude Code skills | ⭐⭐⭐⭐ |
| `guides/creating-subagents.md` | How to create Claude Code subagents | ⭐⭐⭐⭐ |
| `guides/testing-agent.md` | How to test agents | ⭐⭐⭐⭐ | | `guides/testing-agent.md` | How to test agents | ⭐⭐⭐⭐ |
| `guides/external-libraries-workflow.md` | How to handle external library dependencies | ⭐⭐⭐⭐ | | `guides/external-libraries-workflow.md` | How to handle external library dependencies | ⭐⭐⭐⭐ |
| `guides/github-issues-workflow.md` | How to work with GitHub issues and project board | ⭐⭐⭐⭐ | | `guides/github-issues-workflow.md` | How to work with GitHub issues and project board | ⭐⭐⭐⭐ |
@ -73,11 +84,18 @@
| File | Topic | Priority | | File | Topic | Priority |
|------|-------|----------| |------|-------|----------|
| `lookup/tool-feature-parity.md` | AI coding tool feature comparison | ⭐⭐⭐⭐⭐ |
| `lookup/compatibility-layer-structure.md` | Compatibility package file structure | ⭐⭐⭐⭐⭐ |
| `lookup/subagent-test-commands.md` | Subagent testing commands | ⭐⭐⭐⭐⭐ | | `lookup/subagent-test-commands.md` | Subagent testing commands | ⭐⭐⭐⭐⭐ |
| `lookup/hook-events.md` | All hook events reference | ⭐⭐⭐⭐ |
| `lookup/skill-metadata.md` | SKILL.md frontmatter fields | ⭐⭐⭐⭐ |
| `lookup/skills-comparison.md` | Skills vs other options | ⭐⭐⭐⭐ |
| `lookup/builtin-subagents.md` | Default subagents (Explore, Plan) | ⭐⭐⭐⭐ |
| `lookup/subagent-frontmatter.md` | Subagent configuration fields | ⭐⭐⭐⭐ |
| `lookup/file-locations.md` | Where files are located | ⭐⭐⭐⭐ | | `lookup/file-locations.md` | Where files are located | ⭐⭐⭐⭐ |
| `lookup/commands.md` | Available slash commands | ⭐⭐⭐ | | `lookup/commands.md` | Available slash commands | ⭐⭐⭐ |
**When to read**: Quick command lookups **When to read**: Quick command lookups and feature comparisons
--- ---
@ -86,6 +104,7 @@
| File | Topic | Priority | | File | Topic | Priority |
|------|-------|----------| |------|-------|----------|
| `errors/tool-permission-errors.md` | Tool permission issues | ⭐⭐⭐⭐⭐ | | `errors/tool-permission-errors.md` | Tool permission issues | ⭐⭐⭐⭐⭐ |
| `errors/skills-errors.md` | Skills not triggering/loading | ⭐⭐⭐⭐ |
**When to read**: When tests fail with permission errors **When to read**: When tests fail with permission errors
@ -116,7 +135,7 @@
1. Load `standards/agent-frontmatter.md` (valid YAML frontmatter) 1. Load `standards/agent-frontmatter.md` (valid YAML frontmatter)
2. Load `standards/subagent-structure.md` (file structure) 2. Load `standards/subagent-structure.md` (file structure)
3. Load `core-concepts/agents.md` (understand system) 3. Load `core-concepts/agents.md` (understand system)
4. Load `guides/adding-agent.md` (step-by-step) 4. Load `guides/adding-agent-basics.md` (step-by-step)
5. **If using external libraries**: Load `guides/external-libraries-workflow.md` (fetch docs) 5. **If using external libraries**: Load `guides/external-libraries-workflow.md` (fetch docs)
6. Load `examples/subagent-prompt-structure.md` (if subagent) 6. Load `examples/subagent-prompt-structure.md` (if subagent)
7. Load `guides/testing-agent.md` (validate) 7. Load `guides/testing-agent.md` (validate)
@ -153,7 +172,7 @@ All files follow MVI principle (<200 lines):
- `../core/context-system/` - Context management system - `../core/context-system/` - Context management system
- `quick-start.md` - 2-minute repo orientation - `quick-start.md` - 2-minute repo orientation
- `../content-creation/navigation.md` - Content creation principles - `../content-creation/navigation.md` - Content creation principles
- `../to-be-consumed/claude-code-docs/plugins.md` - Claude Code extension docs - `plugins/context/context-overview.md` - Plugin system context
--- ---

View file

@ -0,0 +1,47 @@
# Plugin Architecture
**Purpose**: Extend Claude Code with slash commands, agents, Skills, hooks, and MCP servers
---
## Core Concept
Plugins are directories containing a manifest (`.claude-plugin/plugin.json`) plus optional components (commands, agents, skills, hooks). They enable sharing functionality across projects and teams with namespaced commands.
**Key Difference**:
- **Standalone** (`.claude/`): Personal workflows, short names like `/hello`
- **Plugins**: Shareable, versioned, namespaced like `/plugin-name:hello`
---
## Key Points
- Plugin manifest at `.claude-plugin/plugin.json` defines identity (name, description, version)
- Name field becomes namespace prefix for all slash commands
- Components live at plugin root, NOT inside `.claude-plugin/`
- Load with `--plugin-dir ./my-plugin` for testing
- Multiple plugins can be loaded simultaneously
---
## Quick Example
```json
// .claude-plugin/plugin.json
{
"name": "my-plugin",
"description": "A greeting plugin",
"version": "1.0.0",
"author": { "name": "Your Name" }
}
```
---
## Related
- `../guides/creating-plugins.md` - How to create plugins
- `../lookup/plugin-structure.md` - Directory structure
- `../../guides/adding-skill.md` - Adding skills to plugins
**Reference**: https://docs.anthropic.com/en/docs/claude-code/plugins

View file

@ -20,6 +20,13 @@ Deep dives into specific plugin features.
Guidelines and troubleshooting. Guidelines and troubleshooting.
- [Best Practices](./reference/best-practices.md): Message injection workarounds, security, and performance. - [Best Practices](./reference/best-practices.md): Message injection workarounds, security, and performance.
### 🧩 Claude Code Plugins (External)
Claude Code plugin system documentation (harvested from external docs).
- [Concepts: Plugin Architecture](./concepts/plugin-architecture.md): Core concepts and structure
- [Guides: Creating Plugins](./guides/creating-plugins.md): Step-by-step creation
- [Guides: Migrating to Plugins](./guides/migrating-to-plugins.md): Convert standalone to plugin
- [Lookup: Plugin Structure](./lookup/plugin-structure.md): Directory reference
## 🚀 How to use this library ## 🚀 How to use this library
If you are asking an AI to build a new feature: If you are asking an AI to build a new feature:
1. **For a new tool**: Provide `architecture/overview.md` and `capabilities/tools.md`. 1. **For a new tool**: Provide `architecture/overview.md` and `capabilities/tools.md`.

View file

@ -0,0 +1,61 @@
# Creating Plugins
**Purpose**: Step-by-step guide to create Claude Code plugins
---
## Quickstart Workflow
1. **Create directory**: `mkdir my-plugin`
2. **Create manifest**: `mkdir my-plugin/.claude-plugin`
3. **Add plugin.json** with name, description, version
4. **Add commands**: `mkdir my-plugin/commands` → add `.md` files
5. **Test**: `claude --plugin-dir ./my-plugin`
6. **Use**: `/my-plugin:command-name`
---
## Key Points
- Filename becomes command name (e.g., `hello.md` → `/plugin:hello`)
- Use `$ARGUMENTS` placeholder for user input
- Use `$1`, `$2` for individual arguments
- Restart Claude Code to pick up changes
- Load multiple: `claude --plugin-dir ./one --plugin-dir ./two`
---
## Command File Format
```markdown
---
description: Greet the user with a personalized message
---
# Hello Command
Greet the user named "$ARGUMENTS" warmly.
```
---
## Adding Components
| Component | Location | Purpose |
|-----------|----------|---------|
| Commands | `commands/*.md` | Slash commands |
| Agents | `agents/*.md` | Custom subagents |
| Skills | `skills/*/SKILL.md` | Agent capabilities |
| Hooks | `hooks/hooks.json` | Event handlers |
| MCP | `.mcp.json` | External tools |
| LSP | `.lsp.json` | Code intelligence |
---
## Related
- `../concepts/plugin-architecture.md` - Architecture overview
- `../lookup/plugin-structure.md` - Full directory structure
- `./migrating-to-plugins.md` - Convert standalone to plugin
**Reference**: https://docs.anthropic.com/en/docs/claude-code/plugins

View file

@ -0,0 +1,65 @@
# Migrating Standalone to Plugin
**Purpose**: Convert `.claude/` configurations into shareable plugins
---
## Migration Steps
1. **Create plugin structure**:
```bash
mkdir -p my-plugin/.claude-plugin
```
2. **Create manifest** (`my-plugin/.claude-plugin/plugin.json`):
```json
{
"name": "my-plugin",
"description": "Migrated from standalone",
"version": "1.0.0"
}
```
3. **Copy components**:
```bash
cp -r .claude/commands my-plugin/
cp -r .claude/agents my-plugin/
cp -r .claude/skills my-plugin/
```
4. **Migrate hooks** (from `settings.json` to `hooks/hooks.json`):
```bash
mkdir my-plugin/hooks
# Copy hooks object from settings.json
```
5. **Test**: `claude --plugin-dir ./my-plugin`
---
## What Changes
| Standalone | Plugin |
|------------|--------|
| One project only | Shareable via marketplaces |
| Files in `.claude/` | Files in `plugin-name/` |
| Hooks in `settings.json` | Hooks in `hooks/hooks.json` |
| Manual copy to share | Install with `/plugin install` |
---
## Key Points
- Plugin commands are namespaced (`/plugin:cmd` vs `/cmd`)
- Hook format is identical between settings.json and hooks.json
- Remove original `.claude/` files after verifying migration
- Plugin version takes precedence when loaded
---
## Related
- `../lookup/plugin-structure.md` - Directory structure
- `../concepts/plugin-architecture.md` - Architecture
**Reference**: https://docs.anthropic.com/en/docs/claude-code/plugins

View file

@ -0,0 +1,62 @@
# Plugin Directory Structure
**Purpose**: Quick reference for plugin file organization
---
## Standard Layout
```
my-plugin/
├── .claude-plugin/ # REQUIRED - manifest only
│ └── plugin.json # Plugin identity
│
├── commands/ # Slash commands as .md files
│ └── hello.md
│
├── agents/ # Custom subagent definitions
│ └── reviewer.md
│
├── skills/ # Agent Skills
│ └── code-review/
│ └── SKILL.md
│
├── hooks/ # Event handlers
│ └── hooks.json
│
├── .mcp.json # MCP server configs
└── .lsp.json # LSP server configs
```
---
## Critical Rules
- Only `plugin.json` goes inside `.claude-plugin/`
- All other directories at plugin root level
- Never put commands/, agents/, skills/ inside .claude-plugin/
---
## Manifest Schema
```json
{
"name": "plugin-name", // Required: namespace prefix
"description": "What it does", // Required: shown in manager
"version": "1.0.0", // Required: semver
"author": { "name": "You" }, // Optional
"homepage": "https://...", // Optional
"repository": "https://...", // Optional
"license": "MIT" // Optional
}
```
---
## Related
- `../concepts/plugin-architecture.md` - Architecture
- `../guides/creating-plugins.md` - Creation guide
**Reference**: https://docs.anthropic.com/en/docs/claude-code/plugins-reference

View file

@ -1,565 +0,0 @@
# Agent Skills
> Create, manage, and share Skills to extend Claude's capabilities in Claude Code.
This guide shows you how to create, use, and manage Agent Skills in Claude Code. For background on how Skills work across Claude products, see [What are Skills?](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview).
A Skill is a markdown file that teaches Claude how to do something specific: reviewing PRs using your team's standards, generating commit messages in your preferred format, or querying your company's database schema. When you ask Claude something that matches a Skill's purpose, Claude automatically applies it.
## Create your first Skill
This example creates a personal Skill that teaches Claude to explain code using visual diagrams and analogies. Unlike Claude's default explanations, this Skill ensures every explanation includes an ASCII diagram and a real-world analogy.
<Steps>
<Step title="Check available Skills">
Before creating a Skill, see what Skills Claude already has access to:
```
What Skills are available?
```
Claude will list any Skills currently loaded. You may see none, or you may see Skills from plugins or your organization.
</Step>
<Step title="Create the Skill directory">
Create a directory for the Skill in your personal Skills folder. Personal Skills are available across all your projects. (You can also create [project Skills](#where-skills-live) in `.claude/skills/` to share with your team.)
```bash theme={null}
mkdir -p ~/.claude/skills/explaining-code
```
</Step>
<Step title="Write SKILL.md">
Every Skill needs a `SKILL.md` file. The file starts with YAML metadata between `---` markers and must include a `name` and `description`, followed by Markdown instructions that Claude follows when the Skill is active.
The `description` is especially important, because Claude uses it to decide when to apply the Skill.
Create `~/.claude/skills/explaining-code/SKILL.md`:
```yaml theme={null}
---
name: explaining-code
description: Explains code with visual diagrams and analogies. Use when explaining how code works, teaching about a codebase, or when the user asks "how does this work?"
---
When explaining code, always include:
1. **Start with an analogy**: Compare the code to something from everyday life
2. **Draw a diagram**: Use ASCII art to show the flow, structure, or relationships
3. **Walk through the code**: Explain step-by-step what happens
4. **Highlight a gotcha**: What's a common mistake or misconception?
Keep explanations conversational. For complex concepts, use multiple analogies.
```
</Step>
<Step title="Load and verify the Skill">
Skills are automatically loaded when created or modified. Verify the Skill appears in the list:
```
What Skills are available?
```
You should see `explaining-code` in the list with its description.
</Step>
<Step title="Test the Skill">
Open any file in your project and ask Claude a question that matches the Skill's description:
```
How does this code work?
```
Claude should ask to use the `explaining-code` Skill, then include an analogy and ASCII diagram in its explanation. If the Skill doesn't trigger, try rephrasing to include more keywords from the description, like "explain how this works."
</Step>
</Steps>
The rest of this guide covers how Skills work, configuration options, and troubleshooting.
## How Skills work
Skills are **model-invoked**: Claude decides which Skills to use based on your request. You don't need to explicitly call a Skill. Claude automatically applies relevant Skills when your request matches their description.
When you send a request, Claude follows these steps to find and use relevant Skills:
<Steps>
<Step title="Discovery">
At startup, Claude loads only the name and description of each available Skill. This keeps startup fast while giving Claude enough context to know when each Skill might be relevant.
</Step>
<Step title="Activation">
When your request matches a Skill's description, Claude asks to use the Skill. You'll see a confirmation prompt before the full `SKILL.md` is loaded into context. Since Claude reads these descriptions to find relevant Skills, [write descriptions](#skill-not-triggering) that include keywords users would naturally say.
</Step>
<Step title="Execution">
Claude follows the Skill's instructions, loading referenced files or running bundled scripts as needed.
</Step>
</Steps>
### Where Skills live
Where you store a Skill determines who can use it:
| Location | Path | Applies to |
| :--------- | :----------------------------------------------- | :-------------------------------- |
| Enterprise | See [managed settings](/en/iam#managed-settings) | All users in your organization |
| Personal | `~/.claude/skills/` | You, across all projects |
| Project | `.claude/skills/` | Anyone working in this repository |
| Plugin | Bundled with [plugins](/en/plugins) | Anyone with the plugin installed |
If two Skills have the same name, the higher row wins: managed overrides personal, personal overrides project, and project overrides plugin.
### When to use Skills versus other options
Claude Code offers several ways to customize behavior. The key difference: **Skills are triggered automatically by Claude** based on your request, while slash commands require you to type `/command` explicitly.
| Use this | When you want to... | When it runs |
| :--------------------------------------- | :------------------------------------------------------------------------- | :----------------------------------------- |
| **Skills** | Give Claude specialized knowledge (e.g., "review PRs using our standards") | Claude chooses when relevant |
| **[Slash commands](/en/slash-commands)** | Create reusable prompts (e.g., `/deploy staging`) | You type `/command` to run it |
| **[CLAUDE.md](/en/memory)** | Set project-wide instructions (e.g., "use TypeScript strict mode") | Loaded into every conversation |
| **[Subagents](/en/sub-agents)** | Delegate tasks to a separate context with its own tools | Claude delegates, or you invoke explicitly |
| **[Hooks](/en/hooks)** | Run scripts on events (e.g., lint on file save) | Fires on specific tool events |
| **[MCP servers](/en/mcp)** | Connect Claude to external tools and data sources | Claude calls MCP tools as needed |
**Skills vs. subagents**: Skills add knowledge to the current conversation. Subagents run in a separate context with their own tools. Use Skills for guidance and standards; use subagents when you need isolation or different tool access.
**Skills vs. MCP**: Skills tell Claude *how* to use tools; MCP *provides* the tools. For example, an MCP server connects Claude to your database, while a Skill teaches Claude your data model and query patterns.
<Note>
For a deep dive into the architecture and real-world applications of Agent Skills, read [Equipping agents for the real world with Agent Skills](https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills).
</Note>
## Configure Skills
This section covers Skill file structure, supporting files, tool restrictions, and distribution options.
### Write SKILL.md
The `SKILL.md` file is the only required file in a Skill. It has two parts: YAML metadata (the section between `---` markers) at the top, and Markdown instructions that tell Claude how to use the Skill:
```yaml theme={null}
---
name: your-skill-name
description: Brief description of what this Skill does and when to use it
---
# Your Skill Name
## Instructions
Provide clear, step-by-step guidance for Claude.
## Examples
Show concrete examples of using this Skill.
```
#### Available metadata fields
You can use the following fields in the YAML frontmatter:
| Field | Required | Description |
| :--------------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `name` | Yes | Skill name. Must use lowercase letters, numbers, and hyphens only (max 64 characters). Should match the directory name. |
| `description` | Yes | What the Skill does and when to use it (max 1024 characters). Claude uses this to decide when to apply the Skill. |
| `allowed-tools` | No | Tools Claude can use without asking permission when this Skill is active. Supports comma-separated values or YAML-style lists. See [Restrict tool access](#restrict-tool-access-with-allowed-tools). |
| `model` | No | [Model](https://docs.claude.com/en/docs/about-claude/models/overview) to use when this Skill is active (e.g., `claude-sonnet-4-20250514`). Defaults to the conversation's model. |
| `context` | No | Set to `fork` to run the Skill in a forked sub-agent context with its own conversation history. |
| `agent` | No | Specify which [agent type](/en/sub-agents#built-in-subagents) to use when `context: fork` is set (e.g., `Explore`, `Plan`, `general-purpose`, or a custom agent name from `.claude/agents/`). Defaults to `general-purpose` if not specified. Only applicable when combined with `context: fork`. |
| `hooks` | No | Define hooks scoped to this Skill's lifecycle. Supports `PreToolUse`, `PostToolUse`, and `Stop` events. |
| `user-invocable` | No | Controls whether the Skill appears in the slash command menu. Does not affect the [`Skill` tool](/en/slash-commands#skill-tool) or automatic discovery. Defaults to `true`. See [Control Skill visibility](#control-skill-visibility). |
See the [best practices guide](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/best-practices) for complete authoring guidance including validation rules.
### Update or delete a Skill
To update a Skill, edit its `SKILL.md` file directly. To remove a Skill, delete its directory. Changes take effect immediately.
### Add supporting files with progressive disclosure
Skills share Claude's context window with conversation history, other Skills, and your request. To keep context focused, use **progressive disclosure**: put essential information in `SKILL.md` and detailed reference material in separate files that Claude reads only when needed.
This approach lets you bundle comprehensive documentation, examples, and scripts without consuming context upfront. Claude loads additional files only when the task requires them.
<Tip>Keep `SKILL.md` under 500 lines for optimal performance. If your content exceeds this, split detailed reference material into separate files.</Tip>
#### Example: multi-file Skill structure
Claude discovers supporting files through links in your `SKILL.md`. The following example shows a Skill with detailed documentation in separate files and utility scripts that Claude can execute without reading:
```
my-skill/
├── SKILL.md (required - overview and navigation)
├── reference.md (detailed API docs - loaded when needed)
├── examples.md (usage examples - loaded when needed)
└── scripts/
└── helper.py (utility script - executed, not loaded)
```
The `SKILL.md` file references these supporting files so Claude knows they exist:
````markdown theme={null}
## Overview
[Essential instructions here]
## Additional resources
- For complete API details, see [reference.md](reference.md)
- For usage examples, see [examples.md](examples.md)
## Utility scripts
To validate input files, run the helper script. It checks for required fields and returns any validation errors:
```bash
python scripts/helper.py input.txt
```
````
<Tip>Keep references one level deep. Link directly from `SKILL.md` to reference files. Deeply nested references (file A links to file B which links to file C) may result in Claude partially reading files.</Tip>
**Bundle utility scripts for zero-context execution.** Scripts in your Skill directory can be executed without loading their contents into context. Claude runs the script and only the output consumes tokens. This is useful for:
* Complex validation logic that would be verbose to describe in prose
* Data processing that's more reliable as tested code than generated code
* Operations that benefit from consistency across uses
In `SKILL.md`, tell Claude to run the script rather than read it:
```markdown theme={null}
Run the validation script to check the form:
python scripts/validate_form.py input.pdf
```
For complete guidance on structuring Skills, see the [best practices guide](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/best-practices#progressive-disclosure-patterns).
### Restrict tool access with allowed-tools
Use the `allowed-tools` frontmatter field to limit which tools Claude can use when a Skill is active. You can specify tools as a comma-separated string or a YAML list:
```yaml theme={null}
---
name: reading-files-safely
description: Read files without making changes. Use when you need read-only file access.
allowed-tools: Read, Grep, Glob
---
```
Or use YAML-style lists for better readability:
```yaml theme={null}
---
name: reading-files-safely
description: Read files without making changes. Use when you need read-only file access.
allowed-tools:
- Read
- Grep
- Glob
---
```
When this Skill is active, Claude can only use the specified tools (Read, Grep, Glob) without needing to ask for permission. This is useful for:
* Read-only Skills that shouldn't modify files
* Skills with limited scope: for example, only data analysis, no file writing
* Security-sensitive workflows where you want to restrict capabilities
If `allowed-tools` is omitted, the Skill doesn't restrict tools. Claude uses its standard permission model and may ask you to approve tool usage.
<Note>
`allowed-tools` is only supported for Skills in Claude Code.
</Note>
### Run Skills in a forked context
Use `context: fork` to run a Skill in an isolated sub-agent context with its own conversation history. This is useful for Skills that perform complex multi-step operations without cluttering the main conversation:
```yaml theme={null}
---
name: code-analysis
description: Analyze code quality and generate detailed reports
context: fork
---
```
### Define hooks for Skills
Skills can define hooks that run during the Skill's lifecycle. Use the `hooks` field to specify `PreToolUse`, `PostToolUse`, or `Stop` handlers:
```yaml theme={null}
---
name: secure-operations
description: Perform operations with additional security checks
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/security-check.sh $TOOL_INPUT"
once: true
---
```
The `once: true` option runs the hook only once per session. After the first successful execution, the hook is removed.
Hooks defined in a Skill are scoped to that Skill's execution and are automatically cleaned up when the Skill finishes.
See [Hooks](/en/hooks) for the complete hook configuration format.
### Control Skill visibility
Skills can be invoked in three ways:
1. **Manual invocation**: You type `/skill-name` in the prompt
2. **Programmatic invocation**: Claude calls it via the [`Skill` tool](/en/slash-commands#skill-tool)
3. **Automatic discovery**: Claude reads the Skill's description and loads it when relevant to the conversation
The `user-invocable` field controls only manual invocation. When set to `false`, the Skill is hidden from the slash command menu but Claude can still invoke it programmatically or discover it automatically.
To block programmatic invocation via the `Skill` tool, use `disable-model-invocation: true` instead.
#### When to use each setting
| Setting | Slash menu | `Skill` tool | Auto-discovery | Use case |
| :------------------------------- | :--------- | :----------- | :------------- | :-------------------------------------------------------------- |
| `user-invocable: true` (default) | Visible | Allowed | Yes | Skills you want users to invoke directly |
| `user-invocable: false` | Hidden | Allowed | Yes | Skills that Claude can use but users shouldn't invoke manually |
| `disable-model-invocation: true` | Visible | Blocked | Yes | Skills you want users to invoke but not Claude programmatically |
#### Example: model-only Skill
Set `user-invocable: false` to hide a Skill from the slash menu while still allowing Claude to invoke it programmatically:
```yaml theme={null}
---
name: internal-review-standards
description: Apply internal code review standards when reviewing pull requests
user-invocable: false
---
```
With this setting, users won't see the Skill in the `/` menu, but Claude can still invoke it via the `Skill` tool or discover it automatically based on context.
### Skills and subagents
There are two ways Skills and subagents can work together:
#### Give a subagent access to Skills
[Subagents](/en/sub-agents) do not automatically inherit Skills from the main conversation. To give a custom subagent access to specific Skills, list them in the subagent's `skills` field:
```yaml theme={null}
# .claude/agents/code-reviewer.md
---
name: code-reviewer
description: Review code for quality and best practices
skills: pr-review, security-check
---
```
The full content of each listed Skill is injected into the subagent's context at startup, not just made available for invocation. If the `skills` field is omitted, no Skills are loaded for that subagent.
<Note>
Built-in agents (Explore, Plan, general-purpose) do not have access to your Skills. Only custom subagents you define in `.claude/agents/` with an explicit `skills` field can use Skills.
</Note>
#### Run a Skill in a subagent context
Use `context: fork` and `agent` to run a Skill in a forked subagent with its own separate context. See [Run Skills in a forked context](#run-skills-in-a-forked-context) for details.
### Distribute Skills
You can share Skills in several ways:
* **Project Skills**: Commit `.claude/skills/` to version control. Anyone who clones the repository gets the Skills.
* **Plugins**: To share Skills across multiple repositories, create a `skills/` directory in your [plugin](/en/plugins) with Skill folders containing `SKILL.md` files. Distribute through a [plugin marketplace](/en/plugin-marketplaces).
* **Managed**: Administrators can deploy Skills organization-wide through [managed settings](/en/iam#managed-settings). See [Where Skills live](#where-skills-live) for managed Skill paths.
## Examples
These examples show common Skill patterns, from minimal single-file Skills to multi-file Skills with supporting documentation and scripts.
### Simple Skill (single file)
A minimal Skill needs only a `SKILL.md` file with frontmatter and instructions. This example helps Claude generate commit messages by examining staged changes:
```
commit-helper/
└── SKILL.md
```
```yaml theme={null}
---
name: generating-commit-messages
description: Generates clear commit messages from git diffs. Use when writing commit messages or reviewing staged changes.
---
# Generating Commit Messages
## Instructions
1. Run `git diff --staged` to see changes
2. I'll suggest a commit message with:
- Summary under 50 characters
- Detailed description
- Affected components
## Best practices
- Use present tense
- Explain what and why, not how
```
### Use multiple files
For complex Skills, use progressive disclosure to keep the main `SKILL.md` focused while providing detailed documentation in supporting files. This PDF processing Skill includes reference docs, utility scripts, and uses `allowed-tools` to restrict Claude to specific tools:
```
pdf-processing/
├── SKILL.md # Overview and quick start
├── FORMS.md # Form field mappings and filling instructions
├── REFERENCE.md # API details for pypdf and pdfplumber
└── scripts/
├── fill_form.py # Utility to populate form fields
└── validate.py # Checks PDFs for required fields
```
**`SKILL.md`**:
````yaml theme={null}
---
name: pdf-processing
description: Extract text, fill forms, merge PDFs. Use when working with PDF files, forms, or document extraction. Requires pypdf and pdfplumber packages.
allowed-tools: Read, Bash(python:*)
---
# PDF Processing
## Quick start
Extract text:
```python
import pdfplumber
with pdfplumber.open("doc.pdf") as pdf:
text = pdf.pages[0].extract_text()
```
For form filling, see [FORMS.md](FORMS.md).
For detailed API reference, see [REFERENCE.md](REFERENCE.md).
## Requirements
Packages must be installed in your environment:
```bash
pip install pypdf pdfplumber
```
````
<Note>
If your Skill requires external packages, list them in the description. Packages must be installed in your environment before Claude can use them.
</Note>
## Troubleshooting
### View and test Skills
To see which Skills Claude has access to, ask Claude a question like "What Skills are available?" Claude loads all available Skill names and descriptions into the context window when a conversation starts, so it can list the Skills it currently has access to.
To test a specific Skill, ask Claude to do a task that matches the Skill's description. For example, if your Skill has the description "Reviews pull requests for code quality", ask Claude to "Review the changes in my current branch." Claude automatically uses the Skill when the request matches its description.
### Skill not triggering
The description field is how Claude decides whether to use your Skill. Vague descriptions like "Helps with documents" don't give Claude enough information to match your Skill to relevant requests.
A good description answers two questions:
1. **What does this Skill do?** List the specific capabilities.
2. **When should Claude use it?** Include trigger terms users would mention.
```yaml theme={null}
description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.
```
This description works because it names specific actions (extract, fill, merge) and includes keywords users would say (PDF, forms, document extraction).
### Skill doesn't load
**Check the file path.** Skills must be in the correct directory with the exact filename `SKILL.md` (case-sensitive):
| Type | Path |
| :--------- | :---------------------------------------------------------------------- |
| Personal | `~/.claude/skills/my-skill/SKILL.md` |
| Project | `.claude/skills/my-skill/SKILL.md` |
| Enterprise | See [Where Skills live](#where-skills-live) for platform-specific paths |
| Plugin | `skills/my-skill/SKILL.md` inside the plugin directory |
**Check the YAML syntax.** Invalid YAML in the frontmatter prevents the Skill from loading. The frontmatter must start with `---` on line 1 (no blank lines before it), end with `---` before the Markdown content, and use spaces for indentation (not tabs).
**Run debug mode.** Use `claude --debug` to see Skill loading errors.
### Skill has errors
**Check dependencies are installed.** If your Skill uses external packages, they must be installed in your environment before Claude can use them.
**Check script permissions.** Scripts need execute permissions: `chmod +x scripts/*.py`
**Check file paths.** Use forward slashes (Unix style) in all paths. Use `scripts/helper.py`, not `scripts\helper.py`.
### Multiple Skills conflict
If Claude uses the wrong Skill or seems confused between similar Skills, the descriptions are probably too similar. Make each description distinct by using specific trigger terms.
For example, instead of two Skills with "data analysis" in both descriptions, differentiate them: one for "sales data in Excel files and CRM exports" and another for "log files and system metrics". The more specific your trigger terms, the easier it is for Claude to match the right Skill to your request.
### Plugin Skills not appearing
**Symptom**: You installed a plugin from a marketplace, but its Skills don't appear when you ask Claude "What Skills are available?"
**Solution**: Clear the plugin cache and reinstall:
```bash theme={null}
rm -rf ~/.claude/plugins/cache
```
Then restart Claude Code and reinstall the plugin:
```shell theme={null}
/plugin install plugin-name@marketplace-name
```
This forces Claude Code to re-download and re-register the plugin's Skills.
**If Skills still don't appear**, verify the plugin's directory structure is correct. Skills must be in a `skills/` directory at the plugin root:
```
my-plugin/
├── .claude-plugin/
│ └── plugin.json
└── skills/
└── my-skill/
└── SKILL.md
```
## Next steps
<CardGroup cols={2}>
<Card title="Authoring best practices" icon="lightbulb" href="https://docs.claude.com/en/docs/agents-and-tools/agent-skills/best-practices">
Write Skills that Claude can use effectively
</Card>
<Card title="Agent Skills overview" icon="book" href="https://docs.claude.com/en/docs/agents-and-tools/agent-skills/overview">
Learn how Skills work across Claude products
</Card>
<Card title="Use Skills in the Agent SDK" icon="cube" href="https://docs.claude.com/en/docs/agent-sdk/skills">
Use Skills programmatically with TypeScript and Python
</Card>
<Card title="Get started with Agent Skills" icon="rocket" href="https://docs.claude.com/en/docs/agents-and-tools/agent-skills/quickstart">
Create your first Skill
</Card>
</CardGroup>
---
> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

View file

@ -1,716 +0,0 @@
# Create custom subagents
> Create and use specialized AI subagents in Claude Code for task-specific workflows and improved context management.
Subagents are specialized AI assistants that handle specific types of tasks. Each subagent runs in its own context window with a custom system prompt, specific tool access, and independent permissions. When Claude encounters a task that matches a subagent's description, it delegates to that subagent, which works independently and returns results.
Subagents help you:
* **Preserve context** by keeping exploration and implementation out of your main conversation
* **Enforce constraints** by limiting which tools a subagent can use
* **Reuse configurations** across projects with user-level subagents
* **Specialize behavior** with focused system prompts for specific domains
* **Control costs** by routing tasks to faster, cheaper models like Haiku
Claude uses each subagent's description to decide when to delegate tasks. When you create a subagent, write a clear description so Claude knows when to use it.
Claude Code includes several built-in subagents like **Explore**, **Plan**, and **general-purpose**. You can also create custom subagents to handle specific tasks. This page covers the [built-in subagents](#built-in-subagents), [how to create your own](#quickstart-create-your-first-subagent), [full configuration options](#configure-subagents), [patterns for working with subagents](#work-with-subagents), and [example subagents](#example-subagents).
## Built-in subagents
Claude Code includes built-in subagents that Claude automatically uses when appropriate. Each inherits the parent conversation's permissions with additional tool restrictions.
<Tabs>
<Tab title="Explore">
A fast, read-only agent optimized for searching and analyzing codebases.
* **Model**: Haiku (fast, low-latency)
* **Tools**: Read-only tools (denied access to Write and Edit tools)
* **Purpose**: File discovery, code search, codebase exploration
Claude delegates to Explore when it needs to search or understand a codebase without making changes. This keeps exploration results out of your main conversation context.
When invoking Explore, Claude specifies a thoroughness level: **quick** for targeted lookups, **medium** for balanced exploration, or **very thorough** for comprehensive analysis.
</Tab>
<Tab title="Plan">
A research agent used during [plan mode](/en/common-workflows#use-plan-mode-for-safe-code-analysis) to gather context before presenting a plan.
* **Model**: Inherits from main conversation
* **Tools**: Read-only tools (denied access to Write and Edit tools)
* **Purpose**: Codebase research for planning
When you're in plan mode and Claude needs to understand your codebase, it delegates research to the Plan subagent. This prevents infinite nesting (subagents cannot spawn other subagents) while still gathering necessary context.
</Tab>
<Tab title="General-purpose">
A capable agent for complex, multi-step tasks that require both exploration and action.
* **Model**: Inherits from main conversation
* **Tools**: All tools
* **Purpose**: Complex research, multi-step operations, code modifications
Claude delegates to general-purpose when the task requires both exploration and modification, complex reasoning to interpret results, or multiple dependent steps.
</Tab>
<Tab title="Other">
Claude Code includes additional helper agents for specific tasks. These are typically invoked automatically, so you don't need to use them directly.
| Agent | Model | When Claude uses it |
| :---------------- | :------- | :------------------------------------------------------- |
| Bash | Inherits | Running terminal commands in a separate context |
| statusline-setup | Sonnet | When you run `/statusline` to configure your status line |
| Claude Code Guide | Haiku | When you ask questions about Claude Code features |
</Tab>
</Tabs>
Beyond these built-in subagents, you can create your own with custom prompts, tool restrictions, permission modes, hooks, and skills. The following sections show how to get started and customize subagents.
## Quickstart: create your first subagent
Subagents are defined in Markdown files with YAML frontmatter. You can [create them manually](#write-subagent-files) or use the `/agents` slash command.
This walkthrough guides you through creating a user-level subagent with the `/agent` command. The subagent reviews code and suggests improvements for the codebase.
<Steps>
<Step title="Open the subagents interface">
In Claude Code, run:
```
/agents
```
</Step>
<Step title="Create a new user-level agent">
Select **Create new agent**, then choose **User-level**. This saves the subagent to `~/.claude/agents/` so it's available in all your projects.
</Step>
<Step title="Generate with Claude">
Select **Generate with Claude**. When prompted, describe the subagent:
```
A code improvement agent that scans files and suggests improvements
for readability, performance, and best practices. It should explain
each issue, show the current code, and provide an improved version.
```
Claude generates the system prompt and configuration. Press `e` to open it in your editor if you want to customize it.
</Step>
<Step title="Select tools">
For a read-only reviewer, deselect everything except **Read-only tools**. If you keep all tools selected, the subagent inherits all tools available to the main conversation.
</Step>
<Step title="Select model">
Choose which model the subagent uses. For this example agent, select **Sonnet**, which balances capability and speed for analyzing code patterns.
</Step>
<Step title="Choose a color">
Pick a background color for the subagent. This helps you identify which subagent is running in the UI.
</Step>
<Step title="Save and try it out">
Save the subagent. It's available immediately (no restart needed). Try it:
```
Use the code-improver agent to suggest improvements in this project
```
Claude delegates to your new subagent, which scans the codebase and returns improvement suggestions.
</Step>
</Steps>
You now have a subagent you can use in any project on your machine to analyze codebases and suggest improvements.
You can also create subagents manually as Markdown files, define them via CLI flags, or distribute them through plugins. The following sections cover all configuration options.
## Configure subagents
### Use the /agents command
The `/agents` command provides an interactive interface for managing subagents. Run `/agents` to:
* View all available subagents (built-in, user, project, and plugin)
* Create new subagents with guided setup or Claude generation
* Edit existing subagent configuration and tool access
* Delete custom subagents
* See which subagents are active when duplicates exist
This is the recommended way to create and manage subagents. For manual creation or automation, you can also add subagent files directly.
### Choose the subagent scope
Subagents are Markdown files with YAML frontmatter. Store them in different locations depending on scope. When multiple subagents share the same name, the higher-priority location wins.
| Location | Scope | Priority | How to create |
| :--------------------------- | :---------------------- | :---------- | :------------------------------------ |
| `--agents` CLI flag | Current session | 1 (highest) | Pass JSON when launching Claude Code |
| `.claude/agents/` | Current project | 2 | Interactive or manual |
| `~/.claude/agents/` | All your projects | 3 | Interactive or manual |
| Plugin's `agents/` directory | Where plugin is enabled | 4 (lowest) | Installed with [plugins](/en/plugins) |
**Project subagents** (`.claude/agents/`) are ideal for subagents specific to a codebase. Check them into version control so your team can use and improve them collaboratively.
**User subagents** (`~/.claude/agents/`) are personal subagents available in all your projects.
**CLI-defined subagents** are passed as JSON when launching Claude Code. They exist only for that session and aren't saved to disk, making them useful for quick testing or automation scripts:
```bash theme={null}
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer. Use proactively after code changes.",
"prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
"tools": ["Read", "Grep", "Glob", "Bash"],
"model": "sonnet"
}
}'
```
The `--agents` flag accepts JSON with the same fields as [frontmatter](#supported-frontmatter-fields). Use `prompt` for the system prompt (equivalent to the markdown body in file-based subagents). See the [CLI reference](/en/cli-reference#agents-flag-format) for the full JSON format.
**Plugin subagents** come from [plugins](/en/plugins) you've installed. They appear in `/agents` alongside your custom subagents. See the [plugin components reference](/en/plugins-reference#agents) for details on creating plugin subagents.
### Write subagent files
Subagent files use YAML frontmatter for configuration, followed by the system prompt in Markdown:
<Note>
Subagents are loaded at session start. If you create a subagent by manually adding a file, restart your session or use `/agents` to load it immediately.
</Note>
```markdown theme={null}
---
name: code-reviewer
description: Reviews code for quality and best practices
tools: Read, Glob, Grep
model: sonnet
---
You are a code reviewer. When invoked, analyze the code and provide
specific, actionable feedback on quality, security, and best practices.
```
The frontmatter defines the subagent's metadata and configuration. The body becomes the system prompt that guides the subagent's behavior. Subagents receive only this system prompt (plus basic environment details like working directory), not the full Claude Code system prompt.
#### Supported frontmatter fields
The following fields can be used in the YAML frontmatter. Only `name` and `description` are required.
| Field | Required | Description |
| :---------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name` | Yes | Unique identifier using lowercase letters and hyphens |
| `description` | Yes | When Claude should delegate to this subagent |
| `tools` | No | [Tools](#available-tools) the subagent can use. Inherits all tools if omitted |
| `disallowedTools` | No | Tools to deny, removed from inherited or specified list |
| `model` | No | [Model](#choose-a-model) to use: `sonnet`, `opus`, `haiku`, or `inherit`. Defaults to `sonnet` |
| `permissionMode` | No | [Permission mode](#permission-modes): `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, or `plan` |
| `skills` | No | [Skills](/en/skills) to load into the subagent's context at startup. The full skill content is injected, not just made available for invocation. Subagents don't inherit skills from the parent conversation |
| `hooks` | No | [Lifecycle hooks](#define-hooks-for-subagents) scoped to this subagent |
### Choose a model
The `model` field controls which [AI model](/en/model-config) the subagent uses:
* **Model alias**: Use one of the available aliases: `sonnet`, `opus`, or `haiku`
* **inherit**: Use the same model as the main conversation (useful for consistency)
* **Omitted**: If not specified, uses the default model configured for subagents (`sonnet`)
### Control subagent capabilities
You can control what subagents can do through tool access, permission modes, and conditional rules.
#### Available tools
Subagents can use any of Claude Code's [internal tools](/en/settings#tools-available-to-claude). By default, subagents inherit all tools from the main conversation, including MCP tools.
To restrict tools, use the `tools` field (allowlist) or `disallowedTools` field (denylist):
```yaml theme={null}
---
name: safe-researcher
description: Research agent with restricted capabilities
tools: Read, Grep, Glob, Bash
disallowedTools: Write, Edit
---
```
#### Permission modes
The `permissionMode` field controls how the subagent handles permission prompts. Subagents inherit the permission context from the main conversation but can override the mode.
| Mode | Behavior |
| :------------------ | :----------------------------------------------------------------- |
| `default` | Standard permission checking with prompts |
| `acceptEdits` | Auto-accept file edits |
| `dontAsk` | Auto-deny permission prompts (explicitly allowed tools still work) |
| `bypassPermissions` | Skip all permission checks |
| `plan` | Plan mode (read-only exploration) |
<Warning>
Use `bypassPermissions` with caution. It skips all permission checks, allowing the subagent to execute any operation without approval.
</Warning>
If the parent uses `bypassPermissions`, this takes precedence and cannot be overridden.
#### Conditional rules with hooks
For more dynamic control over tool usage, use `PreToolUse` hooks to validate operations before they execute. This is useful when you need to allow some operations of a tool while blocking others.
This example creates a subagent that only allows read-only database queries. The `PreToolUse` hook runs the script specified in `command` before each Bash command executes:
```yaml theme={null}
---
name: db-reader
description: Execute read-only database queries
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
---
```
Claude Code [passes hook input as JSON](/en/hooks#pretooluse-input) via stdin to hook commands. The validation script reads this JSON, extracts the Bash command, and [exits with code 2](/en/hooks#exit-code-2-behavior) to block write operations:
```bash theme={null}
#!/bin/bash
# ./scripts/validate-readonly-query.sh
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
# Block SQL write operations (case-insensitive)
if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE)\b' > /dev/null; then
echo "Blocked: Only SELECT queries are allowed" >&2
exit 2
fi
exit 0
```
See [Hook input](/en/hooks#pretooluse-input) for the complete input schema and [exit codes](/en/hooks#exit-codes) for how exit codes affect behavior.
#### Disable specific subagents
You can prevent Claude from using specific subagents by adding them to the `deny` array in your [settings](/en/settings#permission-settings). Use the format `Task(subagent-name)` where `subagent-name` matches the subagent's name field.
```json theme={null}
{
"permissions": {
"deny": ["Task(Explore)", "Task(my-custom-agent)"]
}
}
```
This works for both built-in and custom subagents. You can also use the `--disallowedTools` CLI flag:
```bash theme={null}
claude --disallowedTools "Task(Explore)"
```
See [IAM documentation](/en/iam#tool-specific-permission-rules) for more details on permission rules.
### Define hooks for subagents
Subagents can define [hooks](/en/hooks) that run during the subagent's lifecycle. There are two ways to configure hooks:
1. **In the subagent's frontmatter**: Define hooks that run only while that subagent is active
2. **In `settings.json`**: Define hooks that run in the main session when subagents start or stop
#### Hooks in subagent frontmatter
Define hooks directly in the subagent's markdown file. These hooks only run while that specific subagent is active and are cleaned up when it finishes.
| Event | Matcher input | When it fires |
| :------------ | :------------ | :------------------------------ |
| `PreToolUse` | Tool name | Before the subagent uses a tool |
| `PostToolUse` | Tool name | After the subagent uses a tool |
| `Stop` | (none) | When the subagent finishes |
This example validates Bash commands with the `PreToolUse` hook and runs a linter after file edits with `PostToolUse`:
```yaml theme={null}
---
name: code-reviewer
description: Review code changes with automatic linting
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-command.sh $TOOL_INPUT"
PostToolUse:
- matcher: "Edit|Write"
hooks:
- type: command
command: "./scripts/run-linter.sh"
---
```
`Stop` hooks in frontmatter are automatically converted to `SubagentStop` events.
#### Project-level hooks for subagent events
Configure hooks in `settings.json` that respond to subagent lifecycle events in the main session. Use the `matcher` field to target specific agent types by name.
| Event | Matcher input | When it fires |
| :-------------- | :-------------- | :------------------------------- |
| `SubagentStart` | Agent type name | When a subagent begins execution |
| `SubagentStop` | Agent type name | When a subagent completes |
This example runs setup and cleanup scripts only when the `db-agent` subagent starts and stops:
```json theme={null}
{
"hooks": {
"SubagentStart": [
{
"matcher": "db-agent",
"hooks": [
{ "type": "command", "command": "./scripts/setup-db-connection.sh" }
]
}
],
"SubagentStop": [
{
"matcher": "db-agent",
"hooks": [
{ "type": "command", "command": "./scripts/cleanup-db-connection.sh" }
]
}
]
}
}
```
See [Hooks](/en/hooks) for the complete hook configuration format.
## Work with subagents
### Understand automatic delegation
Claude automatically delegates tasks based on the task description in your request, the `description` field in subagent configurations, and current context. To encourage proactive delegation, include phrases like "use proactively" in your subagent's description field.
You can also request a specific subagent explicitly:
```
Use the test-runner subagent to fix failing tests
Have the code-reviewer subagent look at my recent changes
```
### Run subagents in foreground or background
Subagents can run in the foreground (blocking) or background (concurrent):
* **Foreground subagents** block the main conversation until complete. Permission prompts and clarifying questions (like [`AskUserQuestion`](/en/settings#tools-available-to-claude)) are passed through to you.
* **Background subagents** run concurrently while you continue working. They inherit the parent's permissions and auto-deny anything not pre-approved. If a background subagent needs a permission it doesn't have or needs to ask clarifying questions, that tool call fails but the subagent continues. MCP tools are not available in background subagents.
If a background subagent fails due to missing permissions, you can [resume it](#resume-subagents) in the foreground to retry with interactive prompts.
Claude decides whether to run subagents in the foreground or background based on the task. You can also:
* Ask Claude to "run this in the background"
* Press **Ctrl+B** to background a running task
To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](/en/settings#environment-variables).
### Common patterns
#### Isolate high-volume operations
One of the most effective uses for subagents is isolating operations that produce large amounts of output. Running tests, fetching documentation, or processing log files can consume significant context. By delegating these to a subagent, the verbose output stays in the subagent's context while only the relevant summary returns to your main conversation.
```
Use a subagent to run the test suite and report only the failing tests with their error messages
```
#### Run parallel research
For independent investigations, spawn multiple subagents to work simultaneously:
```
Research the authentication, database, and API modules in parallel using separate subagents
```
Each subagent explores its area independently, then Claude synthesizes the findings. This works best when the research paths don't depend on each other.
<Warning>
When subagents complete, their results return to your main conversation. Running many subagents that each return detailed results can consume significant context.
</Warning>
#### Chain subagents
For multi-step workflows, ask Claude to use subagents in sequence. Each subagent completes its task and returns results to Claude, which then passes relevant context to the next subagent.
```
Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them
```
### Choose between subagents and main conversation
Use the **main conversation** when:
* The task needs frequent back-and-forth or iterative refinement
* Multiple phases share significant context (planning → implementation → testing)
* You're making a quick, targeted change
* Latency matters. Subagents start fresh and may need time to gather context
Use **subagents** when:
* The task produces verbose output you don't need in your main context
* You want to enforce specific tool restrictions or permissions
* The work is self-contained and can return a summary
Consider [Skills](/en/skills) instead when you want reusable prompts or workflows that run in the main conversation context rather than isolated subagent context.
<Note>
Subagents cannot spawn other subagents. If your workflow requires nested delegation, use [Skills](/en/skills) or [chain subagents](#chain-subagents) from the main conversation.
</Note>
### Manage subagent context
#### Resume subagents
Each subagent invocation creates a new instance with fresh context. To continue an existing subagent's work instead of starting over, ask Claude to resume it.
Resumed subagents retain their full conversation history, including all previous tool calls, results, and reasoning. The subagent picks up exactly where it stopped rather than starting fresh.
When a subagent completes, Claude receives its agent ID. To resume a subagent, ask Claude to continue the previous work:
```
Use the code-reviewer subagent to review the authentication module
[Agent completes]
Continue that code review and now analyze the authorization logic
[Claude resumes the subagent with full context from previous conversation]
```
You can also ask Claude for the agent ID if you want to reference it explicitly, or find IDs in the transcript files at `~/.claude/projects/{project}/{sessionId}/subagents/`. Each transcript is stored as `agent-{agentId}.jsonl`.
For programmatic usage, see [Subagents in the Agent SDK](/en/agent-sdk/subagents).
Subagent transcripts persist independently of the main conversation:
* **Main conversation compaction**: When the main conversation compacts, subagent transcripts are unaffected. They're stored in separate files.
* **Session persistence**: Subagent transcripts persist within their session. You can [resume a subagent](#resume-subagents) after restarting Claude Code by resuming the same session.
* **Automatic cleanup**: Transcripts are cleaned up based on the `cleanupPeriodDays` setting (default: 30 days).
#### Auto-compaction
Subagents support automatic compaction using the same logic as the main conversation. When a subagent's context approaches its limit, Claude Code summarizes older messages to free up space while preserving important context.
Compaction events are logged in subagent transcript files:
```json theme={null}
{
"type": "system",
"subtype": "compact_boundary",
"compactMetadata": {
"trigger": "auto",
"preTokens": 167189
}
}
```
The `preTokens` value shows how many tokens were used before compaction occurred.
## Example subagents
These examples demonstrate effective patterns for building subagents. Use them as starting points, or generate a customized version with Claude.
<Tip>
**Best practices:**
* **Design focused subagents:** each subagent should excel at one specific task
* **Write detailed descriptions:** Claude uses the description to decide when to delegate
* **Limit tool access:** grant only necessary permissions for security and focus
* **Check into version control:** share project subagents with your team
</Tip>
### Code reviewer
A read-only subagent that reviews code without modifying it. This example shows how to design a focused subagent with limited tool access (no Edit or Write) and a detailed prompt that specifies exactly what to look for and how to format output.
```markdown theme={null}
---
name: code-reviewer
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.
tools: Read, Grep, Glob, Bash
model: inherit
---
You are a senior code reviewer ensuring high standards of code quality and security.
When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately
Review checklist:
- Code is clear and readable
- Functions and variables are well-named
- No duplicated code
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented
- Good test coverage
- Performance considerations addressed
Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)
Include specific examples of how to fix issues.
```
### Debugger
A subagent that can both analyze and fix issues. Unlike the code reviewer, this one includes Edit because fixing bugs requires modifying code. The prompt provides a clear workflow from diagnosis to verification.
```markdown theme={null}
---
name: debugger
description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.
tools: Read, Edit, Bash, Grep, Glob
---
You are an expert debugger specializing in root cause analysis.
When invoked:
1. Capture error message and stack trace
2. Identify reproduction steps
3. Isolate the failure location
4. Implement minimal fix
5. Verify solution works
Debugging process:
- Analyze error messages and logs
- Check recent code changes
- Form and test hypotheses
- Add strategic debug logging
- Inspect variable states
For each issue, provide:
- Root cause explanation
- Evidence supporting the diagnosis
- Specific code fix
- Testing approach
- Prevention recommendations
Focus on fixing the underlying issue, not the symptoms.
```
### Data scientist
A domain-specific subagent for data analysis work. This example shows how to create subagents for specialized workflows outside of typical coding tasks. It explicitly sets `model: sonnet` for more capable analysis.
```markdown theme={null}
---
name: data-scientist
description: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries.
tools: Bash, Read, Write
model: sonnet
---
You are a data scientist specializing in SQL and BigQuery analysis.
When invoked:
1. Understand the data analysis requirement
2. Write efficient SQL queries
3. Use BigQuery command line tools (bq) when appropriate
4. Analyze and summarize results
5. Present findings clearly
Key practices:
- Write optimized SQL queries with proper filters
- Use appropriate aggregations and joins
- Include comments explaining complex logic
- Format results for readability
- Provide data-driven recommendations
For each analysis:
- Explain the query approach
- Document any assumptions
- Highlight key findings
- Suggest next steps based on data
Always ensure queries are efficient and cost-effective.
```
### Database query validator
A subagent that allows Bash access but validates commands to permit only read-only SQL queries. This example shows how to use `PreToolUse` hooks for conditional validation when you need finer control than the `tools` field provides.
```markdown theme={null}
---
name: db-reader
description: Execute read-only database queries. Use when analyzing data or generating reports.
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
---
You are a database analyst with read-only access. Execute SELECT queries to answer questions about the data.
When asked to analyze data:
1. Identify which tables contain the relevant data
2. Write efficient SELECT queries with appropriate filters
3. Present results clearly with context
You cannot modify data. If asked to INSERT, UPDATE, DELETE, or modify schema, explain that you only have read access.
```
Claude Code [passes hook input as JSON](/en/hooks#pretooluse-input) via stdin to hook commands. The validation script reads this JSON, extracts the command being executed, and checks it against a list of SQL write operations. If a write operation is detected, the script [exits with code 2](/en/hooks#exit-code-2-behavior) to block execution and returns an error message to Claude via stderr.
Create the validation script anywhere in your project. The path must match the `command` field in your hook configuration:
```bash theme={null}
#!/bin/bash
# Blocks SQL write operations, allows SELECT queries
# Read JSON input from stdin
INPUT=$(cat)
# Extract the command field from tool_input using jq
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
if [ -z "$COMMAND" ]; then
exit 0
fi
# Block write operations (case-insensitive)
if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE|REPLACE|MERGE)\b' > /dev/null; then
echo "Blocked: Write operations not allowed. Use SELECT queries only." >&2
exit 2
fi
exit 0
```
Make the script executable:
```bash theme={null}
chmod +x ./scripts/validate-readonly-query.sh
```
The hook receives JSON via stdin with the Bash command in `tool_input.command`. Exit code 2 blocks the operation and feeds the error message back to Claude. See [Hooks](/en/hooks#exit-codes) for details on exit codes and [Hook input](/en/hooks#pretooluse-input) for the complete input schema.
## Next steps
Now that you understand subagents, explore these related features:
* [Distribute subagents with plugins](/en/plugins) to share subagents across teams or projects
* [Run Claude Code programmatically](/en/headless) with the Agent SDK for CI/CD and automation
* [Use MCP servers](/en/mcp) to give subagents access to external tools and data
---
> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

View file

@ -1,338 +0,0 @@
# Get started with Claude Code hooks
> Learn how to customize and extend Claude Code's behavior by registering shell commands
Claude Code hooks are user-defined shell commands that execute at various points
in Claude Code's lifecycle. Hooks provide deterministic control over Claude
Code's behavior, ensuring certain actions always happen rather than relying on
the LLM to choose to run them.
<Tip>
For reference documentation on hooks, see [Hooks reference](/en/hooks).
</Tip>
Example use cases for hooks include:
* **Notifications**: Customize how you get notified when Claude Code is awaiting
your input or permission to run something.
* **Automatic formatting**: Run `prettier` on .ts files, `gofmt` on .go files,
etc. after every file edit.
* **Logging**: Track and count all executed commands for compliance or
debugging.
* **Feedback**: Provide automated feedback when Claude Code produces code that
does not follow your codebase conventions.
* **Custom permissions**: Block modifications to production files or sensitive
directories.
By encoding these rules as hooks rather than prompting instructions, you turn
suggestions into app-level code that executes every time it is expected to run.
<Warning>
You must consider the security implication of hooks as you add them, because hooks run automatically during the agent loop with your current environment's credentials.
For example, malicious hooks code can exfiltrate your data. Always review your hooks implementation before registering them.
For full security best practices, see [Security Considerations](/en/hooks#security-considerations) in the hooks reference documentation.
</Warning>
## Hook Events Overview
Claude Code provides several hook events that run at different points in the
workflow:
* **PreToolUse**: Runs before tool calls (can block them)
* **PermissionRequest**: Runs when a permission dialog is shown (can allow or deny)
* **PostToolUse**: Runs after tool calls complete
* **UserPromptSubmit**: Runs when the user submits a prompt, before Claude processes it
* **Notification**: Runs when Claude Code sends notifications
* **Stop**: Runs when Claude Code finishes responding
* **SubagentStop**: Runs when subagent tasks complete
* **PreCompact**: Runs before Claude Code is about to run a compact operation
* **SessionStart**: Runs when Claude Code starts a new session or resumes an existing session
* **SessionEnd**: Runs when Claude Code session ends
Each event receives different data and can control Claude's behavior in
different ways.
## Quickstart
In this quickstart, you'll add a hook that logs the shell commands that Claude
Code runs.
### Prerequisites
Install `jq` for JSON processing in the command line.
### Step 1: Open hooks configuration
Run the `/hooks` [slash command](/en/slash-commands) and select
the `PreToolUse` hook event.
`PreToolUse` hooks run before tool calls and can block them while providing
Claude feedback on what to do differently.
### Step 2: Add a matcher
Select `+ Add new matcher…` to run your hook only on Bash tool calls.
Type `Bash` for the matcher.
<Note>You can use `*` to match all tools.</Note>
### Step 3: Add the hook
Select `+ Add new hook…` and enter this command:
```bash theme={null}
jq -r '"\(.tool_input.command) - \(.tool_input.description // "No description")"' >> ~/.claude/bash-command-log.txt
```
### Step 4: Save your configuration
For storage location, select `User settings` since you're logging to your home
directory. This hook will then apply to all projects, not just your current
project.
Then press `Esc` until you return to the REPL. Your hook is now registered.
### Step 5: Verify your hook
Run `/hooks` again or check `~/.claude/settings.json` to see your configuration:
```json theme={null}
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "jq -r '\"\\(.tool_input.command) - \\(.tool_input.description // \"No description\")\"' >> ~/.claude/bash-command-log.txt"
}
]
}
]
}
}
```
### Step 6: Test your hook
Ask Claude to run a simple command like `ls` and check your log file:
```bash theme={null}
cat ~/.claude/bash-command-log.txt
```
You should see entries like:
```
ls - Lists files and directories
```
## More Examples
<Note>
For a complete example implementation, see the [bash command validator example](https://github.com/anthropics/claude-code/blob/main/examples/hooks/bash_command_validator_example.py) in our public codebase.
</Note>
### Code Formatting Hook
Automatically format TypeScript files after editing:
```json theme={null}
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.file_path' | { read file_path; if echo \"$file_path\" | grep -q '\\.ts$'; then npx prettier --write \"$file_path\"; fi; }"
}
]
}
]
}
}
```
### Markdown Formatting Hook
Automatically fix missing language tags and formatting issues in markdown files:
```json theme={null}
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/markdown_formatter.py"
}
]
}
]
}
}
```
Create `.claude/hooks/markdown_formatter.py` with this content:
````python theme={null}
#!/usr/bin/env python3
"""
Markdown formatter for Claude Code output.
Fixes missing language tags and spacing issues while preserving code content.
"""
import json
import sys
import re
import os
def detect_language(code):
"""Best-effort language detection from code content."""
s = code.strip()
# JSON detection
if re.search(r'^\s*[{\[]', s):
try:
json.loads(s)
return 'json'
except:
pass
# Python detection
if re.search(r'^\s*def\s+\w+\s*\(', s, re.M) or \
re.search(r'^\s*(import|from)\s+\w+', s, re.M):
return 'python'
# JavaScript detection
if re.search(r'\b(function\s+\w+\s*\(|const\s+\w+\s*=)', s) or \
re.search(r'=>|console\.(log|error)', s):
return 'javascript'
# Bash detection
if re.search(r'^#!.*\b(bash|sh)\b', s, re.M) or \
re.search(r'\b(if|then|fi|for|in|do|done)\b', s):
return 'bash'
# SQL detection
if re.search(r'\b(SELECT|INSERT|UPDATE|DELETE|CREATE)\s+', s, re.I):
return 'sql'
return 'text'
def format_markdown(content):
"""Format markdown content with language detection."""
# Fix unlabeled code fences
def add_lang_to_fence(match):
indent, info, body, closing = match.groups()
if not info.strip():
lang = detect_language(body)
return f"{indent}```{lang}\n{body}{closing}\n"
return match.group(0)
fence_pattern = r'(?ms)^([ \t]{0,3})```([^\n]*)\n(.*?)(\n\1```)\s*$'
content = re.sub(fence_pattern, add_lang_to_fence, content)
# Fix excessive blank lines (only outside code fences)
content = re.sub(r'\n{3,}', '\n\n', content)
return content.rstrip() + '\n'
# Main execution
try:
input_data = json.load(sys.stdin)
file_path = input_data.get('tool_input', {}).get('file_path', '')
if not file_path.endswith(('.md', '.mdx')):
sys.exit(0) # Not a markdown file
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
formatted = format_markdown(content)
if formatted != content:
with open(file_path, 'w', encoding='utf-8') as f:
f.write(formatted)
print(f"✓ Fixed markdown formatting in {file_path}")
except Exception as e:
print(f"Error formatting markdown: {e}", file=sys.stderr)
sys.exit(1)
````
Make the script executable:
```bash theme={null}
chmod +x .claude/hooks/markdown_formatter.py
```
This hook automatically:
* Detects programming languages in unlabeled code blocks
* Adds appropriate language tags for syntax highlighting
* Fixes excessive blank lines while preserving code content
* Only processes markdown files (`.md`, `.mdx`)
### Custom Notification Hook
Get desktop notifications when Claude needs input:
```json theme={null}
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "notify-send 'Claude Code' 'Awaiting your input'"
}
]
}
]
}
}
```
### File Protection Hook
Block edits to sensitive files:
```json theme={null}
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "python3 -c \"import json, sys; data=json.load(sys.stdin); path=data.get('tool_input',{}).get('file_path',''); sys.exit(2 if any(p in path for p in ['.env', 'package-lock.json', '.git/']) else 0)\""
}
]
}
]
}
}
```
## Learn more
* For reference documentation on hooks, see [Hooks reference](/en/hooks).
* For comprehensive security best practices and safety guidelines, see [Security Considerations](/en/hooks#security-considerations) in the hooks reference documentation.
* For troubleshooting steps and debugging techniques, see [Debugging](/en/hooks#debugging) in the hooks reference
documentation.
---
> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

View file

@ -1,36 +0,0 @@
# Claude Code Documentation
**Purpose**: External documentation for Claude Code to be integrated into main context
---
## Structure
```
to-be-consumed/claude-code-docs/
├── navigation.md (this file)
└── [external documentation files]
```
---
## Quick Routes
| Task | Path |
|------|------|
| **View docs** | `./` |
| **To-be-consumed** | `../navigation.md` |
---
## By Type
**External Docs** → Documentation from external sources
**To Be Integrated** → Content awaiting integration into main context
---
## Related Context
- **To-be-consumed Navigation** → `../navigation.md`
- **Development** → `../../development/navigation.md`

View file

@ -1,413 +0,0 @@
# Create plugins
> Create custom plugins to extend Claude Code with slash commands, agents, hooks, Skills, and MCP servers.
Plugins let you extend Claude Code with custom functionality that can be shared across projects and teams. This guide covers creating your own plugins with slash commands, agents, Skills, hooks, and MCP servers.
Looking to install existing plugins? See [Discover and install plugins](/en/discover-plugins). For complete technical specifications, see [Plugins reference](/en/plugins-reference).
## When to use plugins vs standalone configuration
Claude Code supports two ways to add custom slash commands, agents, and hooks:
| Approach | Slash command names | Best for |
| :---------------------------------------------------------- | :------------------- | :---------------------------------------------------------------------------------------------- |
| **Standalone** (`.claude/` directory) | `/hello` | Personal workflows, project-specific customizations, quick experiments |
| **Plugins** (directories with `.claude-plugin/plugin.json`) | `/plugin-name:hello` | Sharing with teammates, distributing to community, versioned releases, reusable across projects |
**Use standalone configuration when**:
* You're customizing Claude Code for a single project
* The configuration is personal and doesn't need to be shared
* You're experimenting with slash commands or hooks before packaging them
* You want short slash command names like `/hello` or `/review`
**Use plugins when**:
* You want to share functionality with your team or community
* You need the same slash commands/agents across multiple projects
* You want version control and easy updates for your extensions
* You're distributing through a marketplace
* You're okay with namespaced slash commands like `/my-plugin:hello` (namespacing prevents conflicts between plugins)
<Tip>
Start with standalone configuration in `.claude/` for quick iteration, then [convert to a plugin](#convert-existing-configurations-to-plugins) when you're ready to share.
</Tip>
## Quickstart
This quickstart walks you through creating a plugin with a custom slash command. You'll create a manifest (the configuration file that defines your plugin), add a slash command, and test it locally using the `--plugin-dir` flag.
### Prerequisites
* Claude Code [installed and authenticated](/en/quickstart#step-1-install-claude-code)
* Claude Code version 1.0.33 or later (run `claude --version` to check)
<Note>
If you don't see the `/plugin` command, update Claude Code to the latest version. See [Troubleshooting](/en/troubleshooting) for upgrade instructions.
</Note>
### Create your first plugin
<Steps>
<Step title="Create the plugin directory">
Every plugin lives in its own directory containing a manifest and your custom commands, agents, or hooks. Create one now:
```bash theme={null}
mkdir my-first-plugin
```
</Step>
<Step title="Create the plugin manifest">
The manifest file at `.claude-plugin/plugin.json` defines your plugin's identity: its name, description, and version. Claude Code uses this metadata to display your plugin in the plugin manager.
Create the `.claude-plugin` directory inside your plugin folder:
```bash theme={null}
mkdir my-first-plugin/.claude-plugin
```
Then create `my-first-plugin/.claude-plugin/plugin.json` with this content:
```json my-first-plugin/.claude-plugin/plugin.json theme={null}
{
"name": "my-first-plugin",
"description": "A greeting plugin to learn the basics",
"version": "1.0.0",
"author": {
"name": "Your Name"
}
}
```
| Field | Purpose |
| :------------ | :--------------------------------------------------------------------------------------------------------------------- |
| `name` | Unique identifier and slash command namespace. Slash commands are prefixed with this (e.g., `/my-first-plugin:hello`). |
| `description` | Shown in the plugin manager when browsing or installing plugins. |
| `version` | Track releases using [semantic versioning](/en/plugins-reference#version-management). |
| `author` | Optional. Helpful for attribution. |
For additional fields like `homepage`, `repository`, and `license`, see the [full manifest schema](/en/plugins-reference#plugin-manifest-schema).
</Step>
<Step title="Add a slash command">
Slash commands are Markdown files in the `commands/` directory. The filename becomes the slash command name, prefixed with the plugin's namespace (`hello.md` in a plugin named `my-first-plugin` creates `/my-first-plugin:hello`). The Markdown content tells Claude how to respond when someone runs the slash command.
Create a `commands` directory in your plugin folder:
```bash theme={null}
mkdir my-first-plugin/commands
```
Then create `my-first-plugin/commands/hello.md` with this content:
```markdown my-first-plugin/commands/hello.md theme={null}
---
description: Greet the user with a friendly message
---
# Hello Command
Greet the user warmly and ask how you can help them today.
```
</Step>
<Step title="Test your plugin">
Run Claude Code with the `--plugin-dir` flag to load your plugin:
```bash theme={null}
claude --plugin-dir ./my-first-plugin
```
Once Claude Code starts, try your new command:
```shell theme={null}
/my-first-plugin:hello
```
You'll see Claude respond with a greeting. Run `/help` to see your command listed under the plugin namespace.
<Note>
**Why namespacing?** Plugin slash commands are always namespaced (like `/greet:hello`) to prevent conflicts when multiple plugins have commands with the same name.
To change the namespace prefix, update the `name` field in `plugin.json`.
</Note>
</Step>
<Step title="Add slash command arguments">
Make your slash command dynamic by accepting user input. The `$ARGUMENTS` placeholder captures any text the user provides after the slash command.
Update your `hello.md` file:
```markdown my-first-plugin/commands/hello.md theme={null}
---
description: Greet the user with a personalized message
---
# Hello Command
Greet the user named "$ARGUMENTS" warmly and ask how you can help them today. Make the greeting personal and encouraging.
```
Restart Claude Code to pick up the changes, then try the command with your name:
```shell theme={null}
/my-first-plugin:hello Alex
```
Claude will greet you by name. For more argument options like `$1`, `$2` for individual parameters, see [Slash commands](/en/slash-commands).
</Step>
</Steps>
You've successfully created and tested a plugin with these key components:
* **Plugin manifest** (`.claude-plugin/plugin.json`): describes your plugin's metadata
* **Commands directory** (`commands/`): contains your custom slash commands
* **Command arguments** (`$ARGUMENTS`): captures user input for dynamic behavior
<Tip>
The `--plugin-dir` flag is useful for development and testing. When you're ready to share your plugin with others, see [Create and distribute a plugin marketplace](/en/plugin-marketplaces).
</Tip>
## Plugin structure overview
You've created a plugin with a slash command, but plugins can include much more: custom agents, Skills, hooks, MCP servers, and LSP servers.
<Warning>
**Common mistake**: Don't put `commands/`, `agents/`, `skills/`, or `hooks/` inside the `.claude-plugin/` directory. Only `plugin.json` goes inside `.claude-plugin/`. All other directories must be at the plugin root level.
</Warning>
| Directory | Location | Purpose |
| :---------------- | :---------- | :---------------------------------------------- |
| `.claude-plugin/` | Plugin root | Contains only `plugin.json` manifest (required) |
| `commands/` | Plugin root | Slash commands as Markdown files |
| `agents/` | Plugin root | Custom agent definitions |
| `skills/` | Plugin root | Agent Skills with `SKILL.md` files |
| `hooks/` | Plugin root | Event handlers in `hooks.json` |
| `.mcp.json` | Plugin root | MCP server configurations |
| `.lsp.json` | Plugin root | LSP server configurations for code intelligence |
<Note>
**Next steps**: Ready to add more features? Jump to [Develop more complex plugins](#develop-more-complex-plugins) to add agents, hooks, MCP servers, and LSP servers. For complete technical specifications of all plugin components, see [Plugins reference](/en/plugins-reference).
</Note>
## Develop more complex plugins
Once you're comfortable with basic plugins, you can create more sophisticated extensions.
### Add Skills to your plugin
Plugins can include [Agent Skills](/en/skills) to extend Claude's capabilities. Skills are model-invoked: Claude automatically uses them based on the task context.
Add a `skills/` directory at your plugin root with Skill folders containing `SKILL.md` files:
```
my-plugin/
├── .claude-plugin/
│ └── plugin.json
└── skills/
└── code-review/
└── SKILL.md
```
Each `SKILL.md` needs frontmatter with `name` and `description` fields, followed by instructions:
```yaml theme={null}
---
name: code-review
description: Reviews code for best practices and potential issues. Use when reviewing code, checking PRs, or analyzing code quality.
---
When reviewing code, check for:
1. Code organization and structure
2. Error handling
3. Security concerns
4. Test coverage
```
After installing the plugin, restart Claude Code to load the Skills. For complete Skill authoring guidance including progressive disclosure and tool restrictions, see [Agent Skills](/en/skills).
### Add LSP servers to your plugin
<Tip>
For common languages like TypeScript, Python, and Rust, install the pre-built LSP plugins from the official marketplace. Create custom LSP plugins only when you need support for languages not already covered.
</Tip>
LSP (Language Server Protocol) plugins give Claude real-time code intelligence. If you need to support a language that doesn't have an official LSP plugin, you can create your own by adding an `.lsp.json` file to your plugin:
```json .lsp.json theme={null}
{
"go": {
"command": "gopls",
"args": ["serve"],
"extensionToLanguage": {
".go": "go"
}
}
}
```
Users installing your plugin must have the language server binary installed on their machine.
For complete LSP configuration options, see [LSP servers](/en/plugins-reference#lsp-servers).
### Organize complex plugins
For plugins with many components, organize your directory structure by functionality. For complete directory layouts and organization patterns, see [Plugin directory structure](/en/plugins-reference#plugin-directory-structure).
### Test your plugins locally
Use the `--plugin-dir` flag to test plugins during development. This loads your plugin directly without requiring installation.
```bash theme={null}
claude --plugin-dir ./my-plugin
```
As you make changes to your plugin, restart Claude Code to pick up the updates. Test your plugin components:
* Try your commands with `/command-name`
* Check that agents appear in `/agents`
* Verify hooks work as expected
<Tip>
You can load multiple plugins at once by specifying the flag multiple times:
```bash theme={null}
claude --plugin-dir ./plugin-one --plugin-dir ./plugin-two
```
</Tip>
### Debug plugin issues
If your plugin isn't working as expected:
1. **Check the structure**: Ensure your directories are at the plugin root, not inside `.claude-plugin/`
2. **Test components individually**: Check each command, agent, and hook separately
3. **Use validation and debugging tools**: See [Debugging and development tools](/en/plugins-reference#debugging-and-development-tools) for CLI commands and troubleshooting techniques
### Share your plugins
When your plugin is ready to share:
1. **Add documentation**: Include a `README.md` with installation and usage instructions
2. **Version your plugin**: Use [semantic versioning](/en/plugins-reference#version-management) in your `plugin.json`
3. **Create or use a marketplace**: Distribute through [plugin marketplaces](/en/plugin-marketplaces) for installation
4. **Test with others**: Have team members test the plugin before wider distribution
Once your plugin is in a marketplace, others can install it using the instructions in [Discover and install plugins](/en/discover-plugins).
<Note>
For complete technical specifications, debugging techniques, and distribution strategies, see [Plugins reference](/en/plugins-reference).
</Note>
## Convert existing configurations to plugins
If you already have custom commands, Skills, or hooks in your `.claude/` directory, you can convert them into a plugin for easier sharing and distribution.
### Migration steps
<Steps>
<Step title="Create the plugin structure">
Create a new plugin directory:
```bash theme={null}
mkdir -p my-plugin/.claude-plugin
```
Create the manifest file at `my-plugin/.claude-plugin/plugin.json`:
```json my-plugin/.claude-plugin/plugin.json theme={null}
{
"name": "my-plugin",
"description": "Migrated from standalone configuration",
"version": "1.0.0"
}
```
</Step>
<Step title="Copy your existing files">
Copy your existing configurations to the plugin directory:
```bash theme={null}
# Copy commands
cp -r .claude/commands my-plugin/
# Copy agents (if any)
cp -r .claude/agents my-plugin/
# Copy skills (if any)
cp -r .claude/skills my-plugin/
```
</Step>
<Step title="Migrate hooks">
If you have hooks in your settings, create a hooks directory:
```bash theme={null}
mkdir my-plugin/hooks
```
Create `my-plugin/hooks/hooks.json` with your hooks configuration. Copy the `hooks` object from your `.claude/settings.json` or `settings.local.json`—the format is the same:
```json my-plugin/hooks/hooks.json theme={null}
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [{ "type": "command", "command": "npm run lint:fix $FILE" }]
}
]
}
}
```
</Step>
<Step title="Test your migrated plugin">
Load your plugin to verify everything works:
```bash theme={null}
claude --plugin-dir ./my-plugin
```
Test each component: run your commands, check agents appear in `/agents`, and verify hooks trigger correctly.
</Step>
</Steps>
### What changes when migrating
| Standalone (`.claude/`) | Plugin |
| :---------------------------- | :------------------------------- |
| Only available in one project | Can be shared via marketplaces |
| Files in `.claude/commands/` | Files in `plugin-name/commands/` |
| Hooks in `settings.json` | Hooks in `hooks/hooks.json` |
| Must manually copy to share | Install with `/plugin install` |
<Note>
After migrating, you can remove the original files from `.claude/` to avoid duplicates. The plugin version will take precedence when loaded.
</Note>
## Next steps
Now that you understand Claude Code's plugin system, here are suggested paths for different goals:
### For plugin users
* [Discover and install plugins](/en/discover-plugins): browse marketplaces and install plugins
* [Configure team marketplaces](/en/discover-plugins#configure-team-marketplaces): set up repository-level plugins for your team
### For plugin developers
* [Create and distribute a marketplace](/en/plugin-marketplaces): package and share your plugins
* [Plugins reference](/en/plugins-reference): complete technical specifications
* Dive deeper into specific plugin components:
* [Slash commands](/en/slash-commands): command development details
* [Subagents](/en/sub-agents): agent configuration and capabilities
* [Agent Skills](/en/skills): extend Claude's capabilities
* [Hooks](/en/hooks): event handling and automation
* [MCP](/en/mcp): external tool integration
---
> To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt

View file

@ -0,0 +1,200 @@
<!-- Context: ui/web/animation-advanced | Priority: medium | Version: 1.0 | Updated: 2025-12-09 -->
# Advanced Animation Patterns
Recipes, best practices, micro-interactions, and accessibility considerations.
---
## Page Transitions
### Route Changes
```css
/* Page fade out */
.page-exit {
animation: fadeOut 200ms ease-in;
}
@keyframes fadeOut {
from { opacity: 1; }
to { opacity: 0; }
}
/* Page fade in */
.page-enter {
animation: fadeIn 300ms ease-out;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
```
**Micro-syntax**:
```
pageExit: 200ms ease-in [α1→0]
pageEnter: 300ms ease-out [α0→1]
```
---
## Micro-Interactions
### Hover Effects
```css
/* Link underline slide */
.link {
position: relative;
}
.link::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 0;
height: 2px;
background: currentColor;
transition: width 250ms ease-out;
}
.link:hover::after {
width: 100%;
}
```
**Micro-syntax**:
```
linkHover: 250ms ease-out [width0→100%]
```
### Toggle Switches
```css
/* Toggle slide */
.toggle-switch {
transition: background-color 200ms ease-out;
}
.toggle-switch .thumb {
transition: transform 200ms ease-out;
}
.toggle-switch.on .thumb {
transform: translateX(20px);
}
```
**Micro-syntax**:
```
toggle: 200ms ease-out [X0→20, bg→accent]
```
---
## Animation Recipes
### Chat UI Complete Animation System
```
## Core Message Flow
userMsg: 400ms ease-out [Y+20→0, X+10→0, S0.9→1]
aiMsg: 600ms bounce [Y+15→0, S0.95→1] +200ms
typing: 1400ms ∞ [Y±8, α0.4→1] stagger+200ms
status: 300ms ease-out [α0.6→1, S1→1.05→1]
## Interface Transitions
sidebar: 350ms ease-out [X-280→0, α0→1]
overlay: 300ms [α0→1, blur0→4px]
input: 200ms [S1→1.01, shadow+ring] focus
input: 150ms [S1.01→1, shadow-ring] blur
## Button Interactions
sendBtn: 150ms [S1→0.95→1, R±2°] press
sendBtn: 200ms [S1→1.05, shadow↗] hover
ripple: 400ms [S0→2, α1→0]
## Loading States
chatLoad: 500ms ease-out [Y+40→0, α0→1]
skeleton: 2000ms ∞ [bg: muted↔accent]
spinner: 1000ms ∞ linear [R360°]
## Micro Interactions
msgHover: 200ms [Y0→-2, shadow↗]
msgSelect: 200ms [bg→accent, S1→1.02]
error: 400ms [X±5] shake
success: 600ms bounce [S0→1.2→1, R360°]
## Scroll & Navigation
autoScroll: 400ms smooth
scrollHint: 800ms ∞×3 [Y±5]
```
---
## Best Practices
### Do's ✅
- Keep animations under 400ms for most interactions
- Use `transform` and `opacity` for 60fps performance
- Provide purpose for every animation
- Use ease-out for entrances, ease-in for exits
- Test on low-end devices
- Respect `prefers-reduced-motion`
- Stagger animations for lists (50-100ms delay)
- Use consistent timing across similar interactions
### Don'ts ❌
- Don't animate width/height (use scale instead)
- Don't use animations longer than 800ms
- Don't animate too many elements at once
- Don't use animations without purpose
- Don't ignore accessibility preferences
- Don't use jarring/distracting animations
- Don't animate on every interaction
- Don't use complex easing for simple interactions
---
## Accessibility
### Reduced Motion
```css
/* Respect user preferences */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
```
### Focus Indicators
```css
/* Always animate focus states */
:focus-visible {
outline: 2px solid var(--ring);
outline-offset: 2px;
transition: outline-offset 150ms ease-out;
}
```
---
## References
- [Web Animation API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API)
- [CSS Easing Functions](https://easings.net/)
- [Animation Performance](https://web.dev/animations-guide/)
- [Reduced Motion](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion)
---
## Related Files
- [Animation Basics](./animation-basics.md) - Fundamentals
- [UI Animations](./animation-ui.md) - Common UI patterns
- [Loading Animations](./animation-loading.md) - Loading states

View file

@ -0,0 +1,94 @@
<!-- Context: ui/web/animation-basics | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
# Animation Basics
## Overview
Standards and patterns for UI animations, micro-interactions, and transitions. Animations should feel natural, purposeful, and enhance user experience without causing distraction.
## Quick Reference
**Timing**: 150-400ms for most interactions
**Easing**: ease-out for entrances, ease-in for exits
**Purpose**: Every animation should have a clear purpose
**Performance**: Use transform and opacity for 60fps
---
## Animation Micro-Syntax
### Notation Guide
**Format**: `element: duration easing [properties] modifiers`
**Symbols**:
- `→` = transition from → to
- `±` = oscillate/shake
- `↗` = increase
- `↘` = decrease
- `∞` = infinite loop
- `×N` = repeat N times
- `+Nms` = delay N milliseconds
**Properties**:
- `Y` = translateY
- `X` = translateX
- `S` = scale
- `R` = rotate
- `α` = opacity
- `bg` = background
**Example**: `button: 200ms ease-out [S1→1.05, α0.8→1]`
- Button scales from 1 to 1.05 and fades from 0.8 to 1 over 200ms with ease-out
---
## Core Animation Principles
### Timing Standards
```
Ultra-fast: 100-150ms (micro-feedback, hover states)
Fast: 150-250ms (button clicks, toggles)
Standard: 250-350ms (modals, dropdowns, navigation)
Moderate: 350-500ms (page transitions, complex animations)
Slow: 500-800ms (dramatic reveals, storytelling)
```
### Easing Functions
```css
/* Entrances - start slow, end fast */
ease-out: cubic-bezier(0, 0, 0.2, 1);
/* Exits - start fast, end slow */
ease-in: cubic-bezier(0.4, 0, 1, 1);
/* Both - smooth throughout */
ease-in-out: cubic-bezier(0.4, 0, 0.2, 1);
/* Bounce - playful, attention-grabbing */
bounce: cubic-bezier(0.68, -0.55, 0.265, 1.55);
/* Elastic - spring-like */
elastic: cubic-bezier(0.68, -0.6, 0.32, 1.6);
```
### Performance Guidelines
**60fps Animations** (GPU-accelerated):
- ✅ `transform` (translate, scale, rotate)
- ✅ `opacity`
- ✅ `filter` (with caution)
**Avoid** (causes reflow/repaint):
- ❌ `width`, `height`
- ❌ `top`, `left`, `right`, `bottom`
- ❌ `margin`, `padding`
---
## Related Files
- [UI Animations](./animation-ui.md) - Common UI patterns
- [Loading Animations](./animation-loading.md) - Loading states
- [Advanced Animations](./animation-advanced.md) - Recipes & best practices

View file

@ -0,0 +1,113 @@
<!-- Context: ui/web/animation-chat | Priority: medium | Version: 1.0 | Updated: 2025-12-09 -->
# Chat UI Animation Patterns
Animation patterns for message entrances, typing indicators, and chat interactions.
---
## Message Entrance
```css
/* User message - slide from right */
.message-user {
animation: slideInRight 400ms ease-out;
}
@keyframes slideInRight {
from {
transform: translateX(10px) translateY(20px);
opacity: 0;
scale: 0.9;
}
to {
transform: translateX(0) translateY(0);
opacity: 1;
scale: 1;
}
}
/* AI message - slide from left with bounce */
.message-ai {
animation: slideInLeft 600ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
animation-delay: 200ms;
}
@keyframes slideInLeft {
from {
transform: translateY(15px);
opacity: 0;
scale: 0.95;
}
to {
transform: translateY(0);
opacity: 1;
scale: 1;
}
}
```
**Micro-syntax**:
```
userMsg: 400ms ease-out [Y+20→0, X+10→0, S0.9→1]
aiMsg: 600ms bounce [Y+15→0, S0.95→1] +200ms
```
---
## Typing Indicator
```css
.typing-indicator span {
animation: typingDot 1400ms infinite;
}
.typing-indicator span:nth-child(2) { animation-delay: 200ms; }
.typing-indicator span:nth-child(3) { animation-delay: 400ms; }
@keyframes typingDot {
0%, 60%, 100% {
transform: translateY(0);
opacity: 0.4;
}
30% {
transform: translateY(-8px);
opacity: 1;
}
}
```
**Micro-syntax**:
```
typing: 1400ms ∞ [Y±8, α0.4→1] stagger+200ms
```
---
## Chat Message Micro-Interactions
```css
/* Message hover */
.message:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
transition: all 200ms ease-out;
}
/* Message selection */
.message.selected {
background-color: var(--accent);
transform: scale(1.02);
transition: all 200ms ease-out;
}
```
**Micro-syntax**:
```
msgHover: 200ms [Y0→-2, shadow↗]
msgSelect: 200ms [bg→accent, S1→1.02]
```
---
## Related Files
- [Animation Basics](./animation-basics.md) - Fundamentals
- [Component Animations](./animation-components.md) - UI components
- [Loading Animations](./animation-loading.md) - Loading states

View file

@ -0,0 +1,137 @@
<!-- Context: ui/web/animation-components | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
# Component Animation Patterns
Animation patterns for buttons, cards, modals, dropdowns, and sidebars.
---
## Button Interactions
```css
.button {
transition: transform 200ms ease-out, box-shadow 200ms ease-out;
}
.button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.button:active {
transform: scale(0.95);
transition: transform 100ms ease-in;
}
@keyframes ripple {
from { transform: scale(0); opacity: 1; }
to { transform: scale(2); opacity: 0; }
}
.button::after { animation: ripple 400ms ease-out; }
```
**Micro-syntax**:
```
buttonHover: 200ms ease-out [Y0→-2, shadow↗]
buttonPress: 100ms ease-in [S1→0.95]
ripple: 400ms ease-out [S0→2, α1→0]
```
---
## Card Interactions
```css
.card {
transition: transform 300ms ease-out, box-shadow 300ms ease-out;
}
.card:hover {
transform: translateY(-4px);
box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
}
.card.selected {
transform: scale(1.02);
background-color: var(--accent);
transition: all 200ms ease-out;
}
```
**Micro-syntax**:
```
cardHover: 300ms ease-out [Y0→-4, shadow↗]
cardSelect: 200ms ease-out [S1→1.02, bg→accent]
```
---
## Modal/Dialog Animations
```css
.modal-backdrop { animation: fadeIn 300ms ease-out; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
.modal { animation: slideUp 350ms ease-out; }
@keyframes slideUp {
from { transform: translateY(40px); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
.modal.closing { animation: slideDown 250ms ease-in; }
@keyframes slideDown {
from { transform: translateY(0); opacity: 1; }
to { transform: translateY(40px); opacity: 0; }
}
```
**Micro-syntax**:
```
backdrop: 300ms ease-out [α0→1]
modalEnter: 350ms ease-out [Y+40→0, α0→1]
modalExit: 250ms ease-in [Y0→+40, α1→0]
```
---
## Dropdown/Menu Animations
```css
.dropdown {
animation: dropdownOpen 200ms ease-out;
transform-origin: top;
}
@keyframes dropdownOpen {
from { transform: scaleY(0.95); opacity: 0; }
to { transform: scaleY(1); opacity: 1; }
}
```
**Micro-syntax**: `dropdown: 200ms ease-out [scaleY0.95→1, α0→1]`
---
## Sidebar/Drawer Animations
```css
.sidebar { animation: slideInLeft 350ms ease-out; }
@keyframes slideInLeft {
from { transform: translateX(-280px); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
.overlay { animation: overlayFade 300ms ease-out; }
@keyframes overlayFade {
from { opacity: 0; backdrop-filter: blur(0); }
to { opacity: 1; backdrop-filter: blur(4px); }
}
```
**Micro-syntax**:
```
sidebar: 350ms ease-out [X-280→0, α0→1]
overlay: 300ms ease-out [α0→1, blur0→4px]
```
---
## Related Files
- [Animation Basics](./animation-basics.md) - Fundamentals
- [Chat Animations](./animation-chat.md) - Message patterns
- [Loading Animations](./animation-loading.md) - Loading states

View file

@ -0,0 +1,121 @@
<!-- Context: ui/web/animation-forms | Priority: medium | Version: 1.0 | Updated: 2025-12-09 -->
# Form Animation Patterns
Animation patterns for form inputs, validation states, and scroll animations.
---
## Focus States
```css
/* Input focus - ring and scale */
.input {
transition: all 200ms ease-out;
}
.input:focus {
transform: scale(1.01);
box-shadow: 0 0 0 3px var(--ring);
}
/* Input blur - return to normal */
.input:not(:focus) {
transition: all 150ms ease-in;
}
```
**Micro-syntax**:
```
inputFocus: 200ms ease-out [S1→1.01, shadow+ring]
inputBlur: 150ms ease-in [S1.01→1, shadow-ring]
```
---
## Validation States
```css
/* Error shake */
.input-error {
animation: shake 400ms ease-in-out;
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
25% { transform: translateX(-5px); }
75% { transform: translateX(5px); }
}
/* Success checkmark */
.input-success::after {
animation: checkmark 600ms cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
@keyframes checkmark {
from {
transform: scale(0) rotate(0deg);
opacity: 0;
}
to {
transform: scale(1.2) rotate(360deg);
opacity: 1;
}
}
```
**Micro-syntax**:
```
error: 400ms ease-in-out [X±5] shake
success: 600ms bounce [S0→1.2, R0→360°, α0→1]
```
---
## Scroll Animations
### Scroll-Triggered Fade In
```css
.fade-in-on-scroll {
opacity: 0;
transform: translateY(40px);
transition: opacity 500ms ease-out, transform 500ms ease-out;
}
.fade-in-on-scroll.visible {
opacity: 1;
transform: translateY(0);
}
```
**Micro-syntax**:
```
scrollFadeIn: 500ms ease-out [Y+40→0, α0→1]
```
### Auto-Scroll
```css
html {
scroll-behavior: smooth;
}
.scroll-hint {
animation: scrollHint 800ms infinite;
animation-iteration-count: 3;
}
@keyframes scrollHint {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(5px); }
}
```
**Micro-syntax**:
```
autoScroll: 400ms smooth
scrollHint: 800ms ∞×3 [Y±5]
```
---
## Related Files
- [Animation Basics](./animation-basics.md) - Fundamentals
- [UI Animations](./animation-ui.md) - Common UI patterns
- [Loading Animations](./animation-loading.md) - Loading states

View file

@ -0,0 +1,118 @@
<!-- Context: ui/web/animation-loading | Priority: medium | Version: 1.0 | Updated: 2025-12-09 -->
# Loading State Animations
Animation patterns for skeleton screens, spinners, progress bars, and status indicators.
---
## Skeleton Screens
```css
/* Skeleton shimmer */
.skeleton {
animation: shimmer 2000ms infinite;
background: linear-gradient(
90deg,
var(--muted) 0%,
var(--accent) 50%,
var(--muted) 100%
);
background-size: 200% 100%;
}
@keyframes shimmer {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
}
```
**Micro-syntax**:
```
skeleton: 2000ms ∞ [bg: muted↔accent]
```
---
## Spinners
```css
/* Circular spinner */
.spinner {
animation: spin 1000ms linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
/* Pulsing dots */
.loading-dots span {
animation: dotPulse 1500ms infinite;
}
.loading-dots span:nth-child(2) { animation-delay: 200ms; }
.loading-dots span:nth-child(3) { animation-delay: 400ms; }
@keyframes dotPulse {
0%, 80%, 100% { opacity: 0.3; scale: 0.8; }
40% { opacity: 1; scale: 1; }
}
```
**Micro-syntax**:
```
spinner: 1000ms ∞ linear [R360°]
dotPulse: 1500ms ∞ [α0.3→1→0.3, S0.8→1→0.8] stagger+200ms
```
---
## Progress Bars
```css
/* Indeterminate progress */
.progress-bar {
animation: progress 2000ms ease-in-out infinite;
}
@keyframes progress {
0% { transform: translateX(-100%); }
50% { transform: translateX(0); }
100% { transform: translateX(100%); }
}
```
**Micro-syntax**:
```
progress: 2000ms ∞ ease-in-out [X-100%→0→100%]
```
---
## Status Indicators
```css
/* Online status pulse */
.status-online {
animation: pulse 2000ms infinite;
}
@keyframes pulse {
0%, 100% {
opacity: 1;
scale: 1;
}
50% {
opacity: 0.6;
scale: 1.05;
}
}
```
**Micro-syntax**:
```
status: 2000ms ∞ [α1→0.6→1, S1→1.05→1]
```
---
## Related Files
- [Animation Basics](./animation-basics.md) - Fundamentals
- [Form Animations](./animation-forms.md) - Form patterns
- [Advanced Animations](./animation-advanced.md) - Recipes & best practices

View file

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

View file

@ -0,0 +1,149 @@
<!-- Context: ui/web/cdn | Priority: medium | Version: 1.0 | Updated: 2026-02-05 -->
# CDN Resources
**Purpose**: Common CDN libraries for frontend development
---
## CSS Frameworks
### Tailwind CSS
```html
<script src="https://cdn.tailwindcss.com"></script>
```
### Flowbite
```html
<link href="https://cdn.jsdelivr.net/npm/flowbite@2.0.0/dist/flowbite.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/flowbite@2.0.0/dist/flowbite.min.js"></script>
```
### Bootstrap
```html
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
```
---
## JavaScript Libraries
### Alpine.js
```html
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
```
### HTMX
```html
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
```
### Chart.js
```html
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
```
---
## Animation Libraries
### Animate.css
```html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
```
### AOS (Animate On Scroll)
```html
<link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
<script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
```
---
## Video Placeholders
```html
<!-- Sample video -->
<video class="w-full rounded-lg" controls>
<source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
</video>
<!-- Background video -->
<video class="w-full h-screen object-cover" autoplay muted loop playsinline>
<source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4" type="video/mp4">
</video>
```
---
## Best Practices
### Version Pinning
```html
<!-- Good: Specific version -->
<script src="https://unpkg.com/lucide@0.294.0/dist/umd/lucide.min.js"></script>
<!-- Risky: Latest version -->
<script src="https://unpkg.com/lucide@latest/dist/umd/lucide.min.js"></script>
```
### Integrity Hashes
```html
<script
src="https://cdn.jsdelivr.net/npm/alpinejs@3.13.3/dist/cdn.min.js"
integrity="sha384-..."
crossorigin="anonymous"
></script>
```
---
## File Naming Conventions
**Design Files:**
- Initial: `{name}_1.html` (e.g., `table_1.html`)
- Iterations: `{name}_1_1.html`, `{name}_1_2.html`
- Themes: `theme_1.css`, `theme_2.css`
**Asset Files:**
- Images: `hero-image.jpg`, `product-1.png`
- Icons: `logo.svg`, `icon-menu.svg`
- Fonts: `inter-var.woff2`
---
## Project Structure
```
design_iterations/
├── theme_1.css
├── ui_1.html
├── ui_1_1.html (iteration)
├── dashboard_1.html
└── assets/
├── images/
├── icons/
└── fonts/
```
---
## Accessibility Checklist
**Images:**
- [ ] All images have alt text
- [ ] Decorative images have `alt=""` and `role="presentation"`
- [ ] Complex images have figcaption
**Icons:**
- [ ] Icon-only buttons have `aria-label`
- [ ] Decorative icons have `aria-hidden="true"`
- [ ] Icons with text are hidden from screen readers
---
## Related
- `images-guide.md` - Image guidelines
- `icons-guide.md` - Icon systems
- `fonts-guide.md` - Font loading

View file

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

View file

@ -0,0 +1,145 @@
# Premium Dark UI - Advanced
Animations, accessibility, and checklists for premium dark UI.
---
## Animations
### Hover Effects
```tsx
// Card hover
<div className="transition-all duration-300 hover:scale-[1.02]">
Card content
</div>
// Button hover
<button className="transition-colors duration-200 hover:bg-[#6bb890]">
Button
</button>
// Image hover
<img className="transition-transform duration-700 hover:scale-105" />
```
### Scroll Reveal
```tsx
// npm install react-intersection-observer
import { useInView } from 'react-intersection-observer'
function Component() {
const { ref, inView } = useInView({ triggerOnce: true, threshold: 0.1 })
return (
<div
ref={ref}
className={`transition-all duration-700 ${
inView ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'
}`}
>
Content
</div>
)
}
```
---
## Accessibility
### Color Contrast
- White on `#0a0f0d`: 21:1 (AAA) ✅
- `slate-300` on `#0a0f0d`: 12.6:1 (AAA) ✅
- `#80cca5` on `#0a0f0d`: 7.8:1 (AAA) ✅
### Focus States
```tsx
<button className="focus:ring-2 focus:ring-[#80cca5] focus:outline-none">
Button
</button>
```
### Semantic HTML
```tsx
<nav>
<ul>
<li><a href="#">Link</a></li>
</ul>
</nav>
```
---
## Quick Wins (Instant Premium Feel)
1. Replace all backgrounds with `#0a0f0d`
2. Use only white and slate-300 for text
3. Make all CTAs `#80cca5` green
4. Add backdrop-blur-xl to all cards
5. Use rounded-2xl for cards, rounded-full for buttons
6. Add one radial glow to hero section
7. Increase padding (py-24 for sections, p-8 for cards)
8. Add hover effects to all interactive elements
---
## Common Mistakes
❌ **DON'T**:
- Use light backgrounds (`bg-white`, `bg-slate-100`)
- Use `dark:` variants (this is dark-only)
- Mix multiple accent colors
- Use high-opacity glass (`bg-white/50`)
- Skip backdrop blur on glass elements
- Use small padding (looks cramped)
- Forget hover states
- Ignore mobile layout
✅ **DO**:
- Stick to the color palette
- Use consistent spacing (multiples of 4)
- Add subtle animations
- Test on mobile first
- Keep glass opacity low
- Use radial glows sparingly
- Maintain high contrast for text
---
## Final Checklist
Before launching, verify:
- [ ] All backgrounds are `#0a0f0d` or `black`
- [ ] All headings are `text-white`
- [ ] All body text is `text-slate-300`
- [ ] All CTAs are `#80cca5` green
- [ ] All cards have `backdrop-blur-xl`
- [ ] All cards use `bg-white/[0.02]`
- [ ] All buttons have hover states
- [ ] All forms have focus states
- [ ] Spacing uses multiples of 4
- [ ] Mobile layout tested
- [ ] Radial glows are subtle (not overwhelming)
- [ ] No light mode variants (`dark:`)
- [ ] Contrast ratios meet WCAG AA minimum
---
**Time to premium**: 30-60 minutes
**Maintenance**: Easy (4 components, 1 color palette)
**Scalability**: High (reusable components)
---
## Related Files
- [Colors & Typography](./premium-dark-ui-colors.md)
- [Components](./premium-dark-ui-components.md)
- [Layouts](./premium-dark-ui-layouts.md)
- [Full System Guide](./premium-dark-ui-system.md)

View file

@ -0,0 +1,164 @@
# Premium Dark UI - Colors & Typography
Quick reference for colors, spacing, and typography in premium dark UI.
---
## Color Palette
```css
/* Backgrounds */
--bg-deep-dark: #0a0f0d; /* Main background */
--bg-black: #000000; /* Alternate sections */
/* Text */
--text-heading: #ffffff; /* Headings */
--text-body: #cbd5e1; /* Body (slate-300) */
--text-muted: #94a3b8; /* Muted (slate-400) */
/* Accent */
--accent: #80cca5; /* Green - CTAs, links, highlights */
--accent-hover: #6bb890; /* Hover state */
/* Glass */
--glass-bg: rgba(255, 255, 255, 0.02);
--glass-border: rgba(255, 255, 255, 0.1);
```
**Rule**: Use ONLY these colors. No exceptions.
---
## Spacing System
```css
/* Use these values ONLY */
py-4 /* 16px - Small spacing */
py-8 /* 32px - Medium spacing */
py-12 /* 48px - Large spacing */
py-24 /* 96px - Section spacing */
px-4 /* 16px - Mobile padding */
px-8 /* 32px - Card padding */
px-12 /* 48px - Large card padding */
gap-4 /* 16px - Small gaps */
gap-8 /* 32px - Medium gaps */
gap-12 /* 48px - Large gaps */
mb-4 /* 16px - Small margin bottom */
mb-6 /* 24px - Medium margin bottom */
mb-8 /* 32px - Large margin bottom */
mb-16 /* 64px - Section margin bottom */
```
**Rule**: Stick to multiples of 4 (4, 8, 12, 16, 24, 32, 48, 64, 96).
---
## Typography Scale
```tsx
// Page Title (H1)
<h1 className="text-4xl md:text-6xl font-bold text-white mb-8">
Page Title
</h1>
// Section Title (H2)
<h2 className="text-3xl md:text-5xl font-bold text-white mb-6">
Section Title <span className="text-[#80cca5]">Accent</span>
</h2>
// Subsection (H3)
<h3 className="text-2xl md:text-4xl font-bold text-white mb-4">
Subsection
</h3>
// Body Text
<p className="text-lg text-slate-300 mb-4">
Body text goes here
</p>
// Muted Text
<p className="text-sm text-slate-400">
Secondary information
</p>
// Accent Text
<p className="text-lg font-semibold text-[#80cca5]">
Call to action text
</p>
```
---
## Buttons & Links
```tsx
// Primary CTA Button
<button className="
px-8 py-4
rounded-full
bg-[#80cca5]
hover:bg-[#6bb890]
text-white
font-semibold
transition-all
shadow-lg
hover:shadow-xl
">
Primary Action
</button>
// Secondary Button
<button className="
px-6 py-3
rounded-full
bg-white/[0.02]
border border-white/10
hover:border-[#80cca5]/30
text-white
font-medium
transition-all
">
Secondary Action
</button>
// Link
<a href="#" className="text-[#80cca5] hover:text-[#6bb890] transition-colors">
Link Text
</a>
```
---
## Form Inputs
```tsx
// Text Input
<input
type="text"
className="
w-full px-4 py-3 rounded-lg
border border-[#80cca5]/20
bg-slate-900/50
text-white
placeholder:text-slate-500
focus:ring-2 focus:ring-[#80cca5] focus:border-transparent
"
placeholder="Enter text"
/>
// Label
<label className="text-slate-200 font-medium mb-2 block">
Field Label
</label>
```
---
## Related Files
- [Components](./premium-dark-ui-components.md)
- [Layouts](./premium-dark-ui-layouts.md)
- [Advanced](./premium-dark-ui-advanced.md)

View file

@ -0,0 +1,142 @@
# Premium Dark UI - Core Components
The 4 building blocks for premium dark UI.
---
## A. Section Wrapper
```tsx
// PremiumSection.tsx
export function PremiumSection({ children, withGlow = true }) {
return (
<section className="relative py-24 px-4 bg-[#0a0f0d] overflow-hidden">
{withGlow && (
<div
className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] pointer-events-none"
style={{
background: 'radial-gradient(circle, rgba(128, 204, 165, 0.15) 0%, transparent 70%)',
opacity: 0.15
}}
/>
)}
<div className="max-w-7xl mx-auto relative z-10">
{children}
</div>
</section>
)
}
```
---
## B. Glass Card
```tsx
// PremiumCard.tsx
export function PremiumCard({ children, className = "" }) {
return (
<div className={`
p-8 rounded-2xl
bg-white/[0.02]
border border-white/10
backdrop-blur-xl
shadow-2xl
transition-all duration-300
hover:bg-white/[0.04]
hover:border-[#80cca5]/30
${className}
`}>
{children}
</div>
)
}
```
---
## C. Heading
```tsx
// PremiumHeading.tsx
export function PremiumHeading({ children, accent, as: Tag = 'h2' }) {
return (
<Tag className="text-3xl md:text-5xl font-bold text-white mb-6">
{children}
{accent && <span className="text-[#80cca5]"> {accent}</span>}
</Tag>
)
}
```
---
## D. Radial Glow
```tsx
// RadialGlow.tsx
export function RadialGlow({ className = "" }) {
return (
<div
className={`absolute -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] pointer-events-none ${className}`}
style={{
background: 'radial-gradient(circle, rgba(128, 204, 165, 0.15) 0%, transparent 70%)',
opacity: 0.15
}}
/>
)
}
```
---
## Glassmorphism Rules
✅ **DO**:
- Use `bg-white/[0.02]` for card backgrounds
- Add `backdrop-blur-xl` for blur effect
- Use `border-white/10` for subtle borders
- Keep opacity LOW (0.02 to 0.04)
- Layer multiple glass surfaces
❌ **DON'T**:
- Use high opacity (breaks glass effect)
- Skip backdrop blur (looks flat)
- Use on light backgrounds (invisible)
- Overuse (reserve for cards/panels)
---
## Radial Glow Usage
### When to Use:
- ✅ Hero sections (large, centered)
- ✅ Important CTAs (behind forms)
- ✅ Section breaks (corner glows)
- ❌ Every section (overwhelming)
- ❌ Small components (too subtle)
### Sizes:
- **Small**: 400px (subtle accent)
- **Medium**: 600px (default)
- **Large**: 800px (hero sections)
### Positioning:
```tsx
// Centered
<RadialGlow className="top-1/2 left-1/2" />
// Top-left
<RadialGlow className="top-0 left-0" />
// Bottom-right
<RadialGlow className="bottom-0 right-0" />
```
---
## Related Files
- [Colors & Typography](./premium-dark-ui-colors.md)
- [Layouts](./premium-dark-ui-layouts.md)
- [Advanced](./premium-dark-ui-advanced.md)

View file

@ -0,0 +1,173 @@
# Premium Dark UI - Layouts
Common layout patterns for premium dark UI.
---
## Hero Section
```tsx
<PremiumSection>
<div className="max-w-4xl mx-auto text-center">
<PremiumHeading as="h1" accent="AI">
Build Production
</PremiumHeading>
<p className="text-xl text-slate-300 mb-8">
Your subtitle goes here
</p>
<button className="px-8 py-4 rounded-full bg-[#80cca5] hover:bg-[#6bb890] text-white font-semibold transition-all shadow-lg">
Get Started
</button>
</div>
</PremiumSection>
```
---
## Feature Grid
```tsx
<PremiumSection>
<div className="text-center mb-16">
<PremiumHeading accent="Features">
Powerful
</PremiumHeading>
</div>
<div className="grid md:grid-cols-3 gap-8">
{features.map((feature) => (
<PremiumCard key={feature.id}>
<Icon className="size-12 text-[#80cca5] mb-4" />
<h3 className="text-xl font-bold text-white mb-2">
{feature.title}
</h3>
<p className="text-slate-300">
{feature.description}
</p>
</PremiumCard>
))}
</div>
</PremiumSection>
```
---
## CTA Section
```tsx
<PremiumSection>
<div className="max-w-3xl mx-auto">
<div className="text-center mb-12">
<PremiumHeading accent="Started">
Get
</PremiumHeading>
<p className="text-xl text-slate-300">
Join thousands of users
</p>
</div>
<PremiumCard className="p-8 md:p-12">
<form className="space-y-6">
<input
type="email"
placeholder="you@example.com"
className="w-full px-4 py-3 rounded-lg border border-[#80cca5]/20 bg-slate-900/50 text-white placeholder:text-slate-500 focus:ring-2 focus:ring-[#80cca5] focus:border-transparent"
/>
<button className="w-full px-8 py-4 rounded-full bg-[#80cca5] hover:bg-[#6bb890] text-white font-semibold transition-all">
Sign Up
</button>
</form>
</PremiumCard>
</div>
</PremiumSection>
```
---
## Responsive Design
```tsx
// Mobile: Stack, Desktop: Grid
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
{/* Items */}
</div>
// Mobile: Full width, Desktop: Constrained
<div className="w-full lg:max-w-4xl mx-auto">
{/* Content */}
</div>
// Mobile: Small text, Desktop: Large text
<h2 className="text-3xl md:text-5xl">
Responsive Heading
</h2>
// Mobile: Center, Desktop: Left
<div className="text-center lg:text-left">
{/* Content */}
</div>
```
**Breakpoints**:
- `sm`: 640px (tablets)
- `md`: 768px (tablets/small laptops)
- `lg`: 1024px (laptops)
- `xl`: 1280px (desktops)
---
## Starter Template
```tsx
export default function Page() {
return (
<div className="min-h-screen bg-[#0a0f0d]">
{/* Hero */}
<PremiumSection>
<div className="max-w-4xl mx-auto text-center">
<PremiumHeading as="h1" accent="Premium">
Your
</PremiumHeading>
<p className="text-xl text-slate-300 mb-8">Subtitle here</p>
<button className="px-8 py-4 rounded-full bg-[#80cca5] hover:bg-[#6bb890] text-white font-semibold">
Get Started
</button>
</div>
</PremiumSection>
{/* Features */}
<PremiumSection>
<div className="text-center mb-16">
<PremiumHeading accent="Features">Amazing</PremiumHeading>
</div>
<div className="grid md:grid-cols-3 gap-8">
<PremiumCard>
<h3 className="text-xl font-bold text-white mb-2">Feature 1</h3>
<p className="text-slate-300">Description</p>
</PremiumCard>
{/* More cards */}
</div>
</PremiumSection>
{/* CTA */}
<PremiumSection>
<div className="max-w-3xl mx-auto text-center">
<PremiumHeading accent="Started">Get</PremiumHeading>
<PremiumCard className="p-8 md:p-12">
<form className="space-y-6">
<input type="email" placeholder="you@example.com" className="w-full px-4 py-3 rounded-lg border border-[#80cca5]/20 bg-slate-900/50 text-white" />
<button className="w-full px-8 py-4 rounded-full bg-[#80cca5] text-white font-semibold">Sign Up</button>
</form>
</PremiumCard>
</div>
</PremiumSection>
</div>
)
}
```
---
## Related Files
- [Colors & Typography](./premium-dark-ui-colors.md)
- [Components](./premium-dark-ui-components.md)
- [Advanced](./premium-dark-ui-advanced.md)

View file

@ -1,638 +0,0 @@
# Premium Dark UI - Quick Start Guide
**Goal**: Create a sophisticated, modern dark website with glassmorphism and depth.
**Time to implement**: 30-60 minutes
---
## 1. COLOR PALETTE (Copy This)
```css
/* Backgrounds */
--bg-deep-dark: #0a0f0d; /* Main background */
--bg-black: #000000; /* Alternate sections */
/* Text */
--text-heading: #ffffff; /* Headings */
--text-body: #cbd5e1; /* Body (slate-300) */
--text-muted: #94a3b8; /* Muted (slate-400) */
/* Accent */
--accent: #80cca5; /* Green - CTAs, links, highlights */
--accent-hover: #6bb890; /* Hover state */
/* Glass */
--glass-bg: rgba(255, 255, 255, 0.02);
--glass-border: rgba(255, 255, 255, 0.1);
```
**Rule**: Use ONLY these colors. No exceptions.
---
## 2. CORE COMPONENTS (4 Building Blocks)
### A. Section Wrapper
```tsx
// PremiumSection.tsx
export function PremiumSection({ children, withGlow = true }) {
return (
<section className="relative py-24 px-4 bg-[#0a0f0d] overflow-hidden">
{withGlow && (
<div
className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] pointer-events-none"
style={{
background: 'radial-gradient(circle, rgba(128, 204, 165, 0.15) 0%, transparent 70%)',
opacity: 0.15
}}
/>
)}
<div className="max-w-7xl mx-auto relative z-10">
{children}
</div>
</section>
)
}
```
### B. Glass Card
```tsx
// PremiumCard.tsx
export function PremiumCard({ children, className = "" }) {
return (
<div className={`
p-8 rounded-2xl
bg-white/[0.02]
border border-white/10
backdrop-blur-xl
shadow-2xl
transition-all duration-300
hover:bg-white/[0.04]
hover:border-[#80cca5]/30
${className}
`}>
{children}
</div>
)
}
```
### C. Heading
```tsx
// PremiumHeading.tsx
export function PremiumHeading({ children, accent, as: Tag = 'h2' }) {
return (
<Tag className="text-3xl md:text-5xl font-bold text-white mb-6">
{children}
{accent && <span className="text-[#80cca5]"> {accent}</span>}
</Tag>
)
}
```
### D. Radial Glow
```tsx
// RadialGlow.tsx
export function RadialGlow({ className = "" }) {
return (
<div
className={`absolute -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] pointer-events-none ${className}`}
style={{
background: 'radial-gradient(circle, rgba(128, 204, 165, 0.15) 0%, transparent 70%)',
opacity: 0.15
}}
/>
)
}
```
---
## 3. SPACING SYSTEM
```css
/* Use these values ONLY */
py-4 /* 16px - Small spacing */
py-8 /* 32px - Medium spacing */
py-12 /* 48px - Large spacing */
py-24 /* 96px - Section spacing */
px-4 /* 16px - Mobile padding */
px-8 /* 32px - Card padding */
px-12 /* 48px - Large card padding */
gap-4 /* 16px - Small gaps */
gap-8 /* 32px - Medium gaps */
gap-12 /* 48px - Large gaps */
mb-4 /* 16px - Small margin bottom */
mb-6 /* 24px - Medium margin bottom */
mb-8 /* 32px - Large margin bottom */
mb-16 /* 64px - Section margin bottom */
```
**Rule**: Stick to multiples of 4 (4, 8, 12, 16, 24, 32, 48, 64, 96).
---
## 4. TYPOGRAPHY SCALE
```tsx
// Page Title (H1)
<h1 className="text-4xl md:text-6xl font-bold text-white mb-8">
Page Title
</h1>
// Section Title (H2)
<h2 className="text-3xl md:text-5xl font-bold text-white mb-6">
Section Title <span className="text-[#80cca5]">Accent</span>
</h2>
// Subsection (H3)
<h3 className="text-2xl md:text-4xl font-bold text-white mb-4">
Subsection
</h3>
// Body Text
<p className="text-lg text-slate-300 mb-4">
Body text goes here
</p>
// Muted Text
<p className="text-sm text-slate-400">
Secondary information
</p>
// Accent Text
<p className="text-lg font-semibold text-[#80cca5]">
Call to action text
</p>
```
---
## 5. BUTTONS & LINKS
```tsx
// Primary CTA Button
<button className="
px-8 py-4
rounded-full
bg-[#80cca5]
hover:bg-[#6bb890]
text-white
font-semibold
transition-all
shadow-lg
hover:shadow-xl
">
Primary Action
</button>
// Secondary Button
<button className="
px-6 py-3
rounded-full
bg-white/[0.02]
border border-white/10
hover:border-[#80cca5]/30
text-white
font-medium
transition-all
">
Secondary Action
</button>
// Link
<a href="#" className="text-[#80cca5] hover:text-[#6bb890] transition-colors">
Link Text
</a>
```
---
## 6. FORM INPUTS
```tsx
// Text Input
<input
type="text"
className="
w-full
px-4 py-3
rounded-lg
border border-[#80cca5]/20
bg-slate-900/50
text-white
placeholder:text-slate-500
focus:ring-2
focus:ring-[#80cca5]
focus:border-transparent
"
placeholder="Enter text"
/>
// Textarea
<textarea
className="
w-full
px-4 py-3
rounded-lg
border border-[#80cca5]/20
bg-slate-900/50
text-white
placeholder:text-slate-500
focus:ring-2
focus:ring-[#80cca5]
focus:border-transparent
resize-none
"
rows={4}
/>
// Label
<label className="text-slate-200 font-medium mb-2 block">
Field Label
</label>
```
---
## 7. COMMON LAYOUTS
### Hero Section
```tsx
<PremiumSection>
<div className="max-w-4xl mx-auto text-center">
<PremiumHeading as="h1" accent="AI">
Build Production
</PremiumHeading>
<p className="text-xl text-slate-300 mb-8">
Your subtitle goes here
</p>
<button className="px-8 py-4 rounded-full bg-[#80cca5] hover:bg-[#6bb890] text-white font-semibold transition-all shadow-lg">
Get Started
</button>
</div>
</PremiumSection>
```
### Feature Grid
```tsx
<PremiumSection>
<div className="text-center mb-16">
<PremiumHeading accent="Features">
Powerful
</PremiumHeading>
</div>
<div className="grid md:grid-cols-3 gap-8">
{features.map((feature) => (
<PremiumCard key={feature.id}>
<Icon className="size-12 text-[#80cca5] mb-4" />
<h3 className="text-xl font-bold text-white mb-2">
{feature.title}
</h3>
<p className="text-slate-300">
{feature.description}
</p>
</PremiumCard>
))}
</div>
</PremiumSection>
```
### CTA Section
```tsx
<PremiumSection>
<div className="max-w-3xl mx-auto">
<div className="text-center mb-12">
<PremiumHeading accent="Started">
Get
</PremiumHeading>
<p className="text-xl text-slate-300">
Join thousands of users
</p>
</div>
<PremiumCard className="p-8 md:p-12">
<form className="space-y-6">
<input
type="email"
placeholder="you@example.com"
className="w-full px-4 py-3 rounded-lg border border-[#80cca5]/20 bg-slate-900/50 text-white placeholder:text-slate-500 focus:ring-2 focus:ring-[#80cca5] focus:border-transparent"
/>
<button className="w-full px-8 py-4 rounded-full bg-[#80cca5] hover:bg-[#6bb890] text-white font-semibold transition-all">
Sign Up
</button>
</form>
</PremiumCard>
</div>
</PremiumSection>
```
---
## 8. GLASSMORPHISM RULES
✅ **DO**:
- Use `bg-white/[0.02]` for card backgrounds
- Add `backdrop-blur-xl` for blur effect
- Use `border-white/10` for subtle borders
- Keep opacity LOW (0.02 to 0.04)
- Layer multiple glass surfaces
❌ **DON'T**:
- Use high opacity (breaks glass effect)
- Skip backdrop blur (looks flat)
- Use on light backgrounds (invisible)
- Overuse (reserve for cards/panels)
**Example**:
```tsx
<div className="bg-white/[0.02] border border-white/10 backdrop-blur-xl">
Glass content
</div>
```
---
## 9. RADIAL GLOW USAGE
### When to Use:
- ✅ Hero sections (large, centered)
- ✅ Important CTAs (behind forms)
- ✅ Section breaks (corner glows)
- ❌ Every section (overwhelming)
- ❌ Small components (too subtle)
### Sizes:
- **Small**: 400px (subtle accent)
- **Medium**: 600px (default)
- **Large**: 800px (hero sections)
### Positioning:
```tsx
// Centered
<RadialGlow className="top-1/2 left-1/2" />
// Top-left
<RadialGlow className="top-0 left-0" />
// Bottom-right
<RadialGlow className="bottom-0 right-0" />
```
---
## 10. RESPONSIVE DESIGN
```tsx
// Mobile: Stack, Desktop: Grid
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
{/* Items */}
</div>
// Mobile: Full width, Desktop: Constrained
<div className="w-full lg:max-w-4xl mx-auto">
{/* Content */}
</div>
// Mobile: Small text, Desktop: Large text
<h2 className="text-3xl md:text-5xl">
Responsive Heading
</h2>
// Mobile: Center, Desktop: Left
<div className="text-center lg:text-left">
{/* Content */}
</div>
```
**Breakpoints**:
- `sm`: 640px (tablets)
- `md`: 768px (tablets/small laptops)
- `lg`: 1024px (laptops)
- `xl`: 1280px (desktops)
---
## 11. ANIMATIONS
### Hover Effects
```tsx
// Card hover
<div className="transition-all duration-300 hover:scale-[1.02]">
Card content
</div>
// Button hover
<button className="transition-colors duration-200 hover:bg-[#6bb890]">
Button
</button>
// Image hover
<img className="transition-transform duration-700 hover:scale-105" />
```
### Scroll Reveal (Optional)
```tsx
// Install: npm install react-intersection-observer
import { useInView } from 'react-intersection-observer'
function Component() {
const { ref, inView } = useInView({ triggerOnce: true, threshold: 0.1 })
return (
<div
ref={ref}
className={`transition-all duration-700 ${
inView ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'
}`}
>
Content
</div>
)
}
```
---
## 12. ACCESSIBILITY CHECKLIST
✅ **Color Contrast**:
- White on `#0a0f0d`: 21:1 (AAA) ✅
- `slate-300` on `#0a0f0d`: 12.6:1 (AAA) ✅
- `#80cca5` on `#0a0f0d`: 7.8:1 (AAA) ✅
✅ **Focus States**:
```tsx
<button className="focus:ring-2 focus:ring-[#80cca5] focus:outline-none">
Button
</button>
```
✅ **Semantic HTML**:
```tsx
<nav>
<ul>
<li><a href="#">Link</a></li>
</ul>
</nav>
```
✅ **Alt Text**:
```tsx
<img src="..." alt="Descriptive text" />
```
---
## 13. QUICK WINS (Instant Premium Feel)
1. **Replace all backgrounds** with `#0a0f0d`
2. **Use only white and slate-300** for text
3. **Make all CTAs** `#80cca5` green
4. **Add backdrop-blur-xl** to all cards
5. **Use rounded-2xl** for cards, `rounded-full` for buttons
6. **Add one radial glow** to hero section
7. **Increase padding** (py-24 for sections, p-8 for cards)
8. **Add hover effects** to all interactive elements
---
## 14. COMMON MISTAKES TO AVOID
❌ **Don't**:
- Use light backgrounds (`bg-white`, `bg-slate-100`)
- Use `dark:` variants (this is dark-only)
- Mix multiple accent colors
- Use high-opacity glass (`bg-white/50`)
- Skip backdrop blur on glass elements
- Use small padding (looks cramped)
- Forget hover states
- Ignore mobile layout
✅ **Do**:
- Stick to the color palette
- Use consistent spacing (multiples of 4)
- Add subtle animations
- Test on mobile first
- Keep glass opacity low
- Use radial glows sparingly
- Maintain high contrast for text
---
## 15. COPY-PASTE STARTER TEMPLATE
```tsx
import React from 'react'
// 1. Copy the 4 core components (Section A-D above)
// 2. Use this page structure:
export default function Page() {
return (
<div className="min-h-screen bg-[#0a0f0d]">
{/* Hero */}
<PremiumSection>
<div className="max-w-4xl mx-auto text-center">
<PremiumHeading as="h1" accent="Premium">
Your
</PremiumHeading>
<p className="text-xl text-slate-300 mb-8">
Subtitle goes here
</p>
<button className="px-8 py-4 rounded-full bg-[#80cca5] hover:bg-[#6bb890] text-white font-semibold transition-all shadow-lg">
Get Started
</button>
</div>
</PremiumSection>
{/* Features */}
<PremiumSection>
<div className="text-center mb-16">
<PremiumHeading accent="Features">
Amazing
</PremiumHeading>
</div>
<div className="grid md:grid-cols-3 gap-8">
<PremiumCard>
<h3 className="text-xl font-bold text-white mb-2">Feature 1</h3>
<p className="text-slate-300">Description</p>
</PremiumCard>
<PremiumCard>
<h3 className="text-xl font-bold text-white mb-2">Feature 2</h3>
<p className="text-slate-300">Description</p>
</PremiumCard>
<PremiumCard>
<h3 className="text-xl font-bold text-white mb-2">Feature 3</h3>
<p className="text-slate-300">Description</p>
</PremiumCard>
</div>
</PremiumSection>
{/* CTA */}
<PremiumSection>
<div className="max-w-3xl mx-auto text-center">
<PremiumHeading accent="Started">
Get
</PremiumHeading>
<PremiumCard className="p-8 md:p-12">
<form className="space-y-6">
<input
type="email"
placeholder="you@example.com"
className="w-full px-4 py-3 rounded-lg border border-[#80cca5]/20 bg-slate-900/50 text-white placeholder:text-slate-500 focus:ring-2 focus:ring-[#80cca5] focus:border-transparent"
/>
<button className="w-full px-8 py-4 rounded-full bg-[#80cca5] hover:bg-[#6bb890] text-white font-semibold transition-all">
Sign Up
</button>
</form>
</PremiumCard>
</div>
</PremiumSection>
</div>
)
}
```
---
## 16. FINAL CHECKLIST
Before launching, verify:
- [ ] All backgrounds are `#0a0f0d` or `black`
- [ ] All headings are `text-white`
- [ ] All body text is `text-slate-300`
- [ ] All CTAs are `#80cca5` green
- [ ] All cards have `backdrop-blur-xl`
- [ ] All cards use `bg-white/[0.02]`
- [ ] All buttons have hover states
- [ ] All forms have focus states
- [ ] Spacing uses multiples of 4
- [ ] Mobile layout tested
- [ ] Radial glows are subtle (not overwhelming)
- [ ] No light mode variants (`dark:`)
- [ ] Contrast ratios meet WCAG AA minimum
---
## DONE! 🎉
You now have everything needed to create a premium dark UI.
**Time to premium**: 30-60 minutes
**Maintenance**: Easy (4 components, 1 color palette)
**Scalability**: High (reusable components)
**Questions?** Reference the full guide: `.opencode/context/ui/web/design/guides/premium-dark-ui-system.md`

View file

@ -0,0 +1,118 @@
<!-- Context: ui/web/fonts | Priority: medium | Version: 1.0 | Updated: 2026-02-05 -->
# Font Loading
**Purpose**: Guidelines for loading and using web fonts
---
## Quick Reference
**Recommended**: Google Fonts with preconnect
```html
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
```
---
## Google Fonts (Recommended)
### Basic Loading
```html
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
```
### Multiple Fonts
```html
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
```
### CSS Usage
```css
body {
font-family: 'Inter', sans-serif;
}
code, pre {
font-family: 'JetBrains Mono', monospace;
}
```
---
## Popular Font Combinations
### Modern UI
```html
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
```
### Professional
```html
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&family=Roboto+Mono:wght@400;500&display=swap" rel="stylesheet">
```
### Editorial
```html
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;700&family=Source+Sans+Pro:wght@400;600&display=swap" rel="stylesheet">
```
### Friendly
```html
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&family=Space+Mono:wght@400;700&display=swap" rel="stylesheet">
```
---
## Performance Optimization
### Subset Fonts
```html
<!-- Only load needed characters -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&text=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789&display=swap" rel="stylesheet">
```
### Preload Critical Fonts
```html
<link rel="preload" href="/fonts/inter-var.woff2" as="font" type="font/woff2" crossorigin>
```
### Self-Hosted Fonts
```html
<style>
@font-face {
font-family: 'Inter';
src: url('/fonts/inter-var.woff2') format('woff2');
font-weight: 100 900;
font-display: swap;
}
</style>
```
---
## Best Practices
**Do ✅:**
- Use `font-display: swap` (included in Google Fonts URL)
- Preconnect to font servers
- Limit to 2-3 font families
- Subset when possible
- Preload critical fonts
**Don't ❌:**
- Load too many font weights
- Use fonts synchronously (blocking)
- Load fonts you don't need
---
## Related
- `images-guide.md` - Image guidelines
- `icons-guide.md` - Icon systems
- `cdn-resources.md` - CDN libraries

View file

@ -0,0 +1,144 @@
<!-- Context: ui/web/icons | Priority: medium | Version: 1.0 | Updated: 2026-02-05 -->
# Icon Systems
**Purpose**: Guidelines for using icon libraries
---
## Quick Reference
| Library | Loading | Recommended For |
|---------|---------|-----------------|
| Lucide | CDN script | Default choice |
| Heroicons | Inline SVG | Tailwind projects |
| Font Awesome | CDN CSS | Brand icons |
---
## Lucide Icons (Recommended Default)
### Loading
```html
<script src="https://unpkg.com/lucide@latest/dist/umd/lucide.min.js"></script>
<!-- Or specific version -->
<script src="https://unpkg.com/lucide@0.294.0/dist/umd/lucide.min.js"></script>
```
### Usage
```html
<i data-lucide="home"></i>
<i data-lucide="user"></i>
<i data-lucide="settings"></i>
<i data-lucide="heart" class="w-6 h-6 text-red-500"></i>
<script>lucide.createIcons();</script>
```
### Common Icons
```
Navigation: home, menu, x, chevron-down, arrow-left, arrow-right
User: user, user-plus, users, user-check
Actions: edit, trash, save, download, upload, share, copy
Communication: mail, message-circle, phone, send
Media: image, video, music, file, folder
UI: search, settings, bell, heart, star, bookmark
Status: check, x, alert-circle, info, help-circle
```
---
## Heroicons
### Usage (Inline SVG)
```html
<!-- Outline (24x24) -->
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3..." />
</svg>
<!-- Solid (20x20) -->
<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
<path d="M10.707 2.293a1 1 0 00-1.414 0l-7 7..." />
</svg>
```
---
## Font Awesome
### Loading
```html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
```
### Usage
```html
<!-- Solid -->
<i class="fas fa-home"></i>
<i class="fas fa-user"></i>
<!-- Regular -->
<i class="far fa-heart"></i>
<!-- Brands -->
<i class="fab fa-github"></i>
<i class="fab fa-twitter"></i>
<!-- Sizing -->
<i class="fas fa-home fa-2x"></i>
```
---
## Accessibility Best Practices
```html
<!-- Icon with visible text -->
<button class="flex items-center gap-2">
<i data-lucide="trash" aria-hidden="true"></i>
<span>Delete</span>
</button>
<!-- Icon-only button -->
<button aria-label="Delete item">
<i data-lucide="trash"></i>
</button>
<!-- Decorative icon -->
<div>
<i data-lucide="star" aria-hidden="true"></i>
<span>Featured</span>
</div>
<!-- Screen reader text -->
<button>
<i data-lucide="search" aria-hidden="true"></i>
<span class="sr-only">Search</span>
</button>
```
---
## Custom SVG
```html
<!-- Custom icon -->
<svg class="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 4v16m8-8H4" />
</svg>
<!-- Logo -->
<svg class="h-8 w-auto" viewBox="0 0 100 40" fill="currentColor">
<path d="M10 10h80v20H10z" />
</svg>
```
---
## Related
- `images-guide.md` - Image guidelines
- `fonts-guide.md` - Font loading
- `cdn-resources.md` - CDN libraries

View file

@ -0,0 +1,127 @@
<!-- Context: ui/web/images | Priority: medium | Version: 1.0 | Updated: 2026-02-05 -->
# Image Guidelines
**Purpose**: Guidelines for placeholder and responsive images
---
## Quick Reference
**Rule**: NEVER make up image URLs. Always use known placeholder services.
| Service | Best For | URL Pattern |
|---------|----------|-------------|
| Unsplash | Real photos | `source.unsplash.com/random/WxH/?category` |
| Placehold.co | Simple placeholders | `placehold.co/WxH` |
| Picsum | Random photos | `picsum.photos/W/H` |
---
## Unsplash (Recommended)
### Random Images
```html
<img src="https://source.unsplash.com/random/1200x800" alt="Random">
<img src="https://source.unsplash.com/random/1200x800/?nature" alt="Nature">
<img src="https://source.unsplash.com/random/1200x800/?technology" alt="Tech">
```
### Categories
- nature, landscape, mountains, ocean, forest
- technology, computer, code, workspace
- people, portrait, business, team
- food, coffee, restaurant
- architecture, building, interior
- travel, city, street
- abstract, pattern, texture
### Specific Images
```html
<img src="https://images.unsplash.com/photo-1506905925346-21bda4d32df4" alt="Mountain">
```
---
## Placehold.co
```html
<!-- Basic -->
<img src="https://placehold.co/800x600" alt="Placeholder">
<!-- Custom colors -->
<img src="https://placehold.co/800x600/EEE/31343C" alt="Placeholder">
<!-- With text -->
<img src="https://placehold.co/800x600?text=Product+Image" alt="Product">
<!-- Formats -->
<img src="https://placehold.co/800x600.webp" alt="WebP">
```
---
## Picsum Photos
```html
<img src="https://picsum.photos/800/600" alt="Random">
<img src="https://picsum.photos/id/237/800/600" alt="Specific">
<img src="https://picsum.photos/800/600?grayscale" alt="Grayscale">
<img src="https://picsum.photos/800/600?blur=2" alt="Blurred">
```
---
## Responsive Images
```html
<!-- srcset -->
<img
src="https://source.unsplash.com/random/800x600/?nature"
srcset="
https://source.unsplash.com/random/400x300/?nature 400w,
https://source.unsplash.com/random/800x600/?nature 800w,
https://source.unsplash.com/random/1200x900/?nature 1200w
"
sizes="(max-width: 768px) 100vw, 50vw"
alt="Nature"
loading="lazy"
>
<!-- Picture element -->
<picture>
<source srcset="url-1200" media="(min-width: 1024px)">
<source srcset="url-800" media="(min-width: 768px)">
<img src="url-400" alt="Responsive" loading="lazy">
</picture>
<!-- Background -->
<div
class="bg-cover bg-center"
style="background-image: url('https://source.unsplash.com/random/1200x800/?workspace')"
role="img"
aria-label="Workspace"
></div>
```
---
## Optimization
```html
<!-- Lazy loading -->
<img src="image.jpg" loading="lazy" alt="Description">
<!-- Modern formats with fallback -->
<picture>
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="Description">
</picture>
```
---
## Related
- `icons-guide.md` - Icon systems
- `fonts-guide.md` - Font loading
- `cdn-resources.md` - CDN libraries

View file

@ -12,11 +12,19 @@
| File | Description | Priority | | File | Description | Priority |
|------|-------------|----------| |------|-------------|----------|
| [animation-patterns.md](animation-patterns.md) | CSS animations, transitions, micro-interactions | high | | [animation-basics.md](animation-basics.md) | Animation fundamentals, timing, easing | high |
| [animation-components.md](animation-components.md) | Button, card, modal, dropdown animations | high |
| [animation-chat.md](animation-chat.md) | Chat UI and message animations | medium |
| [animation-loading.md](animation-loading.md) | Skeleton, spinner, progress animations | medium |
| [animation-forms.md](animation-forms.md) | Form input and validation animations | medium |
| [animation-advanced.md](animation-advanced.md) | Recipes, best practices, accessibility | medium |
| [ui-styling-standards.md](ui-styling-standards.md) | CSS frameworks, Tailwind patterns, styling best practices | high | | [ui-styling-standards.md](ui-styling-standards.md) | CSS frameworks, Tailwind patterns, styling best practices | high |
| [react-patterns.md](react-patterns.md) | Modern React patterns, hooks, component design | high | | [react-patterns.md](react-patterns.md) | Modern React patterns, hooks, component design | high |
| [design-systems.md](design-systems.md) | Design system principles and component libraries | medium | | [design-systems.md](design-systems.md) | Design system principles and component libraries | medium |
| [design-assets.md](design-assets.md) | Icons, fonts, images, and asset management | medium | | [images-guide.md](images-guide.md) | Placeholder and responsive images | medium |
| [icons-guide.md](icons-guide.md) | Icon systems (Lucide, Heroicons, FA) | medium |
| [fonts-guide.md](fonts-guide.md) | Font loading and optimization | medium |
| [cdn-resources.md](cdn-resources.md) | CDN libraries and resources | medium |
### Subcategories ### Subcategories
@ -34,8 +42,10 @@
3. Reference `animation-patterns.md` (if animations needed) 3. Reference `animation-patterns.md` (if animations needed)
### For animation work: ### For animation work:
1. Load `animation-patterns.md` (CSS animations, transitions) 1. Load `animation-basics.md` (fundamentals, timing, easing)
2. Reference `design/` subcategory for advanced patterns 2. Load `animation-components.md` (UI component animations)
3. Reference `animation-chat.md` for chat UI patterns
4. Reference `animation-advanced.md` for recipes and accessibility
### For scroll animations: ### For scroll animations:
1. Navigate to `design/` subcategory 1. Navigate to `design/` subcategory
@ -59,10 +69,10 @@ This subcategory covers:
## File Summaries ## File Summaries
### animation-patterns.md ### animation-basics.md, animation-components.md, animation-chat.md, animation-loading.md, animation-forms.md, animation-advanced.md
CSS animations, micro-interactions, and UI transitions. Covers timing standards, easing functions, button/card interactions, modals, loading states, and accessibility. CSS animations, micro-interactions, and UI transitions split into focused modules.
**Key topics**: Animation micro-syntax, 60fps performance, reduced motion, chat UI animations **Key topics**: Animation micro-syntax, 60fps performance, reduced motion, chat UI animations, component patterns
### ui-styling-standards.md ### ui-styling-standards.md
CSS framework usage, Tailwind CSS patterns, responsive design, and styling best practices. CSS framework usage, Tailwind CSS patterns, responsive design, and styling best practices.
@ -79,10 +89,10 @@ Design system principles, component libraries, and maintaining consistency acros
**Key topics**: Design tokens, component APIs, documentation, versioning **Key topics**: Design tokens, component APIs, documentation, versioning
### design-assets.md ### images-guide.md, icons-guide.md, fonts-guide.md, cdn-resources.md
Managing icons, fonts, images, and other design assets in web applications. Managing design assets in web applications - split into focused guides.
**Key topics**: Icon libraries (Lucide, Font Awesome), web fonts, image optimization **Key topics**: Placeholder images, icon libraries (Lucide, Heroicons), web fonts, CDN resources
--- ---
@ -101,6 +111,6 @@ Managing icons, fonts, images, and other design assets in web applications.
--- ---
## Statistics ## Statistics
- Core files: 5 - Core files: 8
- Subcategories: 1 (design/) - Subcategories: 1 (design/)
- **Total context files**: 5 + design subcategory - **Total context files**: 8 + design subcategory

View file

@ -0,0 +1,25 @@
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2022,
"sourceType": "module",
"project": "./tsconfig.json"
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended-requiring-type-checking"
],
"plugins": ["@typescript-eslint"],
"rules": {
"@typescript-eslint/explicit-function-return-type": "warn",
"@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }],
"@typescript-eslint/no-explicit-any": "warn",
"no-console": ["warn", { "allow": ["warn", "error", "log"] }]
},
"env": {
"node": true,
"es2022": true
},
"ignorePatterns": ["**/__tests__/**", "**/*.test.ts", "**/*.spec.ts"]
}

35
packages/compatibility-layer/.gitignore vendored Normal file
View file

@ -0,0 +1,35 @@
# Dependencies
node_modules/
# Build output
dist/
*.tsbuildinfo
# Coverage
coverage/
.nyc_output/
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# OS
.DS_Store
Thumbs.db
# Logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Environment
.env
.env.local
.env.*.local
# Testing
.vitest/

View file

@ -0,0 +1,368 @@
# @openagents-control/compatibility-layer
> Compatibility layer for converting OpenAgents Control agents to/from other AI coding tools
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.4-blue)](https://www.typescriptlang.org/)
[![Node](https://img.shields.io/badge/Node-%3E%3D18-green)](https://nodejs.org/)
## Overview
This package provides bidirectional conversion between OpenAgents Control (OAC) agent format and various AI coding tools:
- **Cursor IDE** - VSCode-based AI editor with `.cursorrules`
[![Cursor IDE](./docs/migration-guides/contextscout-cursor.png)](./docs/migration-guides/oac-to-cursor.md)
- **Claude Code** - Anthropic's official CLI with `config.json` and `agents/*.md`
[![Claude Code](./docs/migration-guides/claude-code-validation.png)](./docs/migration-guides/oac-to-claude.md)
- **Windsurf** - AI-powered development environment with JSON config
## Features
- ✅ **Bidirectional conversion** - Convert OAC ↔ Tool formats
- ✅ **Feature parity tracking** - Know what's supported in each tool
- ✅ **Graceful degradation** - Handle unsupported features with warnings
- ✅ **CLI tool** - Easy conversion from command line
- ✅ **Batch migration** - Migrate entire projects at once
- ✅ **Type-safe** - Full TypeScript with Zod validation
- ✅ **Extensible** - Plugin architecture for new tools
## Installation
```bash
# npm
npm install @openagents-control/compatibility-layer
# pnpm
pnpm add @openagents-control/compatibility-layer
```
## Quick Start
### CLI Usage
```bash
# Convert a single file
oac-compat convert agent.md -f cursor -o .cursorrules
# Convert with auto-detection of source format
oac-compat convert .cursorrules -f oac -o agent.md
# Validate compatibility before conversion
oac-compat validate agent.md -t claude --strict
# Migrate entire project
oac-compat migrate ./agents -f claude --out-dir ./output
# Preview migration without writing files
oac-compat migrate ./agents -f windsurf --dry-run
# Show platform capabilities
oac-compat info cursor
# Compare two platforms
oac-compat info cursor --compare claude
```
### Programmatic Usage
```typescript
import {
loadAgent,
getAdapter,
translate,
analyzeCompatibility,
} from "@openagents-control/compatibility-layer";
// Load an OAC agent
const agent = await loadAgent("./agent.md");
// Check compatibility with target platform
const compatibility = analyzeCompatibility(agent, "cursor");
console.log("Compatible:", compatibility.compatible);
console.log("Warnings:", compatibility.warnings);
console.log("Blockers:", compatibility.blockers);
// Convert to another format
const adapter = getAdapter("claude");
const result = await adapter.fromOAC(agent);
if (result.success) {
for (const config of result.configs) {
console.log(`File: ${config.fileName}`);
console.log(config.content);
}
}
// Or use the translate function for quick conversion
const translated = translate(agent, "cursor");
```
## CLI Commands
### `convert` - Convert a single file
```bash
oac-compat convert <input> -f <format> [options]
Options:
-f, --format <format> Target format (oac, cursor, claude, windsurf)
-o, --output <path> Output file path (stdout if omitted)
--from <format> Source format (auto-detect if omitted)
--force Overwrite existing output file
```
### `validate` - Check compatibility
```bash
oac-compat validate <input> -t <format> [options]
Options:
-t, --target <format> Target format to validate against
--strict Enable strict validation mode
```
### `migrate` - Batch migration
```bash
oac-compat migrate <source-dir> -f <format> [options]
Options:
-f, --format <format> Target format
-o, --out-dir <path> Output directory
--dry-run Preview without writing files
--force Overwrite existing files
```
### `info` - Platform information
```bash
oac-compat info [platform] [options]
Options:
-d, --detailed Show detailed capability information
-c, --compare <other> Compare with another platform
```
### Global Options
```bash
-v, --verbose Enable verbose output
-q, --quiet Suppress all output except errors
--output-format <format> Output format (text, json)
```
## Feature Parity Matrix
| Feature | OAC | Cursor | Claude | Windsurf |
| -------------------- | -------- | ---------- | ------ | -------- |
| **Config Format** | YAML+MD | Plain text | JSON | JSON |
| **Multiple Agents** | ✅ | ❌ | ✅ | ✅ |
| **Tool Permissions** | Granular | Binary | Binary | Binary |
| **Temperature** | ✅ | ❌ | ❌ | ✅ |
| **Skills/Contexts** | ✅ | ❌ | ✅ | ⚠️ |
| **Hooks** | ✅ | ❌ | ✅ | ❌ |
| **Model Selection** | ✅ | ✅ | ✅ | ✅ |
See [Feature Matrices](docs/feature-matrices.md) for detailed comparison.
## Migration Guides
- [Cursor → OAC](docs/migration-guides/cursor-to-oac.md) - Import from Cursor
- [Claude → OAC](docs/migration-guides/claude-to-oac.md) - Import from Claude Code
- [OAC → Cursor](docs/migration-guides/oac-to-cursor.md) - Export to Cursor
- [OAC → Claude](docs/migration-guides/oac-to-claude.md) - Export to Claude Code
- [OAC → Windsurf](docs/migration-guides/oac-to-windsurf.md) - Export to Windsurf
## API Reference
### Agent Loading
```typescript
import {
loadAgent,
loadAgents,
AgentLoader,
} from "@openagents-control/compatibility-layer";
// Load single agent
const agent = await loadAgent("./agent.md");
// Load all agents from directory
const agents = await loadAgents("./agents/");
// Using the loader class
const loader = new AgentLoader();
const agent = await loader.loadFromFile("./agent.md");
```
### Adapter Registry
```typescript
import {
registry,
getAdapter,
listAdapters,
} from "@openagents-control/compatibility-layer";
// Get adapter by name
const adapter = getAdapter("cursor");
// List all adapters
const names = listAdapters(); // ['cursor', 'claude', 'windsurf']
// Get all capabilities
const capabilities = getAllCapabilities();
```
### Translation Engine
```typescript
import {
translate,
previewTranslation,
TranslationEngine,
} from "@openagents-control/compatibility-layer";
// Quick translate
const result = translate(agent, "cursor");
// Preview without converting
const preview = previewTranslation(agent, "claude");
console.log("Features lost:", preview.featuresLost);
console.log("Features gained:", preview.featuresGained);
// Using the engine for more control
const engine = new TranslationEngine();
const result = engine.translate(agent, "windsurf", {
preserveComments: true,
strictMode: false,
});
```
### Mappers
```typescript
import {
mapToolFromOAC,
mapModelFromOAC,
mapPermissionsFromOAC,
mapContextPathFromOAC,
} from "@openagents-control/compatibility-layer";
// Map tool names
mapToolFromOAC("bash", "cursor"); // { name: 'terminal', exact: true }
// Map model identifiers
mapModelFromOAC("claude-sonnet-4", "cursor"); // { id: 'claude-3-sonnet', exact: true }
// Map permissions
mapPermissionsFromOAC({ bash: { "*": "allow" } }, "claude");
// { permissions: { bash: true }, warnings: [...] }
```
## Architecture
```
src/
├── types.ts # Zod schemas and TypeScript types
├── index.ts # Public API exports
├── core/
│ ├── AgentLoader.ts # OAC agent file parser
│ ├── AdapterRegistry.ts # Adapter management
│ ├── CapabilityMatrix.ts # Feature compatibility
│ └── TranslationEngine.ts # Orchestrates conversion
├── adapters/
│ ├── BaseAdapter.ts # Abstract base class
│ ├── CursorAdapter.ts # Cursor IDE adapter
│ ├── ClaudeAdapter.ts # Claude Code adapter
│ └── WindsurfAdapter.ts # Windsurf adapter
├── mappers/
│ ├── ToolMapper.ts # Tool name translation
│ ├── ModelMapper.ts # Model ID translation
│ ├── PermissionMapper.ts # Permission translation
│ └── ContextMapper.ts # Context path translation
└── cli/
├── index.ts # CLI entry point
├── types.ts # CLI types
├── utils.ts # CLI utilities
└── commands/
├── convert.ts # convert command
├── validate.ts # validate command
├── migrate.ts # migrate command
└── info.ts # info command
```
## Development
```bash
# Install dependencies
npm install
# Build
npm run build
# Run tests
npm test
# Test with coverage
npm run test:coverage
# Watch mode for development
npm run build:watch
# Lint
npm run lint
npm run lint:fix
```
## Creating Custom Adapters
```typescript
import {
BaseAdapter,
OpenAgent,
ConversionResult,
ToolCapabilities,
} from "@openagents-control/compatibility-layer";
class MyToolAdapter extends BaseAdapter {
readonly name = "my-tool";
readonly displayName = "My Tool";
readonly version = "1.0.0";
getCapabilities(): ToolCapabilities {
return {
supportsMultiAgent: false,
supportsSkills: false,
supportsHooks: false,
supportsGranularPermissions: false,
configFormat: "json",
};
}
async toOAC(source: string): Promise<OpenAgent> {
// Parse source and return OpenAgent
}
async fromOAC(agent: OpenAgent): Promise<ConversionResult> {
// Convert OpenAgent to your format
return {
success: true,
configs: [{ fileName: "config.json", content: "...", encoding: "utf-8" }],
warnings: [],
};
}
}
// Register the adapter
import { registry } from "@openagents-control/compatibility-layer";
registry.register(new MyToolAdapter());
```
## Contributing
See [CONTRIBUTING.md](../../CONTRIBUTING.md) for guidelines.
## License
MIT © OpenAgents Control Contributors

View file

@ -0,0 +1,193 @@
# Feature Compatibility Matrices
Comprehensive comparison of feature support across OpenAgents Control (OAC), Claude Code, Cursor IDE, and Windsurf platforms. Use these matrices to understand conversion impact before migrating agent configurations.
---
## Quick Reference - Platform Support Summary
| Platform | Config Format | Structure | Multiple Agents | Skills | Hooks | Granular Perms |
|----------|---------------|-----------|-----------------|--------|-------|----------------|
| **OAC** | Markdown+YAML | Directory | ✅ | ✅ | ✅ | ✅ |
| **Claude Code** | JSON/Markdown | Directory | ✅ | ✅ | ✅ | ❌ |
| **Cursor IDE** | Plain text | Single file | ❌ | ❌ | ❌ | ❌ |
| **Windsurf** | JSON | Directory | ✅ | ⚠️ | ❌ | ❌ |
**Legend:** ✅ Full support | ⚠️ Partial support | ❌ Not supported
---
## Detailed Matrices
### Tool/Permission Capabilities
| Feature | OAC | Claude Code | Cursor IDE | Windsurf |
|---------|-----|-------------|------------|----------|
| **bash/shell execution** | ✅ | ✅ | ✅ | ✅ |
| **file read** | ✅ | ✅ | ✅ | ✅ |
| **file write** | ✅ | ✅ | ✅ | ✅ |
| **file edit/patch** | ✅ | ✅ | ✅ | ✅ |
| **glob search** | ✅ | ✅ | ✅ | ✅ |
| **grep content search** | ✅ | ✅ | ✅ | ✅ |
| **task delegation** | ✅ | ✅ | ❌ | ⚠️ |
| **granular permissions** | ✅ | ❌ | ❌ | ❌ |
| **ask permissions** | ✅ | ❌ | ❌ | ❌ |
| **path pattern rules** | ✅ | ❌ | ❌ | ⚠️ |
**Notes:**
- Cursor has no task delegation - all work happens in a single agent
- All platforms reduce OAC granular permissions (allow/deny/ask per path) to binary on/off
- Windsurf's delegation is limited compared to Claude's full subagent system
---
### Configuration Features
| Feature | OAC | Claude Code | Cursor IDE | Windsurf |
|---------|-----|-------------|------------|----------|
| **custom model selection** | ✅ | ✅ | ✅ | ✅ |
| **temperature control** | ✅ | ❌ | ⚠️ | ⚠️ |
| **maxSteps limit** | ✅ | ❌ | ❌ | ❌ |
| **agent disable/hidden** | ✅ | ⚠️ | ❌ | ⚠️ |
| **custom prompts** | ✅ | ✅ | ✅ | ✅ |
| **version metadata** | ✅ | ⚠️ | ❌ | ⚠️ |
| **author metadata** | ✅ | ⚠️ | ❌ | ⚠️ |
| **tags** | ✅ | ❌ | ❌ | ⚠️ |
**Notes:**
- Claude does not support temperature configuration
- Cursor has limited temperature range support
- Windsurf maps temperature to "creativity" setting (low/medium/high)
- maxSteps is OAC-exclusive
---
### Context/Memory Features
| Feature | OAC | Claude Code | Cursor IDE | Windsurf |
|---------|-----|-------------|------------|----------|
| **external context files** | ✅ | ✅ | ❌ | ✅ |
| **context priority levels** | ✅ | ❌ | ❌ | ❌ |
| **context subdirectories** | ✅ | ✅ | ❌ | ✅ |
| **skills/modules system** | ✅ | ✅ | ❌ | ⚠️ |
| **context descriptions** | ✅ | ⚠️ | ❌ | ⚠️ |
| **dependency declarations** | ✅ | ✅ | ❌ | ⚠️ |
**Notes:**
- Cursor requires all context to be inline in `.cursorrules`
- OAC supports 4 priority levels: critical, high, medium, low
- Windsurf only supports high/low priority (medium/critical get degraded)
- Skills in Windsurf become basic context file references
---
### Agent/Mode Features
| Feature | OAC | Claude Code | Cursor IDE | Windsurf |
|---------|-----|-------------|------------|----------|
| **multiple agents** | ✅ | ✅ | ❌ | ✅ |
| **primary/subagent modes** | ✅ | ✅ | ❌ | ⚠️ |
| **agent categories** | ✅ | ⚠️ | ❌ | ⚠️ |
| **event hooks** | ✅ | ✅ | ❌ | ❌ |
| **hook matchers** | ✅ | ✅ | ❌ | ❌ |
| **priority levels** | ✅ (4) | ⚠️ (2) | ❌ | ⚠️ (2) |
**Notes:**
- Cursor merges all agents into a single `.cursorrules` file
- Hook events supported by Claude: PreToolUse, PostToolUse, PermissionRequest, AgentStart, AgentEnd
- Windsurf has limited mode distinction
---
## Conversion Impact
### Lossless Conversions
These conversions preserve all features without degradation:
| From | To | Notes |
|------|-----|-------|
| Cursor | OAC | Full upgrade - gains all OAC features |
| Cursor | Claude | Gains hooks, skills, multiple agents |
| Cursor | Windsurf | Gains multiple agents, contexts |
| Claude | OAC | Full upgrade - gains granular permissions, temperature |
| Windsurf | OAC | Full upgrade - gains hooks, granular permissions |
---
### Lossy Conversions
These conversions result in feature loss or degradation:
| From | To | What's Lost/Degraded |
|------|-----|---------------------|
| OAC | Claude | Temperature, maxSteps, granular permissions → binary |
| OAC | Cursor | **Significant loss**: hooks, skills, multiple agents, contexts (inline only), granular permissions |
| OAC | Windsurf | Hooks, granular permissions, context priority (4→2 levels), temperature → creativity |
| Claude | Cursor | **Significant loss**: hooks, skills, multiple agents, contexts |
| Claude | Windsurf | Hooks, temperature |
| Windsurf | Cursor | Multiple agents merged, skills lost, contexts inline only |
| Windsurf | Claude | Temperature mapping may be imprecise |
---
## Platform-Specific Notes
### OpenAgents Control (OAC)
- **Config location**: `.opencode/agent/` directory
- **Format**: Markdown files with YAML frontmatter
- **Strengths**: Full feature support, granular permissions, 4-level priorities
- **Best for**: Complex multi-agent workflows requiring fine-grained control
### Claude Code
- **Config location**: `.claude/` directory
- **Primary config**: `.claude/config.json` or `.claude/agents/*.md`
- **Strengths**: Full hooks support, skills system, multiple agents
- **Limitations**: No temperature control, binary permissions only
- **Permission modes**: default, acceptEdits, dontAsk, bypassPermissions
### Cursor IDE
- **Config location**: `.cursorrules` (single file in project root)
- **Format**: Plain text with optional YAML frontmatter
- **Strengths**: Simple setup, universal tool support
- **Limitations**: Single agent only, no external contexts, no hooks/skills
- **Best for**: Simple, single-purpose project rules
### Windsurf
- **Config location**: `.windsurf/` directory
- **Primary config**: `.windsurf/config.json`
- **Strengths**: Multiple agents, context files, creativity settings
- **Limitations**: No hooks, binary permissions, 2-level priority only
- **Temperature mapping**: `≤0.4` → low, `0.4-0.8` → medium, `>0.8` → high
---
## Version Compatibility
| Package Version | OAC Schema | Claude Support | Cursor Support | Windsurf Support |
|-----------------|------------|----------------|----------------|------------------|
| 1.0.x | v1.0 | ✅ Full | ✅ Full | ✅ Full |
### Model Mappings
| OAC Model ID | Claude Code | Cursor IDE | Windsurf |
|--------------|-------------|------------|----------|
| `claude-sonnet-4` | `claude-sonnet-4-20250514` | `claude-sonnet-4` | `claude-4-sonnet` |
| `claude-opus-4` | `claude-opus-4-20250514` | `claude-opus-4` | `claude-4-opus` |
| `claude-3.5-sonnet` | `claude-3-5-sonnet-20241022` | `claude-3.5-sonnet` | `claude-3-5-sonnet` |
| `gpt-4` | — | `gpt-4` | `gpt-4` |
| `gpt-4-turbo` | — | `gpt-4-turbo` | `gpt-4-turbo` |
| `gpt-4o` | — | `gpt-4o` | `gpt-4o` |
### Tool Name Mappings
| OAC Tool | Claude Code | Cursor IDE | Windsurf |
|----------|-------------|------------|----------|
| `bash` | `Bash` | `terminal` | `shell` |
| `read` | `Read` | `file_read` | `read_file` |
| `write` | `Write` | `file_write` | `write_file` |
| `edit` | `Edit` | `file_edit` | `edit_file` |
| `glob` | `Glob` | `file_search` | `find_files` |
| `grep` | `Grep` | `content_search` | `search_content` |
| `task` | `Task` | ❌ (unsupported) | `delegate` |
| `patch` | `Edit` | `file_edit` | `edit_file` |

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

View file

@ -0,0 +1,606 @@
# Migrating from Claude Code to OAC
> Convert your `.claude/` configuration to OpenAgents Control format and gain temperature control, maxSteps limits, and granular per-path permissions.
## Overview
Claude Code uses `.claude/config.json` for primary agents and `.claude/agents/*.md` for subagents. OAC provides all Claude Code capabilities plus temperature control, step limits, and granular permissions that Claude's binary permission modes can't express.
## Prerequisites
**Required:**
- Node.js >= 18
- npm or pnpm
**Install the compatibility layer:**
```bash
npm install @openagents-control/compatibility-layer
```
## Quick Migration
**One command conversion:**
```bash
oac-compat convert .claude/config.json -f oac -o agent.md
```
For subagents:
```bash
oac-compat convert .claude/agents/code-reviewer.md -f oac -o .opencode/agent/code-reviewer.md
```
**Verify the result:**
```bash
oac-compat validate agent.md
```
## Step-by-Step Manual Migration
### 1. Claude Code Structure
Claude Code uses a directory-based structure:
```
.claude/
├── config.json # Primary agent configuration
├── agents/ # Subagent definitions
│ ├── code-reviewer.md
│ └── doc-writer.md
└── skills/ # Context injection
└── project-context/
└── SKILL.md
```
**Primary agent (config.json):**
```json
{
"name": "main-agent",
"description": "Primary development assistant",
"systemPrompt": "You are a senior developer.",
"model": "claude-sonnet-4-20250514",
"tools": ["Read", "Write", "Bash"],
"permissionMode": "default",
"skills": ["project-context"],
"hooks": {
"PreToolUse": [
{
"matcher": "Write",
"hooks": [{ "type": "command", "command": "npm run lint" }]
}
]
}
}
```
**Subagent (agents/code-reviewer.md):**
```yaml
---
name: "code-reviewer"
description: "Reviews code for quality"
tools: "Read, Grep, Glob"
model: "sonnet"
permissionMode: "default"
---
You are a code reviewer. Analyze code for:
- Best practices
- Performance issues
- Security vulnerabilities
```
### 2. OAC Agent Structure
OAC agents use markdown with YAML frontmatter:
```yaml
---
name: main-agent
description: Primary development assistant
mode: primary
model: claude-sonnet-4
temperature: 0.7
maxSteps: 50
tools:
read: true
write: true
bash: true
permission:
write:
"/src/**": allow
"/config/**": ask
"/**": deny
skills:
- context-manager
hooks:
- event: PreToolUse
matchers:
- "write"
commands:
- type: command
command: "npm run lint"
---
# Main Agent
You are a senior developer.
## Guidelines
- Write clean, maintainable code
- Follow project conventions
```
### 3. Key Differences
| Aspect | Claude Code | OAC |
|--------|-------------|-----|
| **Config location** | `.claude/` directory | `.opencode/agent/` directory |
| **Primary config** | `config.json` (JSON) | `agent.md` (YAML frontmatter) |
| **Subagent format** | Markdown with YAML | Markdown with YAML |
| **Model IDs** | `claude-sonnet-4-20250514` | `claude-sonnet-4` |
| **Tools format** | Array: `["Read", "Write"]` | Object: `{ read: true, write: true }` |
| **Permissions** | Binary modes only | Granular per-path rules |
| **Temperature** | Not supported | Full control (0.0-2.0) |
| **Max steps** | Not supported | Configurable limit |
| **Skills path** | `.claude/skills/` | `.opencode/skill/` |
### 4. Feature Mapping
| Claude Code Feature | OAC Equivalent | Notes |
|---------------------|----------------|-------|
| `name` | `frontmatter.name` | Direct mapping |
| `description` | `frontmatter.description` | Direct mapping |
| `systemPrompt` | Body content (markdown) | Becomes structured markdown |
| `model: "claude-sonnet-4-20250514"` | `model: claude-sonnet-4` | Simplified ID |
| `model: "sonnet"` | `model: claude-sonnet-4` | Alias resolved |
| `model: "opus"` | `model: claude-opus-4` | Alias resolved |
| `model: "haiku"` | `model: claude-haiku-4` | Alias resolved |
| `tools: ["Read", "Write"]` | `tools: { read: true, write: true }` | Object format |
| `permissionMode: "default"` | `permission: { ... }` | Granular rules available |
| `permissionMode: "bypassPermissions"` | `permission: { "*": "allow" }` | Full access |
| `permissionMode: "dontAsk"` | `permission: { "*": "deny" }` | Auto-deny |
| `skills: ["name"]` | `skills: [name]` | Direct mapping |
| `hooks.PreToolUse` | `hooks: [{ event: PreToolUse }]` | Array format |
| (not available) | `frontmatter.temperature` | New capability |
| (not available) | `frontmatter.maxSteps` | New capability |
| (not available) | Granular path permissions | New capability |
### 5. Common Patterns
#### Pattern 1: Primary Agent Config
**Before (Claude Code - config.json):**
```json
{
"name": "typescript-dev",
"description": "TypeScript development assistant",
"systemPrompt": "You are a senior TypeScript developer. Follow strict mode. Write tests.",
"model": "claude-sonnet-4-20250514",
"tools": ["Read", "Write", "Edit", "Bash"],
"permissionMode": "default"
}
```
**After (OAC):**
```yaml
---
name: typescript-dev
description: TypeScript development assistant
mode: primary
model: claude-sonnet-4
temperature: 0.7
tools:
read: true
write: true
edit: true
bash: true
permission:
write:
"/src/**": allow
"/tests/**": allow
"/**": ask
---
# TypeScript Developer
You are a senior TypeScript developer.
## Guidelines
- Follow strict mode
- Write tests for all code
- Use type-safe patterns
```
---
#### Pattern 2: Subagent Migration
**Before (Claude Code - agents/code-reviewer.md):**
```yaml
---
name: "code-reviewer"
description: "Reviews code for quality and best practices"
tools: "Read, Grep, Glob"
model: "sonnet"
permissionMode: "default"
---
You are a code reviewer. Focus on:
- Code quality
- Performance issues
- Security vulnerabilities
```
**After (OAC):**
```yaml
---
name: code-reviewer
description: Reviews code for quality and best practices
mode: subagent
model: claude-sonnet-4
tools:
read: true
grep: true
glob: true
write: false
edit: false
bash: false
---
# Code Reviewer
You are a code reviewer.
## Focus Areas
- Code quality and maintainability
- Performance issues and bottlenecks
- Security vulnerabilities and risks
## Output Format
Provide findings as:
1. **Issue**: Description
2. **Location**: File and line
3. **Severity**: High/Medium/Low
4. **Recommendation**: Fix suggestion
```
---
#### Pattern 3: Hooks Migration
**Before (Claude Code - config.json hooks):**
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write",
"hooks": [{ "type": "command", "command": "npm run lint:check" }]
},
{
"matcher": "Bash",
"hooks": [{ "type": "command", "command": "echo 'Executing bash...'" }]
}
],
"PostToolUse": [
{
"matcher": "*",
"hooks": [{ "type": "command", "command": "npm run test:affected" }]
}
]
}
}
```
**After (OAC):**
```yaml
---
name: validated-dev
description: Developer with validation hooks
mode: primary
hooks:
- event: PreToolUse
matchers:
- "write"
commands:
- type: command
command: "npm run lint:check"
- event: PreToolUse
matchers:
- "bash"
commands:
- type: command
command: "echo 'Executing bash...'"
- event: PostToolUse
matchers:
- "*"
commands:
- type: command
command: "npm run test:affected"
---
```
---
#### Pattern 4: Skills to Contexts Migration
**Before (Claude Code - .claude/skills/api-docs/SKILL.md):**
```yaml
---
name: api-docs
description: API documentation context
---
# API Documentation
This skill provides API documentation context.
Load from: `docs/api/`
```
**After (OAC contexts):**
```yaml
---
name: api-aware-agent
description: Agent with API documentation context
mode: primary
---
# API-Aware Agent
<!-- Contexts auto-loaded from .opencode/context/ -->
```
With context file `.opencode/context/api-docs.md`:
```yaml
---
path: docs/api/
priority: high
description: API documentation for reference
---
# API Documentation Context
Reference these docs when working with API endpoints.
```
---
#### Pattern 5: Granular Permissions (OAC Exclusive)
Claude Code only supports binary permission modes. OAC enables per-path rules:
**Claude Code (limited):**
```json
{
"permissionMode": "default"
}
```
**OAC (granular):**
```yaml
---
name: safe-developer
description: Developer with path-based permissions
mode: primary
permission:
write:
"/src/**": allow
"/tests/**": allow
"/docs/**": allow
"/config/**": ask
"/package.json": ask
"/.env*": deny
"/**": deny
bash:
"npm run *": allow
"git *": allow
"rm *": deny
"*": ask
---
```
### 6. Limitations
Features that don't fully translate between formats:
| Feature | Claude Code | OAC | Migration Notes |
|---------|-------------|-----|-----------------|
| Temperature | Not supported | Full support | Set desired value after migration |
| Max steps | Not supported | Configurable | Add limit after migration |
| Granular permissions | Binary modes | Per-path rules | Expand after migration |
| Permission mode `acceptEdits` | Supported | No direct equivalent | Use `permission: { edit: "allow" }` |
| Skill directory structure | `.claude/skills/` | `.opencode/skill/` | Move and rename |
| Agent directory | `.claude/agents/` | `.opencode/agent/` | Move and rename |
### 7. Validation
**Validate your migrated agent:**
```bash
# Check OAC format validity
oac-compat validate agent.md
# Compare capabilities
oac-compat info --tool claude
oac-compat info --tool oac
# Test round-trip conversion
oac-compat convert agent.md -f claude -o .claude/config.test.json
```
**Programmatic validation:**
```typescript
import { loadAgent, validateAgent } from '@openagents-control/compatibility-layer';
const agent = await loadAgent('./agent.md');
const errors = validateAgent(agent);
if (errors.length === 0) {
console.log('Agent is valid!');
} else {
console.error('Validation errors:', errors);
}
```
**Verify feature preservation:**
```typescript
import { ClaudeAdapter } from '@openagents-control/compatibility-layer';
const adapter = new ClaudeAdapter();
const capabilities = adapter.getCapabilities();
console.log('Claude supports:');
console.log('- Multiple agents:', capabilities.supportsMultipleAgents);
console.log('- Skills:', capabilities.supportsSkills);
console.log('- Hooks:', capabilities.supportsHooks);
console.log('- Temperature:', capabilities.supportsTemperature); // false
console.log('- Max steps:', capabilities.supportsMaxSteps); // false
console.log('- Granular perms:', capabilities.supportsGranularPermissions); // false
```
## Troubleshooting
### Model ID not recognized
**Symptom:** Model defaults to `sonnet` or conversion warning appears.
**Cause:** Claude Code uses full version IDs like `claude-sonnet-4-20250514`.
**Fix:** OAC uses simplified model IDs:
| Claude Code | OAC |
|-------------|-----|
| `claude-sonnet-4-20250514` | `claude-sonnet-4` |
| `claude-opus-4` | `claude-opus-4` |
| `claude-haiku-4` | `claude-haiku-4` |
| `sonnet` | `claude-sonnet-4` |
| `opus` | `claude-opus-4` |
| `haiku` | `claude-haiku-4` |
---
### Tools array not converting
**Symptom:** Tools show as all disabled or wrong format.
**Cause:** Claude uses capitalized array format; OAC uses lowercase object format.
**Fix:** Convert manually:
```json
// Claude Code
"tools": ["Read", "Write", "Bash"]
```
```yaml
# OAC
tools:
read: true
write: true
bash: true
edit: false
grep: false
glob: false
```
---
### Permission mode warning
**Symptom:** Warning about permission degradation.
**Cause:** Claude's `permissionMode` is binary; can't express granular rules.
**Fix:** After migration, expand to granular permissions:
```yaml
# Instead of permissionMode: "default"
permission:
write:
"/src/**": allow
"/config/**": ask
"/**": deny
bash:
"npm *": allow
"git *": allow
"*": ask
```
---
### Hooks not triggering
**Symptom:** Hooks defined but not executing.
**Cause:** Hook event names or matchers may differ.
**Fix:** Verify hook format:
```yaml
hooks:
- event: PreToolUse # Exact event name
matchers:
- "write" # Lowercase tool name
- "edit"
commands:
- type: command
command: "npm run lint"
```
Valid events: `PreToolUse`, `PostToolUse`, `PermissionRequest`, `AgentStart`, `AgentEnd`
---
### Skills not found
**Symptom:** Skills referenced but not loading.
**Cause:** Different directory structure between Claude Code and OAC.
**Fix:** Move skills to OAC location:
```bash
# Claude Code location
.claude/skills/my-skill/SKILL.md
# OAC location
.opencode/skill/my-skill/SKILL.md
```
Update skill references in agent:
```yaml
skills:
- my-skill # Name matches directory
```
## Next Steps
- **[OAC Agent Configuration](../configuration/agent-format.md)** - Deep dive into OAC format
- **[Granular Permissions](../features/permissions.md)** - Per-path permission rules
- **[Skills System](../features/skills.md)** - Dynamic skill loading
- **[Hooks Reference](../features/hooks.md)** - Event-driven automation
- **[OAC → Claude Migration](./oac-to-claude.md)** - Reverse migration guide

Binary file not shown.

After

Width:  |  Height:  |  Size: 266 KiB

View file

@ -0,0 +1,480 @@
# Migrating from Cursor to OAC
> Convert your `.cursorrules` to OpenAgents Control format and unlock Skills, Hooks, multi-agent support, and granular permissions.
## Overview
**Why migrate?**
| Feature | Cursor | OAC |
|---------|--------|-----|
| Multiple agents | Single file only | Unlimited agents |
| Skills system | Not supported | Full support |
| Hooks | Not supported | Event-driven hooks |
| Permissions | Binary (on/off) | Granular (allow/deny/ask per path) |
| Contexts | Inline only | External context files |
OAC provides a superset of Cursor's capabilities while maintaining backward compatibility.
## Prerequisites
**Required:**
- Node.js >= 18
- npm or pnpm
**Install the compatibility layer:**
```bash
npm install @openagents-control/compatibility-layer
```
## Quick Migration
**One command conversion:**
```bash
oac-compat convert .cursorrules -f oac -o agent.md
```
This reads your `.cursorrules` file and generates an OAC-compatible `agent.md`.
**Verify the result:**
```bash
oac-compat validate agent.md
```
## Step-by-Step Manual Migration
### 1. Cursor Rules Structure
Cursor uses a single `.cursorrules` file in the project root. Two formats are supported:
**Plain text format:**
```
You are a senior TypeScript developer.
Always use strict mode.
Prefer functional programming patterns.
Write comprehensive tests for all code.
```
**Frontmatter format (optional):**
```yaml
---
name: typescript-dev
description: TypeScript development assistant
model: gpt-4
temperature: 0.7
---
You are a senior TypeScript developer.
Always use strict mode.
Prefer functional programming patterns.
Write comprehensive tests for all code.
```
### 2. OAC Agent Structure
OAC agents use markdown with YAML frontmatter:
```yaml
---
name: typescript-dev
description: TypeScript development assistant
mode: primary
model: gpt-4
temperature: 0.7
tools:
read: true
write: true
edit: true
bash: true
grep: true
glob: true
---
# TypeScript Developer
You are a senior TypeScript developer.
## Guidelines
- Always use strict mode
- Prefer functional programming patterns
- Write comprehensive tests for all code
## Skills
<!-- Skills can be loaded dynamically -->
## Contexts
<!-- External context files for domain knowledge -->
```
### 3. Key Differences
| Aspect | Cursor | OAC |
|--------|--------|-----|
| **File format** | `.cursorrules` (plain/YAML) | `.md` with YAML frontmatter |
| **Location** | Project root | `.opencode/agent/` directory |
| **Multiple agents** | Not supported | Full support |
| **Tool config** | Implicit or comma-separated | Explicit object with booleans |
| **Permissions** | Binary only | Granular rules per path |
| **Context handling** | Inline in prompt | External files with priority |
| **Skills** | Not supported | Dynamic skill loading |
| **Hooks** | Not supported | Event-driven lifecycle hooks |
### 4. Feature Mapping
| Cursor Feature | OAC Equivalent | Notes |
|----------------|----------------|-------|
| `name` | `frontmatter.name` | Direct mapping |
| `description` | `frontmatter.description` | Direct mapping |
| `model: gpt-4` | `frontmatter.model: gpt-4` | Direct mapping |
| `model: claude-3-opus` | `frontmatter.model: claude-opus-3` | Model ID normalized |
| `model: claude-3-sonnet` | `frontmatter.model: claude-sonnet-3` | Model ID normalized |
| `model: claude-3-haiku` | `frontmatter.model: claude-haiku-3` | Model ID normalized |
| `temperature` | `frontmatter.temperature` | Direct mapping |
| `tools: "read, write"` | `tools: { read: true, write: true }` | Object format |
| Plain text body | `systemPrompt` | Becomes the agent prompt |
| (not available) | `frontmatter.mode` | Set to `primary` or `subagent` |
| (not available) | `frontmatter.skills` | Add skill references |
| (not available) | `frontmatter.hooks` | Add lifecycle hooks |
| (not available) | `frontmatter.permission` | Add granular permissions |
| (not available) | `contexts` | Add external context files |
### 5. Common Patterns
#### Pattern 1: Basic Rules
**Before (Cursor):**
```
You are a helpful coding assistant.
Follow best practices for clean code.
Always explain your changes.
```
**After (OAC):**
```yaml
---
name: code-assistant
description: Helpful coding assistant
mode: primary
---
# Code Assistant
You are a helpful coding assistant.
## Guidelines
- Follow best practices for clean code
- Always explain your changes
```
---
#### Pattern 2: Tool Configuration
**Before (Cursor):**
```yaml
---
name: restricted-agent
tools: read, grep, glob
---
You can only read and search files.
Do not modify any files.
```
**After (OAC):**
```yaml
---
name: restricted-agent
description: Read-only agent for code analysis
mode: primary
tools:
read: true
grep: true
glob: true
write: false
edit: false
bash: false
---
# Restricted Agent
You can only read and search files.
## Restrictions
- Read files: ALLOWED
- Search files: ALLOWED
- Modify files: DENIED
- Execute commands: DENIED
```
---
#### Pattern 3: Model Configuration
**Before (Cursor):**
```yaml
---
name: creative-writer
model: claude-3-opus
temperature: 0.9
---
Write creative and engaging documentation.
```
**After (OAC):**
```yaml
---
name: creative-writer
description: Creative documentation writer
mode: primary
model: claude-opus-3
temperature: 0.9
tools:
read: true
write: true
edit: true
---
# Creative Writer
Write creative and engaging documentation.
## Style Guidelines
- Use vivid language
- Include examples
- Make content accessible
```
> **Note:** Claude model IDs are normalized (`claude-3-opus` → `claude-opus-3`).
---
#### Pattern 4: Adding OAC-Exclusive Features
After migrating, enhance your agent with OAC-exclusive features:
**Add Skills:**
```yaml
---
name: full-stack-dev
description: Full-stack development assistant
mode: primary
skills:
- context-manager
- task-management
---
```
**Add Hooks:**
```yaml
---
name: validated-writer
description: Writer with validation hooks
mode: primary
hooks:
- event: PreToolUse
matchers:
- "write"
- "edit"
commands:
- type: command
command: "npm run lint:check"
---
```
**Add Granular Permissions:**
```yaml
---
name: safe-modifier
description: Agent with path-based permissions
mode: primary
permission:
write:
"/src/**": allow
"/tests/**": allow
"/config/**": ask
"/**": deny
---
```
**Add Contexts:**
```yaml
---
name: context-aware
description: Agent with external context files
mode: primary
---
# Context-Aware Agent
<!-- Contexts loaded automatically -->
```
With context files in `.opencode/context/`:
```
.opencode/context/
├── core/
│ ├── architecture.md
│ └── conventions.md
└── domain/
└── business-rules.md
```
### 6. Limitations
Features that don't exist in Cursor (gained during migration):
| Feature | Cursor | OAC | Workaround |
|---------|--------|-----|------------|
| Multiple agents | Single file | Unlimited | Create separate agent files |
| Skills system | None | Full support | Inline skill content in prompt |
| Hooks | None | Event-driven | Manual validation steps |
| Granular permissions | Binary | Per-path rules | Document restrictions in prompt |
| External contexts | None | Priority-based | Inline context in prompt |
| Subagent mode | None | Delegation support | Use primary mode only |
| Max steps | None | Configurable | Not available in Cursor |
### 7. Validation
**Validate your migrated agent:**
```bash
# Check OAC format validity
oac-compat validate agent.md
# Compare capabilities
oac-compat info --tool cursor
oac-compat info --tool oac
# Test round-trip conversion
oac-compat convert agent.md -f cursor -o .cursorrules.test
```
**Programmatic validation:**
```typescript
import { loadAgent, validateAgent } from '@openagents-control/compatibility-layer';
const agent = await loadAgent('./agent.md');
const errors = validateAgent(agent);
if (errors.length === 0) {
console.log('Agent is valid!');
} else {
console.error('Validation errors:', errors);
}
```
## Troubleshooting
### Frontmatter not parsing
**Symptom:** Agent name shows as `cursor-agent` instead of your custom name.
**Cause:** Frontmatter must have exact format with `---` delimiters.
**Fix:**
```yaml
---
name: my-agent
---
Content here...
```
Not:
```yaml
---
name: my-agent
Content here...
```
---
### Model not recognized
**Symptom:** Model defaults to `gpt-4`.
**Cause:** Cursor model IDs differ from OAC.
**Fix:** Use OAC model IDs:
| Cursor | OAC |
|--------|-----|
| `claude-3-opus` | `claude-opus-3` |
| `claude-3-sonnet` | `claude-sonnet-3` |
| `claude-3-haiku` | `claude-haiku-3` |
| `gpt-4` | `gpt-4` |
| `gpt-4-turbo` | `gpt-4-turbo` |
| `gpt-4o` | `gpt-4o` |
---
### Tools not working
**Symptom:** Agent can't use expected tools.
**Cause:** Tools must be explicitly enabled in OAC.
**Fix:** Add tools to frontmatter:
```yaml
tools:
read: true
write: true
edit: true
bash: true
grep: true
glob: true
```
---
### Content appears duplicated
**Symptom:** System prompt contains frontmatter text.
**Cause:** Frontmatter delimiters missing or malformed.
**Fix:** Ensure proper YAML frontmatter format:
```yaml
---
name: agent-name
---
Content starts here (not in frontmatter).
```
## Next Steps
- **[OAC Agent Configuration](../configuration/agent-format.md)** - Deep dive into OAC format
- **[Skills System](../features/skills.md)** - Learn to use dynamic skills
- **[Hooks Reference](../features/hooks.md)** - Event-driven automation
- **[Multi-Agent Setup](../features/multi-agent.md)** - Configure agent delegation
- **[OAC → Cursor Migration](./oac-to-cursor.md)** - Reverse migration guide

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