chore: install openagent opencode

Signed-off-by: Dmytro Stanchiev <git@dmytros.dev>
This commit is contained in:
2026-04-07 11:31:26 -04:00
parent b4c03ff25e
commit c2263602c4
204 changed files with 38010 additions and 0 deletions

View File

@@ -0,0 +1,136 @@
<!-- Context: workflows/review | Priority: high | Version: 2.0 | Updated: 2025-01-21 -->
# Code Review Guidelines
## Quick Reference
**Golden Rule**: Review code as you'd want yours reviewed - thoroughly but kindly
**Checklist**: Functionality, Code Quality, Security, Testing, Performance, Maintainability
**Report Format**: Summary, Assessment, Issues (🔴🟡🔵), Positive Observations, Recommendations
**Principles**: Constructive, Thorough, Timely
---
## Principles
**Constructive**: Focus on code not person, explain WHY, suggest improvements, acknowledge good practices
**Thorough**: Check functionality not just style, consider edge cases, think maintainability, look for security
**Timely**: Review promptly, don't block unnecessarily, prioritize critical issues
## Review Checklist
### Functionality
- [ ] Does what it's supposed to do
- [ ] Edge cases handled
- [ ] Error cases handled
- [ ] No obvious bugs
### Code Quality
- [ ] Clear, descriptive naming
- [ ] Functions small and focused
- [ ] No unnecessary complexity
- [ ] Follows coding standards
- [ ] DRY - no duplication
### Security
- [ ] Input validation present
- [ ] No SQL injection vulnerabilities
- [ ] No XSS vulnerabilities
- [ ] No hardcoded secrets
- [ ] Sensitive data handled properly
- [ ] Auth/authorization appropriate
### Testing
- [ ] Tests present
- [ ] Happy path covered
- [ ] Edge cases covered
- [ ] Error cases covered
- [ ] All tests pass
### Performance
- [ ] No obvious performance issues
- [ ] Efficient algorithms
- [ ] No unnecessary operations
- [ ] Resources properly managed
### Maintainability
- [ ] Easy to understand
- [ ] Complex logic documented
- [ ] Follows project conventions
- [ ] Easy to modify/extend
## Review Report Format
```markdown
## Code Review: {Feature/PR Name}
**Summary:** {Brief overview}
**Assessment:** Approve / Needs Work / Requires Changes
---
### Issues Found
#### 🔴 Critical (Must Fix)
- **File:** `src/auth.js:42`
**Issue:** Password stored in plain text
**Fix:** Hash password before storing
#### 🟡 Warnings (Should Fix)
- **File:** `src/user.js:15`
**Issue:** No input validation
**Fix:** Validate email format
#### 🔵 Suggestions (Nice to Have)
- **File:** `src/utils.js:28`
**Issue:** Could be more concise
**Fix:** Use array methods instead of loop
---
### Positive Observations
- ✅ Good test coverage (95%)
- ✅ Clear function names
- ✅ Proper error handling
---
### Recommendations
{Next steps, improvements, follow-up items}
```
## Common Issues
### Security
🔴 Hardcoded credentials
🔴 SQL injection vulnerabilities
🔴 Missing input validation
🔴 Exposed sensitive data
### Code Quality
🟡 Large functions (>50 lines)
🟡 Deep nesting (>3 levels)
🟡 Code duplication
🟡 Unclear naming
### Testing
🟡 Missing tests
🟡 Low coverage (<80%)
🟡 Flaky tests
🟡 Tests testing implementation
## Best Practices
Review within 24 hours
Provide specific, actionable feedback
Explain WHY, not just WHAT
Suggest alternatives
Acknowledge good work
Use severity levels (Critical/Warning/Suggestion)
Test the code if possible
Check for security issues first
**Golden Rule**: Review code as you'd want yours reviewed - thoroughly but kindly.

View File

@@ -0,0 +1,96 @@
<!-- Context: workflows/component-planning | Priority: high | Version: 1.0 -->
# Component-Based Planning Workflow
## Overview
This workflow replaces "Monolithic Planning" (planning everything at once) with "Iterative Component Planning". It is designed for complex features that require breaking down into functional units.
## Core Philosophy
**"Plan the System, Build the Component."**
Don't try to write a detailed plan for the entire system upfront. Create a high-level roadmap, then zoom in to plan one component in detail before executing it.
## The Two-Level Plan Structure
### Level 1: The Master Plan (Roadmap)
**File:** `.tmp/sessions/{id}/master-plan.md`
**Purpose:** High-level architecture and dependency graph.
**Content:**
- System Architecture Diagram (ASCII)
- List of Components (e.g., Auth, Database, API, UI)
- Dependency Order (What must be built first?)
- Global Standards/Decisions
### Level 2: The Component Plan (Active Spec)
**File:** `.tmp/sessions/{id}/component-{name}.md`
**Purpose:** Detailed execution steps for the *current* focus.
**Content:**
- **Interface Definition**: Types, function signatures, API contracts.
- **Test Strategy**: What specific cases will be tested?
- **Task List**: Atomic steps (Create file, Write test, Implement logic).
- **Verification**: How do we know this component is done?
---
## Workflow Steps
### Phase 1: System Design (The Master Plan)
1. **Analyze**: Understand the full feature request.
2. **Decompose**: Break the system into functional Components (e.g., "User Service", "Email Worker", "Frontend Form").
3. **Draft Master Plan**: Create `master-plan.md`.
4. **Approve**: Get user buy-in on the architecture and order.
### Phase 2: Component Execution Loop
*Repeat this for each component in the Master Plan:*
1. **Select Component**: Pick the next unblocked component.
2. **Draft Component Plan**: Create `component-{name}.md`.
* Define the *exact* interface/types first.
* List the atomic implementation steps.
3. **Approve**: Show the detailed component plan to the user.
4. **Execute**:
* Load `component-{name}.md` into `TodoWrite`.
* Implement -> Validate -> Check off.
5. **Integrate**: Update `master-plan.md` to mark component as complete.
---
## When to Use This
- **Complex Features**: >3 files, multiple layers (DB + API + UI).
- **Unknowns**: When later parts of the system depend on earlier decisions.
- **Large Scope**: Anything taking >2 hours.
## Example Master Plan (`master-plan.md`)
```markdown
# Master Plan: E-Commerce Checkout
## Architecture
[Cart] -> [Order Service] -> [Payment Gateway]
-> [Inventory Service]
## Component Order
1. [ ] **Inventory Service** (Check stock)
2. [ ] **Order Service** (Create order record)
3. [ ] **Payment Integration** (Stripe)
4. [ ] **Checkout UI** (React components)
```
## Example Component Plan (`component-inventory.md`)
```markdown
# Component: Inventory Service
## Interface
```typescript
interface InventoryManager {
checkStock(sku: string): Promise<boolean>;
reserve(sku: string, quantity: number): Promise<void>;
}
```
## Tasks
- [ ] Define `InventoryManager` interface in `src/types.ts`
- [ ] Create mock implementation for tests
- [ ] Implement `checkStock` logic with DB query
- [ ] Add unit tests for race conditions
```

View File

@@ -0,0 +1,20 @@
<!-- Context: workflows/delegation | Priority: high | Version: 2.0 | Updated: 2025-01-21 -->
# Delegation Context Template
> **Note**: This is a reference file. Start with [`task-delegation-basics.md`](./task-delegation-basics.md).
## Quick Reference
**Process**: Create context → Populate → Delegate → Cleanup
**Location**: `.tmp/sessions/{timestamp}-{task-slug}/context.md`
**Template Sections**: Request, Requirements, Decisions, Files, Static Context, Constraints, Progress, Instructions
---
For the full delegation workflow, use:
- [task-delegation-basics.md](./task-delegation-basics.md)
- [task-delegation-specialists.md](./task-delegation-specialists.md)
- [task-delegation-caching.md](./task-delegation-caching.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 Basics](../../ui/web/animation-basics.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 Basics](../../ui/web/animation-basics.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)

View File

@@ -0,0 +1,461 @@
<!-- Context: workflows/external-context-integration | Priority: high | Version: 1.0 | Updated: 2026-01-28 -->
# External Context Integration Guide
## Overview
This guide explains how to integrate external context (fetched via ExternalScout) into the main agent workflow so that subagents can access it without re-fetching.
**Key Principle**: Main agents fetch external docs once → persist to disk → reference in session → subagents read (no re-fetching)
---
## When to Use External Context
Use ExternalScout to fetch external context when:
1. **User asks about external libraries** (Drizzle, Better Auth, Next.js, etc.)
2. **Task involves integration** between multiple external libraries
3. **Setup or configuration** of external tools is needed
4. **API patterns or best practices** from external libraries are relevant
**Don't use** when:
- Question is about internal project code
- Answer is in `.opencode/context/` (use ContextScout instead)
- User is asking for general programming concepts
---
## Integration Workflow
### Stage 1: Analyze & Discover (Before Approval)
```
Main Agent (OpenAgent, etc.)
1. Analyze user request
2. Identify external libraries mentioned
3. Call ContextScout for internal context
4. Call ExternalScout for external docs
- ExternalScout fetches from Context7 API
- ExternalScout persists to .tmp/external-context/
- ExternalScout returns file paths
5. Capture returned file paths
6. Do NOT write anything to disk yet
```
### Stage 2: Propose Plan (Before Approval)
```
Main Agent
1. Show user lightweight summary:
- What will be done
- Which external libraries involved
- Which context files will be used
2. Include discovered external context files in proposal
3. Wait for user approval
```
### Stage 3: Approve (User Gate)
```
User
Approves plan (or redirects)
```
### Stage 4: Init Session (After Approval)
```
Main Agent
1. Create .tmp/sessions/{session-id}/context.md
2. Populate sections:
- ## Context Files (from ContextScout)
- ## Reference Files (project files)
- ## External Context Fetched (from ExternalScout)
- ## Components
- ## Constraints
- ## Exit Criteria
3. CRITICAL: Add "## External Context Fetched" section with:
- File paths returned by ExternalScout
- Brief description of each file
- Note that files are read-only
```
### Stage 5: Delegate with Context Path
```
Main Agent
1. Call TaskManager (or other subagent)
2. Pass session path in prompt:
"Load context from .tmp/sessions/{session-id}/context.md"
3. TaskManager reads session context
4. TaskManager extracts external context files
5. TaskManager includes in subtask JSONs
```
### Stage 6: Subagents Read External Context
```
TaskManager / CoderAgent / TestEngineer
1. Read session context file
2. Extract "## External Context Fetched" section
3. Read referenced files from .tmp/external-context/
4. Use external docs to inform implementation
5. NO RE-FETCHING ✅
```
---
## Implementation Details
### Step 1: Call ExternalScout
In your main agent (before approval):
```javascript
// Detect external libraries from user request
const externalLibraries = ["drizzle-orm", "better-auth", "next.js"];
// Call ExternalScout
task(
subagent_type="ExternalScout",
description="Fetch external documentation",
prompt="Fetch documentation for these libraries:
- Drizzle ORM: modular schema organization
- Better Auth: Next.js integration
- Next.js: App Router setup
Persist fetched docs to .tmp/external-context/
Return file paths for each fetched document"
)
// Capture returned file paths
// Example return:
// - .tmp/external-context/drizzle-orm/modular-schemas.md
// - .tmp/external-context/better-auth/nextjs-integration.md
// - .tmp/external-context/next.js/app-router-setup.md
```
### Step 2: Propose Plan with External Context
```markdown
## Implementation Plan
**Task**: Set up Drizzle + Better Auth in Next.js
**External Libraries Involved**:
- Drizzle ORM (database)
- Better Auth (authentication)
- Next.js (framework)
**External Context Discovered**:
- `.tmp/external-context/drizzle-orm/modular-schemas.md`
- `.tmp/external-context/better-auth/nextjs-integration.md`
- `.tmp/external-context/next.js/app-router-setup.md`
**Approach**:
1. Set up Drizzle schema with modular organization
2. Configure Better Auth with Drizzle adapter
3. Integrate with Next.js App Router
**Approval needed before proceeding.**
```
### Step 3: Create Session with External Context
After approval, create `.tmp/sessions/{session-id}/context.md`:
```markdown
# Task Context: Drizzle + Better Auth Integration
Session ID: 2026-01-28-drizzle-auth
Created: 2026-01-28T14:30:22Z
Status: in_progress
## Current Request
Set up Drizzle ORM with Better Auth in a Next.js application
## Context Files (Standards to Follow)
- .opencode/context/core/standards/code-quality.md
- .opencode/context/core/standards/test-coverage.md
## Reference Files (Source Material)
- package.json
- src/db/schema.ts (existing)
- src/auth/config.ts (existing)
## External Context Fetched
These are live documentation files fetched from external libraries. Subagents should reference these instead of re-fetching.
### Drizzle ORM
- `.tmp/external-context/drizzle-orm/modular-schemas.md` — Schema organization patterns for modular architecture
- `.tmp/external-context/drizzle-orm/postgresql-setup.md` — PostgreSQL configuration and setup
### Better Auth
- `.tmp/external-context/better-auth/nextjs-integration.md` — Integration guide for Next.js App Router
- `.tmp/external-context/better-auth/drizzle-adapter.md` — Drizzle adapter setup and configuration
### Next.js
- `.tmp/external-context/next.js/app-router-setup.md` — App Router basics and configuration
- `.tmp/external-context/next.js/server-actions.md` — Server Actions patterns for mutations
**Important**: These files are read-only and cached for reference. Do not modify them.
## Components
- Drizzle schema setup with modular organization
- Better Auth configuration with Drizzle adapter
- Next.js App Router integration
## Constraints
- TypeScript strict mode
- Must support PostgreSQL
- Backward compatible with existing auth system
## Exit Criteria
- [ ] Drizzle schema set up with modular organization
- [ ] Better Auth configured with Drizzle adapter
- [ ] Next.js App Router integration complete
- [ ] All tests passing
- [ ] Documentation updated
## Progress
- [ ] Session initialized
- [ ] Tasks created
- [ ] Implementation complete
- [ ] Tests passing
- [ ] Handoff complete
```
### Step 4: Delegate to TaskManager
```javascript
task(
subagent_type="TaskManager",
description="Break down Drizzle + Better Auth integration",
prompt="Load context from .tmp/sessions/2026-01-28-drizzle-auth/context.md
Read the context file for full requirements, standards, and external documentation.
Break down this feature into atomic subtasks:
1. Drizzle schema setup with modular organization
2. Better Auth configuration with Drizzle adapter
3. Next.js App Router integration
4. Test suite
For each subtask, include:
- context_files: Standards from context.md
- reference_files: Project files to understand
- external_context: External docs to reference
Create subtask files in tasks/subtasks/drizzle-auth-integration/"
)
```
### Step 5: TaskManager Creates Subtasks with External Context
TaskManager creates subtask JSONs like:
```json
{
"id": "01-drizzle-schema-setup",
"title": "Set up Drizzle schema with modular organization",
"description": "Create modular Drizzle schema following best practices",
"context_files": [
".opencode/context/core/standards/code-quality.md",
".opencode/context/core/standards/test-coverage.md"
],
"reference_files": [
"package.json",
"src/db/schema.ts"
],
"external_context": [
".tmp/external-context/drizzle-orm/modular-schemas.md",
".tmp/external-context/drizzle-orm/postgresql-setup.md"
],
"instructions": "Set up Drizzle schema following modular patterns from external context. Reference .tmp/external-context/drizzle-orm/modular-schemas.md for best practices.",
"acceptance_criteria": [
"Schema organized into separate files by domain",
"PostgreSQL configuration matches external docs",
"TypeScript types properly exported",
"Tests cover schema setup"
]
}
```
### Step 6: CoderAgent Implements Using External Context
CoderAgent reads subtask JSON and:
1. Loads context_files (standards)
2. Reads reference_files (existing code)
3. **Reads external_context files** (external docs)
4. Implements following all standards and external docs
5. Returns completed subtask
---
## Best Practices
### For Main Agents
**DO**:
- Call ExternalScout early in planning phase
- Capture returned file paths
- Add to session context under "## External Context Fetched"
- Pass session path to subagents
- Include external context in proposal to user
**DON'T**:
- Forget to call ExternalScout when external libraries involved
- Skip adding external context to session
- Re-fetch external docs (trust ExternalScout persistence)
- Modify external context files
### For ExternalScout
**DO**:
- Always persist fetched docs to `.tmp/external-context/`
- Update `.manifest.json` after each fetch
- Include metadata header in every file
- Filter aggressively to relevant sections
- Cite sources and include official docs links
**DON'T**:
- Forget to persist files
- Skip manifest updates
- Return entire documentation
- Fabricate documentation content
- Write outside `.tmp/external-context/`
### For TaskManager
**DO**:
- Extract external_context from session context
- Include in subtask JSONs
- Pass to downstream agents
- Document which external docs informed decisions
**DON'T**:
- Forget to include external_context in subtasks
- Mix external_context with context_files
- Assume subagents will re-fetch
### For Subagents (CoderAgent, TestEngineer, etc.)
**DO**:
- Read external_context files from subtask JSON
- Use external docs to inform implementation
- Reference external docs in comments
- Follow patterns from external docs
**DON'T**:
- Re-fetch external documentation
- Ignore external context files
- Modify external context files
- Assume external docs are optional
---
## Example: Complete Flow
### User Request
```
"Set up Drizzle ORM with Better Auth in Next.js, using modular schema organization"
```
### Main Agent Flow
1. **Analyze**: Detect Drizzle, Better Auth, Next.js
2. **Discover**: Call ContextScout + ExternalScout
3. **Propose**: Show plan with external context files
4. **Approve**: User approves
5. **Init Session**: Create context.md with external context section
6. **Delegate**: Call TaskManager with session path
7. **Validate**: Check tests pass
8. **Complete**: Update docs, cleanup
### ExternalScout Flow
1. **Detect**: Drizzle, Better Auth, Next.js
2. **Fetch**: Get docs from Context7 API
3. **Filter**: Extract relevant sections
4. **Persist**: Write to `.tmp/external-context/{package}/{topic}.md`
5. **Update**: Add to `.manifest.json`
6. **Return**: File paths to main agent
### TaskManager Flow
1. **Read**: Session context.md
2. **Extract**: External context files
3. **Create**: Subtasks with external_context field
4. **Delegate**: Pass to CoderAgent
### CoderAgent Flow
1. **Read**: Subtask JSON
2. **Load**: context_files (standards)
3. **Reference**: reference_files (existing code)
4. **Read**: external_context files (external docs)
5. **Implement**: Following all standards and external docs
6. **Complete**: Return implemented subtask
---
## Troubleshooting
### External Context Files Not Found
**Problem**: Subagent can't find `.tmp/external-context/{package}/{topic}.md`
**Solution**:
1. Check ExternalScout ran successfully
2. Verify file path in session context matches actual location
3. Check `.manifest.json` to see what's cached
4. If missing, re-run ExternalScout
### Stale External Context
**Problem**: External docs are outdated
**Solution**:
1. Delete stale files: `scripts/external-context/manage-external-context.sh delete-package {package}`
2. Re-run ExternalScout to fetch fresh docs
3. Update session context with new file paths
### Manifest Out of Sync
**Problem**: `.manifest.json` doesn't match actual files
**Solution**:
1. Regenerate manifest: `scripts/external-context/manage-external-context.sh regenerate-manifest`
2. Verify all files have metadata headers
---
## References
- **ExternalScout**: `.opencode/agent/subagents/core/externalscout.md`
- **External Context Management**: `.opencode/context/core/workflows/external-context-management.md`
- **Task Delegation**: `.opencode/context/core/workflows/task-delegation-basics.md`
- **Management Script**: `scripts/external-context/manage-external-context.sh`

View File

@@ -0,0 +1,406 @@
<!-- Context: workflows/external-context | Priority: high | Version: 1.0 | Updated: 2026-01-28 -->
# External Context Management
## Overview
External context is live documentation fetched from external libraries and frameworks (via Context7 API or official docs). Instead of re-fetching on every task, we **persist external context** to `.tmp/external-context/` so main agents can pass it to subagents.
**Key Principle**: ExternalScout fetches once → persists to disk → main agents reference → subagents read (no re-fetching)
---
## Directory Structure
```
.tmp/external-context/
├── .manifest.json # Metadata about all cached external docs
├── drizzle-orm/
│ ├── modular-schemas.md # Fetched: "How to organize schemas modularly"
│ ├── postgresql-setup.md # Fetched: "PostgreSQL setup with Drizzle"
│ └── typescript-config.md # Fetched: "TypeScript configuration"
├── better-auth/
│ ├── nextjs-integration.md # Fetched: "Better Auth + Next.js setup"
│ ├── drizzle-adapter.md # Fetched: "Drizzle adapter for Better Auth"
│ └── session-management.md # Fetched: "Session handling"
├── next.js/
│ ├── app-router-setup.md # Fetched: "App Router basics"
│ ├── server-actions.md # Fetched: "Server Actions patterns"
│ └── middleware.md # Fetched: "Middleware configuration"
└── tanstack-query/
├── server-components.md # Fetched: "TanStack Query + Server Components"
└── prefetching.md # Fetched: "Prefetching strategies"
```
### Naming Conventions
- **Package name** (directory): Exact bun --bun package name (kebab-case)
-`drizzle-orm`, `better-auth`, `next.js`, `@tanstack/react-query`
-`drizzle`, `nextjs`, `tanstack-query`
- **File name** (topic): Kebab-case description of the topic
-`modular-schemas.md`, `nextjs-integration.md`, `server-components.md`
-`modular schemas.md`, `NextJS Integration.md`, `ServerComponents.md`
---
## Manifest File
**Location**: `.tmp/external-context/.manifest.json`
**Purpose**: Track what's cached, when it was fetched, and from which source
**Structure**:
```json
{
"last_updated": "2026-01-28T14:30:22Z",
"packages": {
"drizzle-orm": {
"files": [
"modular-schemas.md",
"postgresql-setup.md",
"typescript-config.md"
],
"last_updated": "2026-01-28T14:30:22Z",
"source": "Context7 API",
"official_docs": "https://orm.drizzle.team"
},
"better-auth": {
"files": [
"nextjs-integration.md",
"drizzle-adapter.md",
"session-management.md"
],
"last_updated": "2026-01-28T14:25:10Z",
"source": "Context7 API",
"official_docs": "https://better-auth.com"
},
"next.js": {
"files": [
"app-router-setup.md",
"server-actions.md",
"middleware.md"
],
"last_updated": "2026-01-28T14:20:05Z",
"source": "Context7 API",
"official_docs": "https://nextjs.org"
}
}
}
```
---
## File Format
Each external context file has a metadata header followed by the documentation content.
**Template**:
```markdown
---
source: Context7 API
library: Drizzle ORM
package: drizzle-orm
topic: modular-schemas
fetched: 2026-01-28T14:30:22Z
official_docs: https://orm.drizzle.team/docs/goodies#multi-file-schemas
---
# Modular Schemas in Drizzle ORM
[Filtered documentation content from Context7 API]
## Key Concepts
[Relevant sections only]
## Code Examples
[Practical examples from official docs]
---
**Source**: Context7 API (live, version-specific)
**Official Docs**: https://orm.drizzle.team/docs/goodies#multi-file-schemas
**Fetched**: 2026-01-28T14:30:22Z
```
---
## Workflow: How External Context Flows
### Stage 1: Main Agent Needs External Context
```
Main Agent (e.g., OpenAgent)
Detects: "User is asking about Drizzle + Better Auth + Next.js"
Calls: ExternalScout to fetch live docs
```
### Stage 2: ExternalScout Fetches & Persists
```
ExternalScout
1. Detects libraries: Drizzle, Better Auth, Next.js
2. Fetches from Context7 API (primary) or official docs (fallback)
3. Filters to relevant sections
4. Persists to .tmp/external-context/{package-name}/{topic}.md
5. Updates .manifest.json
Returns: File paths + formatted documentation
```
### Stage 3: Main Agent References in Session Context
```
Main Agent
Creates session: .tmp/sessions/{session-id}/context.md
Adds section: "## External Context Fetched"
Lists files:
- .tmp/external-context/drizzle-orm/modular-schemas.md
- .tmp/external-context/better-auth/nextjs-integration.md
- .tmp/external-context/next.js/app-router-setup.md
Delegates to TaskManager with session path
```
### Stage 4: Subagents Read External Context
```
TaskManager (or CoderAgent, TestEngineer, etc.)
Reads: .tmp/sessions/{session-id}/context.md
Extracts: "## External Context Fetched" section
Reads: .tmp/external-context/{package-name}/{topic}.md files
Uses: External docs to inform implementation
NO RE-FETCHING needed ✅
```
---
## Integration with Task Delegation
### In Session Context File
Add this section to `.tmp/sessions/{session-id}/context.md`:
```markdown
## External Context Fetched
These are live documentation files fetched from external libraries. Subagents should reference these instead of re-fetching.
### Drizzle ORM
- `.tmp/external-context/drizzle-orm/modular-schemas.md` — Schema organization patterns
- `.tmp/external-context/drizzle-orm/postgresql-setup.md` — PostgreSQL configuration
### Better Auth
- `.tmp/external-context/better-auth/nextjs-integration.md` — Next.js integration guide
- `.tmp/external-context/better-auth/drizzle-adapter.md` — Drizzle adapter setup
### Next.js
- `.tmp/external-context/next.js/app-router-setup.md` — App Router basics
- `.tmp/external-context/next.js/server-actions.md` — Server Actions patterns
**Important**: These files are read-only and should not be modified. They're cached for reference only.
```
### In Subtask JSONs (Created by TaskManager)
When TaskManager creates subtask JSONs, it should include external context files:
```json
{
"id": "01-drizzle-schema-setup",
"title": "Set up Drizzle schema with modular organization",
"context_files": [
".opencode/context/core/standards/code-quality.md",
".opencode/context/core/standards/test-coverage.md"
],
"reference_files": [
"package.json",
"src/db/schema.ts"
],
"external_context": [
".tmp/external-context/drizzle-orm/modular-schemas.md",
".tmp/external-context/drizzle-orm/postgresql-setup.md"
],
"instructions": "Set up Drizzle schema following modular patterns from external context..."
}
```
---
## Cleanup & Maintenance
### When to Clean Up
External context files should be cleaned up when:
1. Task is complete and session is deleted
2. External docs become stale (>7 days old)
3. User explicitly requests cleanup
4. Disk space is needed
### How to Clean Up
**Manual cleanup** (ask user first):
```bash
rm -rf .tmp/external-context/{package-name}/
# Update .manifest.json to remove package entry
```
**Automatic cleanup** (future enhancement):
- Add cleanup script that removes files older than 7 days
- Run as part of session cleanup process
- Update manifest after cleanup
### Manifest Cleanup
After deleting external context files, update `.manifest.json`:
```json
{
"last_updated": "2026-01-28T15:00:00Z",
"packages": {
// Remove entries for deleted packages
}
}
```
---
## Best Practices
### For Main Agents (OpenAgent, etc.)
1. **Call ExternalScout early** in the planning phase
2. **Capture returned file paths** from ExternalScout
3. **Add to session context** in "## External Context Fetched" section
4. **Pass session path to subagents** so they know where to find external docs
5. **Don't re-fetch** — trust that ExternalScout persisted correctly
### For ExternalScout
1. **Always persist** fetched documentation to `.tmp/external-context/`
2. **Update manifest** after each fetch
3. **Include metadata header** in every file (source, library, package, topic, fetched timestamp)
4. **Filter aggressively** — only include relevant sections
5. **Cite sources** — include official docs links
### For Subagents (TaskManager, CoderAgent, etc.)
1. **Read external context files** from session context
2. **Don't re-fetch** — use persisted files
3. **Reference in implementation** — cite which external docs informed decisions
4. **Don't modify** external context files — they're read-only
5. **Include in subtask JSONs** — pass external_context to downstream agents
---
## Examples
### Example 1: Drizzle + Better Auth Integration
**Main Agent Flow**:
```
1. User asks: "Set up Drizzle + Better Auth in Next.js"
2. Main agent calls ExternalScout
3. ExternalScout fetches:
- drizzle-orm/modular-schemas.md
- drizzle-orm/postgresql-setup.md
- better-auth/nextjs-integration.md
- better-auth/drizzle-adapter.md
- next.js/app-router-setup.md
4. ExternalScout persists all files to .tmp/external-context/
5. Main agent creates session with "## External Context Fetched" section
6. Main agent delegates to TaskManager with session path
7. TaskManager reads external context, creates subtasks
8. CoderAgent implements using external docs (no re-fetching)
```
**Session Context File**:
```markdown
## External Context Fetched
### Drizzle ORM
- `.tmp/external-context/drizzle-orm/modular-schemas.md`
- `.tmp/external-context/drizzle-orm/postgresql-setup.md`
### Better Auth
- `.tmp/external-context/better-auth/nextjs-integration.md`
- `.tmp/external-context/better-auth/drizzle-adapter.md`
### Next.js
- `.tmp/external-context/next.js/app-router-setup.md`
```
### Example 2: TanStack Query + Server Components
**Main Agent Flow**:
```
1. User asks: "How do I use TanStack Query with Next.js Server Components?"
2. Main agent calls ExternalScout
3. ExternalScout fetches:
- tanstack-query/server-components.md
- tanstack-query/prefetching.md
- next.js/server-components.md
4. ExternalScout persists to .tmp/external-context/
5. Main agent creates session with external context references
6. Subagents read and implement using external docs
```
---
## Troubleshooting
### External Context Files Not Found
**Problem**: Subagent can't find `.tmp/external-context/{package-name}/{topic}.md`
**Solution**:
1. Check that ExternalScout ran successfully
2. Verify file path in session context matches actual file location
3. Check `.manifest.json` to see what's cached
4. If missing, re-run ExternalScout to fetch and persist
### Stale External Context
**Problem**: External docs are outdated (>7 days old)
**Solution**:
1. Delete stale files: `rm -rf .tmp/external-context/{package-name}/`
2. Update `.manifest.json`
3. Re-run ExternalScout to fetch fresh docs
4. Update session context with new file paths
### Manifest Out of Sync
**Problem**: `.manifest.json` doesn't match actual files
**Solution**:
1. Regenerate manifest by listing actual files:
```bash
find .tmp/external-context -name "*.md" | sort
```
2. Update `.manifest.json` to match
3. Verify all files have metadata headers
---
## References
- **ExternalScout**: `.opencode/agent/subagents/core/externalscout.md` — Fetches and persists external docs
- **Task Delegation**: `.opencode/context/core/workflows/task-delegation-basics.md` — How to reference external context in sessions
- **Session Management**: `.opencode/context/core/workflows/session-management.md` — Session lifecycle
- **Library Registry**: `.opencode/skills/context7/library-registry.md` — Supported libraries and query patterns

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/skills/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,270 @@
<!-- Context: workflows/task-breakdown | Priority: high | Version: 2.0 | Updated: 2025-01-21 -->
# Task Breakdown Guidelines
## Quick Reference
**When to Use**: 4+ files, >60 min effort, complex dependencies, multi-step coordination
**Process**: Scope → Phases → Small Tasks (1-2h) → Dependencies → Estimates
**Template Sections**: Overview, Prerequisites, Tasks (by Phase), Testing Strategy, Total Estimate, Notes
**Best Practices**: Keep tasks small (1-2h), make dependencies clear, include verification, be realistic with estimates
---
## Purpose
Framework for breaking down complex tasks into manageable, sequential subtasks.
## When to Use
Reference this when:
- Task involves 4+ files
- Estimated effort >60 minutes
- Complex dependencies exist
- Multi-step coordination needed
- User requests task breakdown
## Breakdown Process
### 1. Understand the Full Scope
- What's the complete requirement?
- What are all the components needed?
- What's the end goal?
- What are the constraints?
### 2. Identify Major Phases
- What are the logical groupings?
- What must happen first?
- What can happen in parallel?
- What depends on what?
### 3. Break Into Small Tasks
- Each task should be 1-2 hours max
- Clear, actionable items
- Independently completable
- Easy to verify completion
### 4. Define Dependencies
- What must be done first?
- What can be done in parallel?
- What blocks what?
- What's the critical path?
### 5. Estimate Effort
- Realistic time estimates
- Include testing time
- Account for unknowns
- Add buffer for complexity
## Breakdown Template
```markdown
# Task Breakdown: {Task Name}
## Overview
{1-2 sentence description of what we're building}
## Prerequisites
- [ ] {Prerequisite 1}
- [ ] {Prerequisite 2}
## Tasks
### Phase 1: {Phase Name}
**Goal:** {What this phase accomplishes}
- [ ] **Task 1.1:** {Description}
- **Files:** {files to create/modify}
- **Estimate:** {time estimate}
- **Dependencies:** {none / task X}
- **Verification:** {how to verify it's done}
- [ ] **Task 1.2:** {Description}
- **Files:** {files to create/modify}
- **Estimate:** {time estimate}
- **Dependencies:** {task 1.1}
- **Verification:** {how to verify it's done}
### Phase 2: {Phase Name}
**Goal:** {What this phase accomplishes}
- [ ] **Task 2.1:** {Description}
- **Files:** {files to create/modify}
- **Estimate:** {time estimate}
- **Dependencies:** {phase 1 complete}
- **Verification:** {how to verify it's done}
## Testing Strategy
- [ ] Unit tests for {component}
- [ ] Integration tests for {flow}
- [ ] Manual testing: {scenarios}
## Total Estimate
**Time:** {X} hours
**Complexity:** {Low / Medium / High}
## Notes
{Any important context, decisions, or considerations}
```
## Example Breakdown
```markdown
# Task Breakdown: User Authentication System
## Overview
Build authentication system with login, registration, and password reset.
## Prerequisites
- [ ] Database schema designed
- [ ] Email service configured
## Tasks
### Phase 1: Core Authentication
**Goal:** Basic login/logout functionality
- [ ] **Task 1.1:** Create user model and database schema
- **Files:** `models/user.js`, `migrations/001_users.sql`
- **Estimate:** 1 hour
- **Dependencies:** none
- **Verification:** Can create user in database
- [ ] **Task 1.2:** Implement password hashing
- **Files:** `utils/password.js`
- **Estimate:** 30 min
- **Dependencies:** Task 1.1
- **Verification:** Passwords are hashed, not plain text
- [ ] **Task 1.3:** Create login endpoint
- **Files:** `routes/auth.js`, `controllers/auth.js`
- **Estimate:** 1.5 hours
- **Dependencies:** Task 1.1, 1.2
- **Verification:** Can login with valid credentials
### Phase 2: Registration
**Goal:** New user registration
- [ ] **Task 2.1:** Create registration endpoint
- **Files:** `routes/auth.js`, `controllers/auth.js`
- **Estimate:** 1 hour
- **Dependencies:** Phase 1 complete
- **Verification:** Can create new user account
- [ ] **Task 2.2:** Add email validation
- **Files:** `utils/validation.js`
- **Estimate:** 30 min
- **Dependencies:** Task 2.1
- **Verification:** Invalid emails rejected
### Phase 3: Password Reset
**Goal:** Users can reset forgotten passwords
- [ ] **Task 3.1:** Generate reset tokens
- **Files:** `utils/tokens.js`
- **Estimate:** 1 hour
- **Dependencies:** Phase 1 complete
- **Verification:** Tokens generated and validated
- [ ] **Task 3.2:** Create reset endpoints
- **Files:** `routes/auth.js`, `controllers/auth.js`
- **Estimate:** 1.5 hours
- **Dependencies:** Task 3.1
- **Verification:** Can request and complete password reset
- [ ] **Task 3.3:** Send reset emails
- **Files:** `services/email.js`
- **Estimate:** 1 hour
- **Dependencies:** Task 3.2
- **Verification:** Reset emails sent successfully
## Testing Strategy
- [ ] Unit tests for password hashing
- [ ] Unit tests for token generation
- [ ] Integration tests for login flow
- [ ] Integration tests for registration flow
- [ ] Integration tests for password reset flow
- [ ] Manual testing: Complete user journey
## Total Estimate
**Time:** 8.5 hours
**Complexity:** Medium
## Notes
- Use bcrypt for password hashing (industry standard)
- Reset tokens expire after 1 hour
- Rate limit password reset requests
- Email service must be configured before Phase 3
```
## Best Practices
### Keep Tasks Small
- 1-2 hours maximum per task
- If larger, break it down further
- Each task should be completable in one sitting
### Make Dependencies Clear
- Explicitly state what must be done first
- Identify parallel work opportunities
- Note blocking dependencies
### Include Verification
- How do you know the task is done?
- What should work when complete?
- How can it be tested?
### Be Realistic with Estimates
- Include time for testing
- Account for unknowns
- Add buffer for complexity
- Better to overestimate than underestimate
### Group Related Work
- Organize by feature or component
- Keep related tasks together
- Make phases logical and cohesive
## Common Patterns
### Database-First Pattern
1. Design schema
2. Create migrations
3. Build models
4. Implement business logic
5. Add API endpoints
6. Write tests
### Feature-First Pattern
1. Define requirements
2. Design interface
3. Implement core logic
4. Add error handling
5. Write tests
6. Document usage
### Refactoring Pattern
1. Add tests for existing behavior
2. Refactor small section
3. Verify tests still pass
4. Repeat for next section
5. Clean up and optimize
6. Update documentation
## Quick Reference
**Good breakdown:**
- Small, focused tasks (1-2 hours)
- Clear dependencies
- Realistic estimates
- Verification criteria
- Logical phases
**Breakdown checklist:**
- [ ] All requirements captured
- [ ] Tasks are small and focused
- [ ] Dependencies identified
- [ ] Estimates are realistic
- [ ] Testing included
- [ ] Verification criteria clear

View File

@@ -0,0 +1,60 @@
<!-- Context: core/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
# Core Workflows Navigation
**Purpose**: Process workflows for common development tasks
---
## Files
| File | Topic | Priority | Load When |
|------|-------|----------|-----------|
| `code-review.md` | Code review process | ⭐⭐⭐⭐ | Reviewing code |
| `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 |
| `session-management.md` | Managing sessions | ⭐⭐⭐ | Session cleanup |
| `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 |
---
## Loading Strategy
**For code review**:
1. Load `code-review.md` (high)
2. Depends on: `../standards/code-quality.md`, `../standards/security-patterns.md`
**For task delegation**:
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**:
1. Load `feature-breakdown.md` (high)
2. Depends on: `task-delegation-basics.md`
**For session management**:
1. Load `session-management.md` (medium)
---
## Related
- **Standards** → `../standards/navigation.md`
- **OpenAgents Control Delegation** → `../../openagents-repo/guides/subagent-invocation.md`

View File

@@ -0,0 +1,19 @@
<!-- Context: workflows/review | Priority: high | Version: 2.0 | Updated: 2025-01-21 -->
# Code Review Guidelines
> **Note**: This is a reference file. The full content is in [`code-review.md`](./code-review.md).
## Quick Reference
**Golden Rule**: Review code as you'd want yours reviewed - thoroughly but kindly
**Checklist**: Functionality, Code Quality, Security, Testing, Performance, Maintainability
**Report Format**: Summary, Assessment, Issues (🔴🟡🔵), Positive Observations, Recommendations
**Principles**: Constructive, Thorough, Timely
---
For the complete code review guidelines, see [code-review.md](./code-review.md).

View File

@@ -0,0 +1,157 @@
<!-- Context: workflows/sessions | Priority: medium | Version: 2.0 | Updated: 2025-01-21 -->
# Session Management
## Quick Reference
**Key Principle**: Lazy initialization - only create when needed
**Session ID**: `{timestamp}-{random-4-chars}` (e.g., `20250118-143022-a4f2`)
**Cleanup**: Always ask user confirmation before deleting
**Safety**: NEVER delete outside current session, ONLY delete tracked files, ALWAYS confirm
---
## Lazy Initialization
**Only create session when first context file needed**
- Don't create sessions for simple questions or direct execution
- Initialize on first delegation that requires context file
- Session ID format: `{timestamp}-{random-4-chars}`
- Example: `20250118-143022-a4f2`
## Session Structure
```
.tmp/sessions/{session-id}/
├── .manifest.json
├── features/
│ └── {task-name}-context.md
├── documentation/
│ └── {task-name}-context.md
├── code/
│ └── {task-name}-context.md
├── tasks/
│ └── {task-name}-tasks.md
└── general/
└── {task-name}-context.md
```
## Session Isolation
**Each session has unique ID - prevents concurrent agent conflicts**
✅ Multiple agent instances can run simultaneously
✅ No file conflicts between sessions
✅ Each session tracks only its own files
✅ Safe cleanup - only deletes own session folder
## Manifest Structure
**Location**: `.tmp/sessions/{session-id}/.manifest.json`
```json
{
"session_id": "20250118-143022-a4f2",
"created_at": "2025-01-18T14:30:22Z",
"last_activity": "2025-01-18T14:35:10Z",
"context_files": {
"features/user-auth-context.md": {
"created": "2025-01-18T14:30:22Z",
"for": "@TaskManager",
"keywords": ["user-auth", "authentication", "features"]
},
"tasks/user-auth-tasks.md": {
"created": "2025-01-18T14:32:15Z",
"for": "@TaskManager",
"keywords": ["user-auth", "tasks", "breakdown"]
}
},
"context_index": {
"user-auth": [
"features/user-auth-context.md",
"tasks/user-auth-tasks.md"
]
}
}
```
## Activity Tracking
**Update timestamp after each context file creation or delegation**
- Update `last_activity` field in manifest
- Used for stale session detection
- Helps identify active vs abandoned sessions
## Cleanup Policy
### Manual Cleanup (Preferred)
**Ask user confirmation before cleanup**
After task completion:
1. Ask: "Should I clean up temporary session files at `.tmp/sessions/{session-id}/`?"
2. Wait for user confirmation
3. Only delete files tracked in current session's manifest
4. Remove entire session folder: `.tmp/sessions/{session-id}/`
### Safety Rules
- **NEVER** delete files outside current session
- **ONLY** delete files tracked in manifest
- **ALWAYS** confirm with user before cleanup
### Stale Session Cleanup
**Auto-remove sessions >24 hours old**
- Check `last_activity` timestamp in manifest
- Safe to run periodically (see `scripts/cleanup-stale-sessions.sh`)
- Won't affect active sessions
## Error Handling
### Subagent Failure
- Report error to user
- Ask if should retry or abort
- Don't auto-retry without approval
### Context File Error
- Fall back to inline context in delegation prompt
- Warn user that context file creation failed
- Continue with task if possible
### Session Creation Error
- Continue without session
- Warn user
- Use inline context for delegation
- Don't block task execution
## Best Practices
1. **Lazy Init**: Only create session when actually needed
2. **Track Everything**: Add all context files to manifest
3. **Update Activity**: Touch `last_activity` on each operation
4. **Clean Promptly**: Remove files after task completion
5. **Isolate Sessions**: Never access files from other sessions
6. **Confirm Cleanup**: Always ask user before deleting
## Example Workflow
```bash
# User: "Build user authentication system"
# → Complex task, needs context file
# → Create session: 20250118-143022-a4f2
# → Create: .tmp/sessions/20250118-143022-a4f2/features/user-auth-context.md
# → Delegate to @task-manager
# User: "Implement login component"
# → Same session, add context
# → Create: .tmp/sessions/20250118-143022-a4f2/code/login-context.md
# → Delegate to @coder-agent
# Task complete
# → Ask: "Clean up session files?"
# → User confirms
# → Delete: .tmp/sessions/20250118-143022-a4f2/
```

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-overview.md` - OpenFrontendSpecialist workflow