🔧 chore: update agent documentation and enhance prompt architecture with structured XML methodology

This commit is contained in:
darrenhinde 2025-09-18 16:02:28 +01:00
parent 2ca29f0e6f
commit b4927fc1b0
9 changed files with 1404 additions and 56 deletions

View file

@ -0,0 +1,760 @@
# The OpenCode Agent System Blueprint
_Build Intelligent Workflow Systems with Context-Aware AI_
## The Golden Rule
**Context flows in one direction: Commands load context immediately, Agents can look up additional context deterministically.**
Like a well-organized library: the librarian (command) brings you the right books immediately, but you (agent) can look up specific references when needed.
## How @ Symbol Context Loading Works (FUNDAMENTAL)
### The Magic of Automatic Context Injection
When you create a slash command with @ references, OpenCode automatically loads that context into the agent's memory BEFORE the agent starts thinking:
```markdown
# .opencode/command/create-component.md
---
name: create-component
agent: simple-coder
---
You are creating React components following our patterns.
**Request:** $ARGUMENTS
@.opencode/context/frontend/react-patterns.md
@.opencode/context/styling/design-system.md
@.opencode/context/core/validation-patterns.md
Create the component now.
```
**What happens when user types `/create-component "user profile card"`:**
1. ✅ OpenCode reads the command file
2. ✅ **Automatically loads** react-patterns.md, design-system.md, validation-patterns.md
3. ✅ **Injects all context** into the agent's working memory
4. ✅ Agent receives: user request + all loaded context + instructions
5. ✅ Agent can immediately use patterns without looking them up
### Why This Mechanism Is Powerful
**❌ Without @ loading:**
```
Agent: "I need to create a component but don't know your patterns. Let me search..."
→ Agent uses generic patterns or has to look up files
→ Inconsistent results, slower execution
```
**✅ With @ loading:**
```
Agent: "I have your React patterns, design system, and validation rules loaded. Creating component..."
→ Agent immediately follows your exact patterns
→ Consistent, fast, high-quality results
```
### Context Loading Strategy
**Base Context (Always Load):**
```markdown
@.opencode/context/core/essential-patterns.md
@.opencode/context/architecture/project-structure.md
```
**Domain-Specific Context (Load Based on Command Purpose):**
```markdown
# Frontend commands
@.opencode/context/frontend/react-patterns.md
@.opencode/context/styling/design-system.md
# Backend commands
@.opencode/context/backend/server-patterns.md
@.opencode/context/database/query-patterns.md
# Testing commands
@.opencode/context/testing/test-patterns.md
```
### Dynamic Context Loading
```markdown
# Advanced: Conditional context based on request analysis
@.opencode/context/core/essential-patterns.md
!`if echo "$ARGUMENTS" | grep -i "component\|ui" > /dev/null; then echo "@.opencode/context/frontend/react-patterns.md"; fi`
!`if echo "$ARGUMENTS" | grep -i "database\|query" > /dev/null; then echo "@.opencode/context/database/query-patterns.md"; fi`
```
### Best Practices for @ Context Loading
1. **Load 2-4 context files maximum** (prevent cognitive overload)
2. **Always include core patterns** (essential-patterns.md)
3. **Load domain-specific patterns** based on command purpose
4. **Keep context files focused** (50-150 lines each)
5. **Use conditional loading** for dynamic context selection
### Why This Architecture Matters
Understanding @ symbol auto-loading is crucial because:
- **It's the foundation** of how agents get consistent context
- **It determines command design** - you must anticipate what context agents need
- **It explains the architecture** - why commands are "smart loaders" and agents are "focused executors"
- **It guides best practices** - load the right context, not too much, not too little
**This mechanism is what makes the system "intelligent" - agents always start with the right knowledge instead of having to discover it.**
## Core Principles
### 1. Single-Level Context Loading
**OpenCode processes `@` references only in command templates, NOT recursively in file contents.**
```markdown
# ✅ This works (in command template)
@.opencode/context/frontend/patterns.md
@.opencode/context/styling/design-system.md
# ❌ This doesn't work (inside patterns.md file)
# If patterns.md contains @other-file.md, it's treated as plain text
```
**Critical Implication**: Commands must load ALL necessary context upfront using @ references. Agents can look up additional files using tools (read, grep, glob), but cannot use @ loading themselves.
### 2. Deterministic vs Non-Deterministic Behavior
- **Commands**: Non-deterministic - analyze requests and load appropriate context
- **Agents**: Deterministic - predictable behavior, can look up additional context
### 3. Context Optimization
- **Maximum 4 context files per command** (250-450 lines total)
- **50-150 lines per context file** (optimal range)
- **Always load core patterns** + request-specific context
## The 5-Part Intelligent System
### 1. Commands (.opencode/command/)
**What:** Entry points that load immediate context based on request analysis
**Rule:** Commands are non-deterministic - they adapt context to the request
```
/workflow → Intelligent routing with dynamic context
/plan-task → Task planning with architecture context
/execute-task → Step execution with progress tracking
/create-frontend-component → UI development with styling + frontend context
/create-backend-operation → Server logic with backend + database context
/create-database-operation → Database queries with focused database context
/review-completion → Quality assurance with minimal context
/validate-with-tests → Automated testing with testing context
```
**Command Structure Pattern:**
```markdown
---
name: command-name
agent: target-agent
description: "What this command does"
---
You are [doing specific task]. [Direct instructions to agent].
**Request:** $ARGUMENTS
**Your Instructions:**
1. **ANALYZE** the request...
2. **IMPLEMENT** following patterns...
3. **VALIDATE** the results...
**Context Loaded:**
@.opencode/context/core/essential-patterns.md
@.opencode/context/[domain]/[specific-patterns].md
@.opencode/context/architecture/architecture-lite.md
**Success Criteria:**
- [Specific measurable outcomes]
Execute this [task type] now.
```
### 2. Agents (.opencode/agent/)
**What:** Deterministic AI workers with specific capabilities
**Rule:** Agents can look up additional context but are predictable in behavior
```
Primary Agents:
├── workflow-orchestrator.md → Routes requests and analyzes complexity
├── task-planner.md → Creates detailed task plans with file tracking
├── task-executor.md → Executes planned steps systematically
├── post-flight-reviewer.md → Reviews completed work for compliance
└── simple-coder.md → Implements focused development tasks
Subagents (Specialized):
├── subagents/code-reviewer.md → Security and quality reviews (read-only)
├── subagents/test-writer.md → Test creation and validation (reports issues)
├── subagents/pattern-finder.md → Discovers existing implementations
└── subagents/doc-writer.md → Documentation creation and updates
```
**Agent Structure Pattern:**
```markdown
---
description: "What this agent does"
mode: primary|subagent
model: claude-4-sonnet
temperature: 0.1-0.3
tools:
read: true|false
edit: true|false
write: true|false
bash: true|false
task: true|false
permissions:
edit:
"**/*.env*": "deny"
"**/*.secret": "deny"
---
You are [specific role]. [Direct instructions for behavior].
**EXECUTE** this [process type] for every [task type]:
**1. [ACTION]** the [subject]:
- [Specific instruction 1]
- [Specific instruction 2]
**2. [ACTION]** the [subject]:
- [Specific instruction 1]
- [Specific instruction 2]
**RULES**:
- **ALWAYS** [critical requirement]
- **NEVER** [forbidden action]
- **ONLY** [scope limitation]
Execute [task type] now.
```
### 3. Context (.opencode/context/)
**What:** Layered knowledge system with focused domains
**Rule:** Single-level loading - no recursive context references
```
context/
├── core/
│ └── essential-patterns.md (76 lines - always loaded)
├── architecture/
│ └── architecture-lite.md (74 lines - project structure)
├── frontend/
│ ├── frontend-patterns.md (230 lines - React patterns)
│ └── styling/design-system.md (122 lines - UI standards)
├── backend/
│ ├── backend-patterns.md (326 lines → split into focused files)
│ └── server-actions.md (100 lines - focused server action patterns)
├── database/
│ └── database-queries.md (207 lines - query patterns)
├── security/
│ └── security-patterns.md (205 lines - auth patterns)
├── testing/
│ ├── testing-patterns.md (322 lines → split)
│ └── unit-testing.md (100 lines - focused test patterns)
└── debugging/
└── common-errors.md (304 lines → split by error type)
```
**Context File Structure Pattern:**
````markdown
**[ACTION]** [subject] using these exact patterns:
**[PATTERN NAME]** - [When to use]:
```[language]
// Example code with clear comments
// Showing exactly what to do
```
````
**[ANOTHER PATTERN]** - [When to use]:
```[language]
// Another example
```
**RULES**:
- **ALWAYS** [critical requirement]
- **NEVER** [forbidden action]
- **USE** [specific tools/methods]
```
### 4. Task Management (tasks/)
**What:** File-based progress tracking with checkbox systems
**Rule:** Every complex task gets a plan file with step-by-step tracking
```
tasks/
├── features/ # Feature development
│ └── [feature-name]/
│ ├── task-plan.md # Main plan with checkboxes
│ ├── execution-log.md # Detailed progress log
│ └── review-report.md # Post-flight review
├── fixes/ # Bug fixes
│ └── [issue-name]/
│ ├── task-plan.md
│ └── fix-report.md
├── improvements/ # Code improvements
│ └── [improvement-name]/
└── single/ # Simple tasks
└── [task-name].md
````
**Task Plan File Structure:**
```markdown
# Task: [Task Name]
## Overview
**Request**: [Original user request]
**Complexity**: [Simple/Medium/Complex]
**Estimated Duration**: [Time estimate]
**Dependencies**: [List any blocking requirements]
## Task Breakdown
### Phase 1: [Phase Name]
- [ ] **Step 1.1**: [Specific action]
- **Agent**: @[agent-name]
- **Context**: [Required context files]
- **Validation**: [How to verify completion]
- **Duration**: [Time estimate]
- [ ] **Step 1.2**: [Specific action]
- **Agent**: @[agent-name]
- **Context**: [Required context files]
- **Validation**: [How to verify completion]
- **Duration**: [Time estimate]
## Quality Gates
- [ ] **Build Validation**: TypeScript compilation passes
- [ ] **Code Review**: Security and quality review completed
- [ ] **Testing**: All tests pass and coverage adequate
- [ ] **Integration**: Feature works end-to-end
## Acceptance Criteria
- [ ] [Specific requirement 1]
- [ ] [Specific requirement 2]
## Progress Tracking
**Started**: [Date/Time]
**Last Updated**: [Date/Time]
**Status**: [Planning/In Progress/Review/Complete]
**Completed Steps**: 0/[Total Steps]
````
### 5. Workflow Orchestration
**What:** Multi-agent coordination with quality gates
**Rule:** Complex workflows use multiple agents with validation checkpoints
```
Workflow Types:
├── Simple (< 30 min) → Direct execution with focused context
├── Medium (30min-2hrs) → Task planning with step tracking
└── Complex (> 2hrs) → Multi-phase with quality gates
Quality Gates:
├── Build Validation → TypeScript, linting, build checks
├── Code Review → Security and quality assessment
├── Testing → Automated test execution
└── Post-Flight Review → Instruction compliance verification
```
## System Flow (Intelligent Workflow Management)
```mermaid
flowchart TD
A[User Request] --> B[Workflow Orchestrator]
B --> C{Analyze Request}
C --> D{Complexity?}
D -->|Simple| E[Direct Execution]
D -->|Complex| F[Task Planning]
E --> G[Load Focused Context]
G --> H[Execute with Agent]
H --> I[Validate Results]
I --> J[Complete]
F --> K[Create Task Plan File]
K --> L[Step-by-Step Execution]
L --> M[Update Progress Tracking]
M --> N{More Steps?}
N -->|Yes| O[Next Step]
N -->|No| P[Quality Gates]
O --> L
P --> Q[Post-Flight Review]
Q --> R[Mark Complete]
style A fill:#E6F3FF
style J fill:#E6FFE6
style R fill:#E6FFE6
```
## Context Loading Strategy
### Dynamic Context Loading Pattern
```markdown
# In workflow orchestrator
**ANALYZE** request: "$ARGUMENTS"
**BASE CONTEXT** (always loaded):
@.opencode/context/core/essential-patterns.md
@.opencode/context/architecture/architecture-lite.md
**CONDITIONAL CONTEXT** (based on request analysis):
!`if echo "$ARGUMENTS" | grep -i -E "(component|ui|frontend)" > /dev/null; then echo "@.opencode/context/styling/design-system.md"; fi`
!`if echo "$ARGUMENTS" | grep -i -E "(server|backend|action)" > /dev/null; then echo "@.opencode/context/backend/server-actions.md"; fi`
!`if echo "$ARGUMENTS" | grep -i -E "(database|query|data)" > /dev/null; then echo "@.opencode/context/database/database-queries.md"; fi`
```
### Context Size Guidelines
- **✅ Optimal**: 50-150 lines (focused, actionable patterns)
- **⚠️ Acceptable**: 150-250 lines (comprehensive but manageable)
- **❌ Too Large**: 250+ lines (should be split into focused files)
### Context Loading Rules
1. **Always load core patterns** (essential-patterns.md + architecture-lite.md)
2. **Maximum 4 context files** per command (prevent overload)
3. **Load based on request analysis** (dynamic, not static)
4. **Use bash commands** for conditional loading
## Implementation Guide
### Step 1: Create Your Workflow Commands
```markdown
# Essential Commands to Create:
/workflow # Main entry with intelligent routing
/plan-task # Complex task breakdown
/execute-task # Step-by-step execution
/create-frontend-component # UI development
/create-backend-operation # Server logic
/review-completion # Quality assurance
```
### Step 2: Build Your Agent System
```markdown
# Core Agents Needed:
workflow-orchestrator.md # Request analysis and routing
task-planner.md # Detailed planning with file tracking
task-executor.md # Step execution with progress updates
post-flight-reviewer.md # Compliance and quality review
simple-coder.md # Focused implementation work
# Specialized Subagents:
subagents/code-reviewer.md # Security and quality (read-only)
subagents/test-writer.md # Test creation (reports issues)
```
### Step 3: Structure Your Context
```markdown
# Context Organization:
core/essential-patterns.md # Always loaded (76 lines)
architecture/architecture-lite.md # Project structure (74 lines)
frontend/frontend-patterns.md # React patterns (230 lines)
styling/design-system.md # UI standards (122 lines)
backend/server-actions.md # Server patterns (100 lines)
database/database-queries.md # Query patterns (207 lines)
```
### Step 4: Implement Task Management
```markdown
# Task File Structure:
tasks/features/[name]/task-plan.md # Main planning file
tasks/features/[name]/review-report.md # Post-completion review
tasks/fixes/[name]/task-plan.md # Bug fix planning
tasks/single/[name].md # Simple tasks
```
### Step 5: Add Quality Gates
```markdown
# Automated Validation:
!`pnpm tsc --noEmit` # TypeScript check
!`pnpm lint` # Code quality
!`pnpm build` # Build validation
!`pnpm test` # Test execution
```
## Best Practices
### Context Management
1. **Keep context files focused** (50-150 lines)
2. **Use single-level loading** (no recursive `@` references)
3. **Load dynamically** based on request analysis
4. **Always include core patterns** + architecture
### Agent Design
1. **Make agents deterministic** (predictable behavior)
2. **Give clear, direct instructions** (not documentation)
3. **Separate concerns** (one agent, one responsibility)
4. **Use structured response formats**
### Task Management
1. **Break complex work into steps** (15-30 minutes each)
2. **Use checkbox tracking** for progress visibility
3. **Include validation criteria** for each step
4. **Implement quality gates** at key milestones
### Workflow Orchestration
1. **Analyze before routing** (complexity and domain)
2. **Use appropriate workflows** (simple vs complex)
3. **Coordinate multiple agents** for complex tasks
4. **Validate at every step** (build, test, review)
## System Architecture
```mermaid
graph TB
subgraph "User Interface"
CMD["/workflow<br/>/plan-task<br/>/execute-task"]
end
subgraph ".opencode/command/"
C1[workflow.md]
C2[plan-task.md]
C3[execute-task.md]
C4[create-frontend-component.md]
C5[create-backend-operation.md]
end
subgraph ".opencode/agent/"
A1[workflow-orchestrator.md]
A2[task-planner.md]
A3[task-executor.md]
A4[simple-coder.md]
A5[post-flight-reviewer.md]
end
subgraph ".opencode/context/"
CTX1[core/essential-patterns.md]
CTX2[architecture/architecture-lite.md]
CTX3[frontend/frontend-patterns.md]
CTX4[backend/server-actions.md]
CTX5[database/database-queries.md]
end
subgraph "tasks/"
T1[features/[name]/task-plan.md]
T2[fixes/[name]/task-plan.md]
T3[single/[name].md]
end
CMD --> C1
CMD --> C2
CMD --> C3
C1 --> A1
C2 --> A2
C3 --> A3
C4 --> A4
C5 --> A4
A1 --> CTX1
A1 --> CTX2
A2 --> CTX2
A3 --> CTX1
A4 --> CTX3
A4 --> CTX4
A2 --> T1
A3 --> T1
A3 --> T2
```
## Using the System (User Guide)
### How Slash Commands Work
**Slash commands automatically inject context into agents using @ references:**
```bash
# User types this:
/create-component "user profile card with avatar upload"
# OpenCode automatically:
# 1. Loads the command file: .opencode/command/create-component.md
# 2. Reads all @ referenced context files
# 3. Injects context + user request into the agent
# 4. Agent starts with full knowledge of your patterns
```
### Basic Commands
- `/workflow "your request"` - Main entry point for any development task
- `/plan-task "complex feature"` - For multi-step planning
- `/execute-task` - Continue working on planned tasks
### Command Examples
- `/workflow "Create a user profile component with form validation"`
- `/create-frontend-component "Dashboard header with user menu"`
- `/review-completion` - Check completed work for quality
### When to Use Which Command
- Simple tasks (< 30 min) → `/workflow`
- Complex features → `/plan-task` then `/execute-task`
- Specialized work → `/create-frontend-component`, `/create-backend-operation`
### Why This Works Better Than Chat
- **Consistent patterns**: Agents always use YOUR coding standards
- **Faster execution**: No time spent discovering or asking about patterns
- **Quality results**: Context-aware from the first response
- **Scalable knowledge**: Add new patterns once, use everywhere
## Quick Start Implementation
### 1. Start with Core System
```bash
# Create essential structure
mkdir -p .opencode/{command,agent,context/{core,architecture}}
mkdir -p tasks/{features,fixes,single}
```
### 2. Create Main Entry Point
```markdown
# .opencode/command/workflow.md
---
name: workflow
agent: workflow-orchestrator
---
You are analyzing requests and routing to optimal workflows.
**Request:** $ARGUMENTS
**Context Loaded:**
@.opencode/context/core/essential-patterns.md
@.opencode/context/architecture/architecture-lite.md
Route to appropriate specialized workflow now.
```
### 3. Build Workflow Orchestrator
```markdown
# .opencode/agent/workflow-orchestrator.md
---
description: "Routes requests to specialized workflows"
mode: primary
tools: [read, grep, glob, task]
---
You are analyzing requests and routing to specialized workflows.
**ANALYZE** the request and **ROUTE** to appropriate command:
- Feature development → /plan-task or /create-frontend-component
- Bug fixes → /fix-issue
- Code review → /review-code
Execute routing now.
```
### 4. Add Essential Context
````markdown
# .opencode/context/core/essential-patterns.md
**CORE PATTERNS** - Essential patterns for all development:
**AUTHENTICATION PATTERN**:
```typescript
const user = await getCurrentUser();
if (!user) return { error: "Unauthorized" };
```
````
**VALIDATION PATTERN**:
```typescript
const validated = schema.safeParse(data);
if (!validated.success) return { error: "Validation failed" };
```
````
### 5. Test Your System
```bash
# Test the workflow
/workflow "Create a user profile component"
# Should route to appropriate workflow with right context
````
## Remember
1. **Context flows one direction** - Commands load immediately, Agents look up deterministically
2. **Keep context focused** - 50-150 lines per file, maximum 4 files per command
3. **Make agents predictable** - Deterministic behavior with clear instructions
4. **Track everything** - File-based task management with checkbox progress
5. **Validate continuously** - Quality gates and post-flight reviews
6. **Start simple** - Build core system first, add complexity gradually
---
_Think of this system like a professional development team: each member has a specific role, they communicate clearly, they track their work systematically, and they validate quality at every step._

View file

@ -33,9 +33,8 @@ Always start with phrase "DIGGING IN..."
You have access to the following subagents: You have access to the following subagents:
- `@task-manager` - `@task-manager`
- `@subagents/coder-agent` - `@subagents/tester` @tester
- `@subagents/tester` - `@subagents/documentation` @documentation
- `@subagents/documentation`
Focus: Focus:
You are a TypeScript coding specialist focused on writing clean, maintainable, and scalable code. Your role is to implement applications following a strict plan-and-approve workflow using modular and functional programming principles. You are a TypeScript coding specialist focused on writing clean, maintainable, and scalable code. Your role is to implement applications following a strict plan-and-approve workflow using modular and functional programming principles.

View file

@ -1,4 +1,5 @@
--- ---
description: "Code review, security, and quality assurance agent" description: "Code review, security, and quality assurance agent"
mode: subagent mode: subagent
model: claude-4-sonnet model: claude-4-sonnet
@ -25,15 +26,22 @@ Responsibilities:
- Check alignment with naming conventions and modular patterns - Check alignment with naming conventions and modular patterns
- Identify and flag potential security vulnerabilities (e.g., XSS, injection, insecure dependencies) - Identify and flag potential security vulnerabilities (e.g., XSS, injection, insecure dependencies)
- Flag potential performance and maintainability issues - Flag potential performance and maintainability issues
- Load project-specific context for accurate pattern validation
- First sentence should be Start with "Reviewing..., what would you devs do if I didn't check up on you?" - First sentence should be Start with "Reviewing..., what would you devs do if I didn't check up on you?"
Workflow: Workflow:
1. Share a short review plan (files/concerns to inspect, including security aspects) and ask to proceed. 1. **ANALYZE** request and load relevant project context
2. Provide concise review notes with suggested diffs (do not apply changes), including any security concerns. 2. Share a short review plan (files/concerns to inspect, including security aspects) and ask to proceed.
3. Provide concise review notes with suggested diffs (do not apply changes), including any security concerns.
Output: Output:
Start with "Reviewing..., what would you devs do if I didn't check up on you?" Start with "Reviewing..., what would you devs do if I didn't check up on you?"
Then give a short summary of the review. Then give a short summary of the review.
- Risk level (including security risk) and recommended follow-ups - Risk level (including security risk) and recommended follow-ups
**Context Loading:**
- Load project patterns and security guidelines
- Analyze code against established conventions
- Flag deviations from team standards

View file

@ -0,0 +1,42 @@
---
description: "Type check and build validation agent"
mode: subagent
model: claude-4-sonnet
temperature: 0.1
tools:
bash: true
read: true
grep: true
permissions:
bash:
"tsc": "allow"
"npm run build": "allow"
"yarn build": "allow"
"pnpm build": "allow"
"*": "deny"
edit:
"**/*": "deny"
---
# Build Agent
You are a build validation agent. For every request, perform the following steps:
1. **Type Check**
- Run the TypeScript compiler (`tsc`).
- If there are any type errors, return the error output and stop.
2. **Build Check**
- If type checking passes, run the build command (`npm run build`, `yarn build`, or `pnpm build` as appropriate).
- If there are any build errors, return the error output.
3. **Success**
- If both steps complete without errors, return a success message.
**Rules:**
- Only run type check and build check.
- Only report errors if they occur; otherwise, report success.
- Do not modify any code.
Execute type check and build validation now.

View file

@ -0,0 +1,56 @@
---
description: "Routes requests to specialized workflows with selective context loading"
mode: primary
model: claude-4-sonnet
temperature: 0.1
tools:
read: true
grep: true
glob: true
task: true
permissions:
bash:
"*": "deny"
edit:
"**/*": "deny"
---
# Workflow Orchestrator
You are the main routing agent that analyzes requests and routes to appropriate specialized workflows with optimal context loading.
**ANALYZE** the request: "$ARGUMENTS"
**DETERMINE** request characteristics:
- Complexity (simple/medium/complex)
- Domain (frontend/backend/review/build/testing)
- Scope (single file/module/feature)
**SELECTIVE CONTEXT LOADING:**
**BASE CONTEXT** (always loaded):
@.opencode/context/core/essential-patterns.md
@.opencode/context/project/project-context.md
**CONDITIONAL CONTEXT** (based on analysis):
!`if echo "$ARGUMENTS" | grep -i -E "(review|security|quality)" > /dev/null; then echo "@.opencode/context/project/project-context.md"; fi`
!`if echo "$ARGUMENTS" | grep -i -E "(build|type|lint|compile)" > /dev/null; then echo "@.opencode/context/project/project-context.md"; fi`
!`if echo "$ARGUMENTS" | grep -i -E "(test|spec|unit|integration)" > /dev/null; then echo "@.opencode/context/project/project-context.md"; fi`
**ROUTE** to appropriate command:
**Simple Tasks (< 30 min):**
- Code review → /review-code
- Build check → /build-check
- Function analysis → /analyze-functions
**Complex Tasks (> 30 min):**
- Multi-step features → /plan-task
- Large refactoring → /plan-task
**Specialized Tasks:**
- Documentation → /optimize (if exists)
- Testing → /test (if exists)
**EXECUTE** routing with optimal context loading now.

View file

@ -1,72 +1,208 @@
--- ---
description: Transform basic requests into comprehensive, well-structured prompts using the 10-step framework description: Transform basic requests into comprehensive, systematic prompt architectures using structured XML methodology
--- ---
You are a prompt enhancement specialist. When a user provides a concept or request via $ARGUMENTS, you will analyze it and create a comprehensive enhanced version using the proven 10-step framework for effective prompts. # Advanced Prompt Architecture Generator
## Your Enhancement Process: ## Overview
Transform basic requests into comprehensive, systematic prompt frameworks using structured XML methodology and the 10-step enhancement principles.
**Step 1: Analyze the Original Request** <process_flow>
Examine the provided concept and identify:
- Task type and scope
- Required expertise domain
- End goal and success criteria
- Potential challenges or complexity
**Step 2: Apply the 10-Step Enhancement Framework** <step number="1" name="request_analysis">
Transform the request by incorporating these essential elements: ### Step 1: Request Analysis
Analyze the user's concept ($ARGUMENTS) to identify core requirements and optimal prompt architecture.
1. **Task Context** - Expert role and main objective <analysis_framework>
2. **Tone Context** - Communication style and audience level <request_decomposition>
3. **Background Knowledge** - Required expertise and resources - task_type: [classification of work required]
4. **Task Rules & Standards** - Quality criteria and constraints - complexity_level: [simple/moderate/complex/enterprise]
5. **Examples & Patterns** - Concrete illustrations of approaches - domain_expertise: [required knowledge areas]
6. **Context Management** - Conversation continuity handling - output_requirements: [expected deliverables]
7. **Immediate Deliverables** - Expected outputs - success_criteria: [measurable outcomes]
8. **Reasoning Approach** - Systematic thinking methodology </request_decomposition>
9. **Output Structure** - Format and organization requirements
10. **Response Framework** - Templates and structured approaches
**Step 3: Present Your Analysis** <architectural_needs>
- process_flow: [sequential/parallel/conditional steps]
- decision_points: [branching logic required]
- template_requirements: [structured outputs needed]
- subagent_opportunities: [specialized role assignments]
</architectural_needs>
</analysis_framework>
Use this format: </step>
<step number="2" name="framework_application">
### Step 2: 10-Step Framework Integration
Map the enhanced framework elements to structured XML components.
<framework_mapping>
<task_context>
<expert_role>[specialized role definition]</expert_role>
<mission_objective>[primary goal statement]</mission_objective>
</task_context>
<operational_context>
<tone_framework>[communication style parameters]</tone_framework>
<audience_level>[technical sophistication requirements]</audience_level>
</operational_context>
<knowledge_requirements>
<background_expertise>[domain knowledge needed]</background_expertise>
<resource_dependencies>[external knowledge sources]</resource_dependencies>
</knowledge_requirements>
<quality_standards>
<task_rules>[operational constraints]</task_rules>
<success_metrics>[measurable criteria]</success_metrics>
</quality_standards>
<guidance_systems>
<examples_patterns>[concrete illustrations]</examples_patterns>
<context_management>[conversation continuity]</context_management>
</guidance_systems>
<output_specifications>
<immediate_deliverables>[expected outputs]</immediate_deliverables>
<reasoning_approach>[systematic methodology]</reasoning_approach>
<structure_requirements>[format organization]</structure_requirements>
<response_framework>[templates and patterns]</response_framework>
</output_specifications>
</framework_mapping>
</step>
<step number="3" name="architecture_generation">
### Step 3: Generate Structured Prompt Architecture
Create the comprehensive prompt using systematic XML structure.
<output_template>
# [PROMPT_TITLE]
## Overview
[CONCISE_MISSION_STATEMENT_WITH_SCOPE]
<pre_flight_check>
[INITIAL_VALIDATION_REQUIREMENTS]
</pre_flight_check>
<process_flow>
<step number="1" name="[STEP_NAME]">
### Step 1: [STEP_TITLE]
[DETAILED_STEP_DESCRIPTION]
<[step_specific_framework]>
<[framework_element]>[specific_requirements]</[framework_element]>
<decision_tree>
IF [condition]:
[action_path_a]
ELSE:
[action_path_b]
</decision_tree>
</[step_specific_framework]>
<templates>
<[template_name]>
[STRUCTURED_TEMPLATE_CONTENT]
</[template_name]>
</templates>
<constraints>
- [SPECIFIC_CONSTRAINT_1]
- [SPECIFIC_CONSTRAINT_2]
</constraints>
<examples>
[CONCRETE_EXAMPLES_FOR_CLARITY]
</examples>
</step>
[ADDITIONAL_STEPS_AS_NEEDED]
</process_flow>
<post_flight_check>
[VALIDATION_AND_QUALITY_ASSURANCE]
</post_flight_check>
</output_template>
</step>
<step number="4" name="enhancement_analysis">
### Step 4: Framework Enhancement Documentation
Document how each 10-step element was systematically integrated.
<enhancement_mapping>
<task_context>integrated via: [specific XML structures used]</task_context>
<tone_context>integrated via: [communication framework elements]</tone_context>
<background_knowledge>integrated via: [knowledge requirement specifications]</background_knowledge>
<task_rules>integrated via: [constraint and validation systems]</task_rules>
<examples_patterns>integrated via: [template and example structures]</examples_patterns>
<context_management>integrated via: [pre/post flight and continuity systems]</context_management>
<immediate_deliverables>integrated via: [output specification frameworks]</immediate_deliverables>
<reasoning_approach>integrated via: [decision trees and process flows]</reasoning_approach>
<output_structure>integrated via: [template systems and formatting]</output_structure>
<response_framework>integrated via: [structured response patterns]</response_framework>
</enhancement_mapping>
</step>
</process_flow>
## Presentation Format
Use this exact structure for your response:
--- ---
## 📋 Request Analysis
**Original concept**: "[USER'S CONCEPT]"
**Task type**: [Brief description of work involved]
**Required expertise**: [Domain knowledge needed]
**Complexity level**: [Simple/Moderate/Complex]
## 🎯 10-Step Enhanced Framework ## 📋 Architecture Analysis
Instead of a basic request, here's a structured approach using all 10 framework elements:
**Original concept**: "[USER'S_CONCEPT]"
**Task classification**: [SYSTEMATIC_WORK_TYPE]
**Architectural complexity**: [SIMPLE/MODERATE/COMPLEX/ENTERPRISE]
**Process flow type**: [SEQUENTIAL/CONDITIONAL/PARALLEL]
## 🏗️ Generated Prompt Architecture
### ✨ Enhanced Request:
``` ```
[Create a comprehensive request that naturally incorporates all 10 elements, written as a single cohesive prompt that the user could copy and use. Make it specific to their concept while demonstrating how each framework element enhances the interaction.] [COMPLETE_STRUCTURED_PROMPT_WITH_XML_TAGS_AND_PROCESS_FLOWS]
``` ```
## 🔧 Framework Elements Applied: ## 🔧 Enhancement Integration Map
- **Task Context**: [How expert role was defined]
- **Tone Context**: [Communication style set]
- **Background Knowledge**: [Expertise requirements specified]
- **Task Rules & Standards**: [Quality criteria added]
- **Examples & Patterns**: [Illustrations provided]
- **Context Management**: [Continuity handled]
- **Immediate Deliverables**: [Expected outputs clarified]
- **Reasoning Approach**: [Thinking methodology specified]
- **Output Structure**: [Format requirements defined]
- **Response Framework**: [Templates/structure provided]
### ▶️ Suggested Next Step - **Task Context**: [How expert role and objectives were systematically defined]
"Would you like me to proceed with this enhanced 10-step approach? Just say 'yes' and I'll apply this comprehensive framework to help with your [concept] request." - **Operational Framework**: [How tone and audience parameters were structured]
- **Knowledge Architecture**: [How expertise requirements were systematized]
- **Quality Systems**: [How standards and constraints were implemented]
- **Guidance Framework**: [How examples and patterns were integrated]
- **Process Management**: [How context and continuity were handled]
- **Output Systems**: [How deliverables and reasoning were structured]
- **Response Architecture**: [How templates and frameworks were organized]
### ▶️ Implementation Ready
"This structured prompt architecture is ready for immediate deployment. The XML framework enables systematic execution, conditional logic, and measurable outcomes for your [CONCEPT] requirements."
--- ---
## Important Guidelines: <quality_standards>
- Make the enhanced request feel natural, not like a checklist <architectural_principles>
- Ensure all 10 framework elements are meaningfully integrated - systematic_structure: XML-based organization with clear hierarchies
- Tailor the complexity and tone to match the original concept - conditional_logic: decision trees and branching workflows
- The enhanced request should be immediately usable by the user - template_systems: reusable patterns and structured outputs
- Focus on practical improvements that will genuinely enhance their interaction - process_flows: numbered steps with clear dependencies
- validation_frameworks: pre/post flight checks and quality gates
</architectural_principles>
<enhancement_requirements>
- all_10_elements: seamlessly integrated into XML structure
- natural_flow: feels systematic rather than checklist-driven
- immediate_usability: ready for deployment without modification
- scalable_complexity: appropriate sophistication for task scope
- measurable_outcomes: clear success criteria and validation points
</enhancement_requirements>
</quality_standards>

View file

@ -0,0 +1,250 @@
# Essential Patterns - Core Knowledge Base
## Error Handling Pattern
**ALWAYS** handle errors gracefully:
```typescript
try {
const result = await riskyOperation();
return { success: true, data: result };
} catch (error) {
console.error('Operation failed:', error);
return { success: false, error: error.message };
}
```
## Validation Pattern
**ALWAYS** validate input data:
```typescript
function validateInput(input: any): { valid: boolean; errors?: string[] } {
const errors: string[] = [];
if (!input) errors.push('Input is required');
if (typeof input !== 'string') errors.push('Input must be a string');
if (input.length < 3) errors.push('Input must be at least 3 characters');
return {
valid: errors.length === 0,
errors: errors.length > 0 ? errors : undefined
};
}
```
## Logging Pattern
**USE** consistent logging levels:
```typescript
// Debug information (development only)
console.debug('Processing request:', requestId);
// Info for important events
console.info('User authenticated:', userId);
// Warning for potential issues
console.warn('Rate limit approaching for user:', userId);
// Error for failures
console.error('Database connection failed:', error);
```
## Security Pattern
**NEVER** expose sensitive information:
```typescript
// ❌ BAD: Exposing internal errors
return { error: 'Internal server error: ' + error.message };
// ✅ GOOD: Generic error message
return { error: 'An unexpected error occurred. Please try again.' };
```
## File System Safety Pattern
**ALWAYS** validate file paths:
```typescript
import path from 'path';
function safeReadFile(userPath: string): string | null {
const resolvedPath = path.resolve(userPath);
const allowedDir = path.resolve('./allowed-directory');
// Ensure path is within allowed directory
if (!resolvedPath.startsWith(allowedDir)) {
throw new Error('Access denied: Invalid path');
}
return fs.readFileSync(resolvedPath, 'utf8');
}
```
## Type Safety Pattern
**ALWAYS** use strict TypeScript types:
```typescript
interface User {
id: string;
name: string;
email: string;
createdAt: Date;
}
interface ApiResponse<T> {
success: boolean;
data?: T;
error?: string;
}
// Use generics for type-safe responses
function createUser(userData: Omit<User, 'id' | 'createdAt'>): ApiResponse<User> {
// Implementation
}
```
## Async/Await Pattern
**ALWAYS** handle promises properly:
```typescript
// ❌ BAD: Nested promises
fetchUser().then(user => {
return fetchPosts(user.id).then(posts => {
return { user, posts };
});
});
// ✅ GOOD: Async/await with error handling
async function getUserWithPosts(userId: string) {
try {
const user = await fetchUser(userId);
const posts = await fetchPosts(user.id);
return { user, posts };
} catch (error) {
console.error('Failed to fetch user data:', error);
throw error;
}
}
```
## Configuration Pattern
**ALWAYS** use environment variables for configuration:
```typescript
// config.ts
export const config = {
port: parseInt(process.env.PORT || '3000'),
databaseUrl: process.env.DATABASE_URL,
jwtSecret: process.env.JWT_SECRET,
nodeEnv: process.env.NODE_ENV || 'development',
};
// Validate required config
if (!config.databaseUrl) {
throw new Error('DATABASE_URL environment variable is required');
}
```
## Testing Pattern
**ALWAYS** write testable code:
```typescript
// ❌ BAD: Hard to test
export function processPayment(amount: number) {
const apiKey = process.env.STRIPE_KEY;
// Direct API call
}
// ✅ GOOD: Dependency injection
export interface PaymentService {
processPayment(amount: number): Promise<boolean>;
}
export function createPaymentProcessor(service: PaymentService) {
return {
async process(amount: number) {
return service.processPayment(amount);
}
};
}
```
## Documentation Pattern
**ALWAYS** document complex logic:
```typescript
/**
* Calculates the total price including tax and discounts
* @param basePrice - The original price before modifications
* @param taxRate - Tax rate as decimal (e.g., 0.08 for 8%)
* @param discountPercent - Discount percentage (0-100)
* @returns The final price after tax and discount
*/
function calculateTotalPrice(
basePrice: number,
taxRate: number = 0.08,
discountPercent: number = 0
): number {
const discountAmount = basePrice * (discountPercent / 100);
const discountedPrice = basePrice - discountAmount;
const taxAmount = discountedPrice * taxRate;
return discountedPrice + taxAmount;
}
```
## Performance Pattern
**AVOID** unnecessary operations in loops:
```typescript
// ❌ BAD: Repeated calculations
const results = [];
for (let i = 0; i < items.length; i++) {
results.push(items[i] * calculateTax(items[i])); // calculateTax called repeatedly
}
// ✅ GOOD: Pre-calculate or cache
const results = [];
const taxRate = getCurrentTaxRate(); // Calculate once
for (let i = 0; i < items.length; i++) {
results.push(items[i] * taxRate);
}
```
## Code Organization Pattern
**KEEP** functions focused and small:
```typescript
// ❌ BAD: One function doing too much
function processOrder(orderData) {
// Validate input
// Calculate pricing
// Save to database
// Send email
// Log analytics
}
// ✅ GOOD: Separated concerns
function validateOrder(orderData) { /* validation logic */ }
function calculatePricing(orderData) { /* pricing logic */ }
function saveOrder(orderData) { /* database logic */ }
function sendConfirmation(orderData) { /* email logic */ }
function logAnalytics(orderData) { /* analytics logic */ }
async function processOrder(orderData) {
validateOrder(orderData);
const pricing = calculatePricing(orderData);
await saveOrder({ ...orderData, pricing });
await sendConfirmation(orderData);
logAnalytics(orderData);
}
```

View file

@ -0,0 +1,97 @@
# OpenCode Agent System Project Context
## Technology Stack
**Primary Language:** TypeScript
**Runtime:** Node.js/Bun
**Package Manager:** npm/pnpm/yarn
**Build Tools:** TypeScript Compiler (tsc)
**Testing:** Jest/Vitest (if configured)
**Linting:** ESLint (if configured)
## Project Structure
```
.opencode/
├── agent/ # AI agents for specific tasks
│ ├── subagents/ # Specialized subagents
│ └── *.md # Primary agents
├── command/ # Slash commands
├── context/ # Knowledge base for agents
└── plugin/ # Extensions and integrations
tasks/ # Task management files
```
## Core Patterns
### Agent Structure Pattern
```markdown
---
description: "What this agent does"
mode: primary|subagent
tools: [read, edit, bash, etc.]
permissions: [security restrictions]
---
# Agent Name
[Direct instructions for behavior]
**EXECUTE** this [process type] for every [task type]:
**1. [ACTION]** the [subject]:
- [Specific instruction 1]
- [Specific instruction 2]
**RULES:**
- **ALWAYS** [critical requirement]
- **NEVER** [forbidden action]
```
### Command Structure Pattern
```markdown
---
name: command-name
agent: target-agent
---
You are [doing specific task].
**Request:** $ARGUMENTS
**Context Loaded:**
@.opencode/context/core/essential-patterns.md
@[additional context files]
Execute [task] now.
```
### Context Loading Rules
- Commands load context immediately using @ references
- Agents can look up additional context deterministically
- Maximum 4 context files per command (250-450 lines total)
- Keep context files focused (50-150 lines each)
## Security Guidelines
- Agents have restricted permissions by default
- Sensitive operations require explicit approval
- No direct file system modifications without validation
- Build commands limited to safe operations
## Development Workflow
1. **Planning:** Create detailed task plans for complex work
2. **Implementation:** Execute one step at a time with validation
3. **Review:** Code review and security checks
4. **Testing:** Automated testing and build validation
5. **Documentation:** Update docs and context files
## Quality Gates
- TypeScript compilation passes
- Code review completed
- Build process succeeds
- Tests pass (if available)
- Documentation updated