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,41 @@
<!-- Context: development/agents-tools | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
# Concept: Mastra Agents & Tools
**Purpose**: Reusable units of logic and LLM-powered entities.
**Last Updated**: 2026-01-09
---
## Core Idea
Agents are specialized LLM configurations that use Tools to interact with external systems or perform specific logic. Tools are the building blocks that provide functionality to both agents and workflows.
## Key Points
- **Agents**: Defined with a `name`, `instructions`, and `model`. They can be assigned a set of `tools`.
- **Tools**: Defined with `id`, `inputSchema`, `outputSchema`, and an `execute` function.
- **Type Safety**: Both agents and tools use Zod for schema validation.
- **Standalone Use**: Tools can be executed independently of agents, making them highly reusable.
## Quick Example
```typescript
// Tool
const myTool = createTool({
id: 'my-tool',
inputSchema: z.object({ query: z.string() }),
execute: async ({ inputData }) => ({ result: `Processed ${inputData.query}` }),
});
// Agent
const myAgent = new Agent({
name: 'My Agent',
instructions: 'Use my-tool to process queries.',
model: { provider: 'OPEN_AI', name: 'gpt-4o' },
tools: { myTool },
});
```
**Reference**: `src/mastra/agents/`, `src/mastra/tools/`
**Related**:
- concepts/core.md
- concepts/workflows.md

View File

@@ -0,0 +1,37 @@
<!-- Context: development/core | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
# Concept: Mastra Core
**Purpose**: Central orchestration layer for AI agents, workflows, and tools in this project.
**Last Updated**: 2026-01-09
---
## Core Idea
Mastra is the central hub that wires together agents, tools, workflows, and observability. It provides a unified interface for executing complex AI tasks with built-in persistence and logging.
## Key Points
- **Centralized Config**: All components are registered in `src/mastra/index.ts`.
- **Persistence**: Uses `LibSQLStore` (SQLite) for storing traces, spans, and workflow states.
- **Observability**: Built-in tracing and logging (Pino) for every execution.
- **Modular Design**: Agents, tools, and workflows are defined separately and composed in the main instance.
## Quick Example
```typescript
import { Mastra } from '@mastra/core/mastra';
import { agents, tools, workflows } from './components';
export const mastra = new Mastra({
agents,
tools,
workflows,
storage: new LibSQLStore({ url: 'file:./mastra.db' }),
});
```
**Reference**: `src/mastra/index.ts`
**Related**:
- concepts/workflows.md
- concepts/agents-tools.md
- lookup/mastra-config.md

View File

@@ -0,0 +1,41 @@
<!-- Context: development/evaluations | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
# Concept: Mastra Evaluations
**Purpose**: Quality assurance and scoring for LLM outputs.
**Last Updated**: 2026-01-09
---
## Core Idea
Evaluations in Mastra use Scorers to assess the quality, accuracy, and safety of LLM-generated content. They provide a quantitative way to measure performance and detect issues like hallucinations or factual errors.
## Key Points
- **Scorers**: Specialized functions that take LLM output (and optionally ground truth) and return a score (0-1).
- **Integration**: Registered in the Mastra instance and can be triggered automatically during workflow execution.
- **Metrics**: Common metrics include hallucination detection, fact validation, and relevance scoring.
- **Audit Trail**: Scorer results are stored in the `mastra_scorers` table for long-term analysis and reporting.
## Quick Example
```typescript
// Scorer definition
export const hallucinationDetector = new Scorer({
id: 'hallucination-detector',
description: 'Detects hallucinations in LLM output',
execute: async ({ output, context }) => {
// Logic to detect hallucinations
return { score: 0.95, rationale: 'No hallucinations found' };
},
});
// Registration
export const mastra = new Mastra({
scorers: { hallucinationDetector },
});
```
**Reference**: `src/mastra/scorers/`, `src/mastra/evaluation/`
**Related**:
- concepts/core.md
- concepts/workflows.md

View File

@@ -0,0 +1,38 @@
<!-- Context: development/storage | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
# Concept: Mastra Data Storage
**Purpose**: Persistence layer for cases, documents, assessments, and observability.
**Last Updated**: 2026-01-09
---
## Core Idea
Mastra uses a dual-storage approach: a local SQLite database (via Drizzle ORM) for business entities and a built-in `LibSQLStore` for Mastra-specific execution data (traces, spans).
## Key Points
- **Business Entities**: Managed in `src/db/schema.ts`. Includes `cases`, `documents`, `assessments`, and `outputs`.
- **Mastra Store**: `LibSQLStore` handles `mastra_traces`, `mastra_ai_spans`, and `mastra_scorers`.
- **V3 Extensions**: Specific tables for `timeline_events`, `evidence_gaps`, `sub_claims`, and `vulnerability_flags`.
- **Observability**: `prompt_execution_traces` provides detailed cost and token tracking per AI call.
- **File Storage**: Large blobs (PDFs, JSON outputs) are stored in `./tmp/` with paths referenced in the DB.
## Quick Example
```typescript
// Business Schema (Drizzle)
export const cases = sqliteTable('cases', {
id: text('id').primaryKey(),
status: text('status').default('new'),
});
// Mastra Store Config
storage: new LibSQLStore({
url: process.env.MASTRA_DB_PATH || 'file:./mastra.db',
}),
```
**Reference**: `src/db/schema.ts`, `src/mastra/index.ts`
**Related**:
- concepts/core.md
- lookup/mastra-config.md

View File

@@ -0,0 +1,35 @@
<!-- Context: development/workflows | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
# Concept: Mastra Workflows
**Purpose**: Linear and parallel execution chains for complex AI tasks.
**Last Updated**: 2026-01-09
---
## Core Idea
Workflows in Mastra are directed graphs of steps that process data sequentially or in parallel. They provide a structured way to handle multi-stage LLM operations with built-in state management and human-in-the-loop (HITL) support.
## Key Points
- **Step Definition**: Created with `createStep`, requiring `inputSchema`, `outputSchema`, and an `execute` function.
- **Chaining**: Steps are linked using `.then()` for sequential and `.parallel()` for concurrent execution.
- **HITL Support**: Steps can `suspend` execution to wait for human input and `resume` when data is provided.
- **State Access**: Each step has access to the global workflow `state` and the `inputData` from the previous step.
## Quick Example
```typescript
const workflow = createWorkflow({ id: 'my-workflow', inputSchema, outputSchema })
.then(step1)
.parallel([step2a, step2b])
.then(mergeStep)
.commit();
const { runId, start } = workflow.createRun();
const result = await start({ inputData: { ... } });
```
**Reference**: `src/mastra/workflows/`
**Related**:
- concepts/core.md
- examples/workflow-example.md

View File

@@ -0,0 +1,33 @@
<!-- Context: development/mastra-errors | Priority: medium | Version: 1.0 | Updated: 2026-02-15 -->
# Errors: Mastra Implementation
**Purpose**: Common errors, their causes, and recovery strategies.
**Last Updated**: 2026-01-09
---
## Core Idea
Errors in Mastra typically fall into three categories: AI generation failures, structured output validation errors, and context/resource missing errors.
## Key Points
- **AIGenerationError**: Occurs when the LLM fails to generate a response (e.g., safety filters, model downtime).
- **StructuredOutputError**: Triggered when the LLM response doesn't match the Zod schema defined in the tool or step.
- **RateLimitError**: Hit when exceeding provider limits. Includes a `retryAfter` value.
- **MastraContextError**: Raised when a required resource (like `services` or `mastra` instance) is missing from the execution context.
- **Retry Strategy**: Use `isRetryableError(error)` to determine if a transient failure can be recovered with exponential backoff.
## Common Errors Table
| Error | Cause | Fix |
|-------|-------|-----|
| `StructuredOutputError` | LLM hallucinated wrong JSON | Refine prompt or use simpler schema |
| `RateLimitError` | Too many concurrent requests | Implement rate limiting or increase quota |
| `NotFoundError` | Case or Document ID missing in DB | Check DB state before workflow start |
| `MastraContextError` | `services` not passed to tool | Ensure `services` is in `ToolExecutionContext` |
**Reference**: `src/lib/errors.ts`
**Related**:
- concepts/core.md
- guides/testing.md

View File

@@ -0,0 +1,42 @@
<!-- Context: development/workflow-example | Priority: high | Version: 1.0 | Updated: 2026-02-15 -->
# Example: Document Ingestion Workflow
**Purpose**: Demonstrates a multi-step workflow with parallel processing.
**Last Updated**: 2026-01-09
---
## Workflow Definition
```typescript
export const documentIngestionWorkflow = createWorkflow({
id: 'document-ingestion',
inputSchema: z.object({ filename: z.string(), fileBuffer: z.any() }),
outputSchema: z.object({ documentId: z.string(), success: z.boolean() }),
})
.then(uploadStep) // Step 1: Upload
.then(extractionStep) // Step 2: Extract Text
.parallel([ // Step 3: Process in parallel
classificationStep,
summarizationStep
])
.then(mergeResultsStep) // Step 4: Merge
.commit();
```
## Step Execution
```typescript
const uploadStep = createStep({
id: 'upload-document',
execute: async ({ inputData, mastra }) => {
const result = await documentUploadTool.execute(inputData, { mastra });
return result;
},
});
```
**Reference**: `src/mastra/workflows/document-ingestion-with-classification-workflow.ts`
**Related**:
- concepts/workflows.md
- concepts/agents-tools.md

View File

@@ -0,0 +1,37 @@
<!-- Context: development/modular-building | Priority: high | Version: 1.0 | Updated: 2026-02-15 -->
# Guide: Modular Mastra Building
**Purpose**: Best practices for structuring a large-scale Mastra implementation.
**Last Updated**: 2026-01-09
---
## Core Idea
Modular building ensures that as the project grows, components remain testable, reusable, and easy to navigate. This is achieved by separating logic into specialized directories and using a central registry.
## Key Points
- **Component Separation**: Keep `agents`, `tools`, `workflows`, and `scorers` in their own top-level directories within `src/mastra/`.
- **Shared Services**: Use a `shared.ts` file to instantiate services (DB, repositories) to prevent circular dependencies between workflows and the main Mastra instance.
- **Central Registry**: Register all components in `src/mastra/index.ts`. This is the single source of truth for the Mastra instance.
- **Feature-Based Steps**: Group related workflow steps into sub-directories (e.g., `src/mastra/workflows/v3/steps/`) to keep workflow files clean.
## Quick Example
```typescript
// src/mastra/shared.ts
export const services = createServices();
// src/mastra/index.ts
import { services } from './shared';
export const mastra = new Mastra({
workflows: { myWorkflow },
agents: { myAgent },
// ...
});
```
**Reference**: `src/mastra/index.ts`, `src/mastra/shared.ts`
**Related**:
- concepts/core.md
- guides/workflow-step-structure.md

View File

@@ -0,0 +1,35 @@
<!-- Context: development/testing | Priority: high | Version: 1.0 | Updated: 2026-02-15 -->
# Guide: Testing Mastra
**Purpose**: How to run and validate Mastra components in this project.
**Last Updated**: 2026-01-09
---
## Core Idea
Testing in this project is divided into tool-level tests and full workflow integration tests. Use the provided bun --bun scripts for rapid validation.
## Key Points
- **Tool Tests**: Validate individual tools in isolation (e.g., `bun --bun run test:playbook`).
- **Workflow Tests**: Run full end-to-end scenarios (e.g., `bun --bun run test:workflow`).
- **Baseline Tests**: Compare current performance against a known baseline (`bun --bun run test:baseline`).
- **Observability**: Use `bun --bun run traces` after tests to inspect the execution details in the database.
## Quick Example
```bash
# Test a specific tool
bun --bun run test:calculator
# Run full validity workflow
bun --bun run validity:workflow
# View results of the last run
bun --bun run traces
```
**Reference**: `package.json` scripts, `scripts/` directory
**Related**:
- concepts/core.md
- lookup/mastra-config.md

View File

@@ -0,0 +1,40 @@
<!-- Context: development/workflow-step-structure | Priority: high | Version: 1.0 | Updated: 2026-02-15 -->
# Guide: Workflow Step Structure
**Purpose**: Standardized pattern for defining maintainable and testable workflow steps.
**Last Updated**: 2026-01-09
---
## Core Idea
Workflow steps should be self-contained units that encapsulate their input/output schemas and execution logic. For complex workflows, steps should be moved to a dedicated `steps/` directory and grouped by phase.
## Key Points
- **Directory Structure**: Group steps by phase (e.g., `steps/phase1-load.ts`, `steps/phase2-process.ts`).
- **Schema Centralization**: Define shared schemas (like `workflowStateSchema`) in a `schemas.ts` file within the steps directory.
- **Explicit State**: Use `stateSchema` in `createStep` to ensure type safety when accessing the global workflow state.
- **Tool Delegation**: Steps should primarily act as orchestrators, delegating heavy lifting to Tools.
- **Logging**: Include clear console logs at the start and end of each step for easier debugging.
## Quick Example
```typescript
// src/mastra/workflows/v3/steps/phase1.ts
export const myStep = createStep({
id: 'my-step-id',
inputSchema: z.object({ ... }),
outputSchema: z.object({ ... }),
stateSchema: workflowStateSchema,
execute: async ({ inputData, state, mastra }) => {
console.log('🚀 Starting myStep...');
const result = await myTool.execute(inputData, { mastra });
return result;
},
});
```
**Reference**: `src/mastra/workflows/v3/steps/`
**Related**:
- concepts/workflows.md
- guides/modular-building.md

View File

@@ -0,0 +1,41 @@
<!-- Context: development/mastra-config | Priority: high | Version: 1.0 | Updated: 2026-02-15 -->
# Lookup: Mastra Configuration
**Purpose**: Quick reference for Mastra file locations and registration.
**Last Updated**: 2026-01-09
---
## File Locations
| Component | Directory | Registration File |
|-----------|-----------|-------------------|
| **Mastra Instance** | `src/mastra/` | `src/mastra/index.ts` |
| **Agents** | `src/mastra/agents/` | `src/mastra/index.ts` |
| **Tools** | `src/mastra/tools/` | `src/mastra/index.ts` |
| **Workflows** | `src/mastra/workflows/` | `src/mastra/index.ts` |
| **Scorers** | `src/mastra/scorers/` | `src/mastra/index.ts` |
| **Services** | `src/services/` | `src/mastra/shared.ts` |
## Database Tables
| Table Name | Description |
|------------|-------------|
| `mastra_traces` | Workflow execution traces |
| `mastra_ai_spans` | LLM call spans and token usage |
| `mastra_scorers` | Evaluation results and scores |
| `mastra_workflow_state` | Current state of running workflows |
## Common Commands
| Command | Description |
|---------|-------------|
| `bun --bun run dev` | Start Mastra in development mode |
| `bun --bun run traces` | View recent execution traces |
| `bun --bun run test:workflow` | Run the test workflow script |
**Related**:
- concepts/core.md
- concepts/workflows.md

View File

@@ -0,0 +1,31 @@
<!-- Context: development/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
# AI Navigation
**Purpose**: AI frameworks, agent runtimes, and LLM integration patterns.
---
## Structure
```
ai/
├── navigation.md
└── mastra-ai/
├── navigation.md
└── [patterns].md
```
---
## Quick Routes
| Task | Path |
|------|------|
| **MAStra AI** | `mastra-ai/navigation.md` |
---
## By Technology
**MAStra AI** → AI framework for building agents and workflows.

View File

@@ -0,0 +1,79 @@
<!-- Context: development/navigation | Priority: low | Version: 1.0 | Updated: 2026-02-15 -->
# Backend Development Navigation
**Scope**: Server-side, APIs, databases, auth
---
## Structure
```
development/backend/ # [future]
├── navigation.md
├── api-patterns/ # Approach-based
│ ├── rest-design.md
│ ├── graphql-design.md
│ ├── grpc-patterns.md
│ └── websocket-patterns.md
├── nodejs/ # Tech-specific
│ ├── express-patterns.md
│ ├── fastify-patterns.md
│ └── error-handling.md
├── python/
│ ├── fastapi-patterns.md
│ └── django-patterns.md
├── authentication/ # Functional concern
│ ├── jwt-patterns.md
│ ├── oauth-patterns.md
│ └── session-management.md
└── middleware/
├── logging.md
├── rate-limiting.md
└── cors.md
```
---
## Quick Routes
| Task | Path |
|------|------|
| **REST API** | `backend/api-patterns/rest-design.md` [future] |
| **GraphQL** | `backend/api-patterns/graphql-design.md` [future] |
| **API design principles** | `principles/api-design.md` |
| **Node.js** | `backend/nodejs/express-patterns.md` [future] |
| **Python** | `backend/python/fastapi-patterns.md` [future] |
| **Auth (JWT)** | `backend/authentication/jwt-patterns.md` [future] |
---
## By Approach
**REST**`backend/api-patterns/rest-design.md` [future]
**GraphQL**`backend/api-patterns/graphql-design.md` [future]
**gRPC**`backend/api-patterns/grpc-patterns.md` [future]
## By Language
**Node.js**`backend/nodejs/` [future]
**Python**`backend/python/` [future]
## By Concern
**Authentication**`backend/authentication/` [future]
**Middleware**`backend/middleware/` [future]
**Data layer**`data/` [future]
---
## Related Context
- **API Design Principles** → `principles/api-design.md`
- **Core Standards** → `../core/standards/code-quality.md`
- **Data Patterns** → `data/navigation.md` [future]

View File

@@ -0,0 +1,57 @@
<!-- Context: development/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
# Backend Development Navigation
**Purpose**: Server-side development patterns
**Status**: 🚧 Placeholder - Content coming soon
---
## Planned Structure
```
backend/
├── navigation.md
├── api-patterns/ # Approach-based
│ ├── rest-design.md
│ ├── graphql-design.md
│ ├── grpc-patterns.md
│ └── trpc-patterns.md
├── nodejs/ # Tech-specific
│ ├── express-patterns.md
│ ├── fastify-patterns.md
│ └── nextjs-api-routes.md
├── python/
│ ├── fastapi-patterns.md
│ └── django-patterns.md
├── authentication/ # Functional concern
│ ├── jwt-patterns.md
│ ├── oauth-patterns.md
│ └── session-management.md
└── middleware/
├── logging.md
├── rate-limiting.md
└── cors.md
```
---
## For Now
Use specialized navigation: `../backend-navigation.md`
Also see: `../principles/api-design.md`
---
## Related Context
- **Backend Navigation** → `../backend-navigation.md`
- **API Design Principles** → `../principles/api-design.md`
- **Core Standards** → `../../core/standards/code-quality.md`

View File

@@ -0,0 +1,38 @@
<!-- Context: development/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
# Data Layer Navigation
**Purpose**: Database and data access patterns
**Status**: 🚧 Placeholder - Content coming soon
---
## Planned Structure
```
data/
├── navigation.md
├── sql-patterns/
│ ├── postgres-patterns.md
│ ├── mysql-patterns.md
│ └── query-optimization.md
├── nosql-patterns/
│ ├── mongodb-patterns.md
│ ├── redis-patterns.md
│ └── dynamodb-patterns.md
└── orm-patterns/
├── prisma-patterns.md
├── typeorm-patterns.md
└── sequelize-patterns.md
```
---
## Related Context
- **Backend Navigation** → `../backend-navigation.md`
- **Core Standards** → `../../core/standards/code-quality.md`

View File

@@ -0,0 +1,31 @@
<!-- Context: development/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
# Frameworks Navigation
**Purpose**: Full-stack and meta-frameworks that span multiple architectural layers.
---
## Structure
```
frameworks/
├── navigation.md
└── tanstack-start/
├── navigation.md
└── [patterns].md
```
---
## Quick Routes
| Task | Path |
|------|------|
| **Tanstack Start** | `tanstack-start/navigation.md` |
---
## By Framework
**Tanstack Start** → Full-stack React framework with SSR and server functions.

View File

@@ -0,0 +1,42 @@
<!-- Context: development/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
# Frontend Development Navigation
**Purpose**: Client-side development patterns
---
## Structure
```
frontend/
├── navigation.md
├── when-to-delegate.md
└── react/
├── navigation.md
└── react-patterns.md
```
---
## Quick Routes
| Task | Path |
|------|------|
| **When to delegate** | `when-to-delegate.md` |
| **React patterns** | `react/react-patterns.md` |
| **React navigation** | `react/navigation.md` |
---
## By Framework
**React**`react/` - Modern React patterns, hooks, component design
---
## Related Context
- **UI Navigation** → `../ui-navigation.md`
- **Visual Design** → `../../ui/web/navigation.md`
- **Core Standards** → `../../core/standards/code-quality.md`

View File

@@ -0,0 +1,468 @@
<!-- Context: development/frontend/when-to-delegate | Priority: high | Version: 1.0 | Updated: 2026-01-30 -->
# When to Delegate to Frontend Specialist
## Overview
Clear decision criteria for when to delegate frontend/UI work to the **frontend-specialist** subagent vs. handling it directly.
## Quick Reference
**Delegate to frontend-specialist when**:
- UI/UX design work (wireframes, themes, animations)
- Design system implementation
- Complex responsive layouts
- Animation and micro-interactions
- Visual design iterations
**Handle directly when**:
- Simple HTML/CSS edits
- Single component updates
- Bug fixes in existing UI
- Minor styling tweaks
---
## Decision Matrix
### ✅ DELEGATE to Frontend-Specialist
| Scenario | Why Delegate | Example |
|----------|--------------|---------|
| **New UI design from scratch** | Needs staged workflow (layout → theme → animation → implement) | "Create a landing page for our product" |
| **Design system work** | Requires ContextScout for standards, ExternalScout for UI libs | "Implement our design system with Tailwind + Shadcn" |
| **Complex responsive layouts** | Needs mobile-first approach across breakpoints | "Build a dashboard with sidebar, cards, and responsive grid" |
| **Animation implementation** | Requires animation patterns, performance optimization | "Add smooth transitions and micro-interactions to the UI" |
| **Multi-stage design iterations** | Needs versioning (design_iterations/ folder) | "Design a checkout flow with 3 steps" |
| **Theme creation** | Requires OKLCH colors, CSS custom properties | "Create a dark mode theme for the app" |
| **Component library integration** | Needs ExternalScout for current docs (Flowbite, Radix, etc.) | "Integrate Flowbite components into our app" |
| **Accessibility-focused UI** | Requires WCAG compliance, ARIA attributes | "Build an accessible form with proper labels and validation" |
### ⚠️ HANDLE DIRECTLY (Don't Delegate)
| Scenario | Why Direct | Example |
|----------|------------|---------|
| **Simple HTML edits** | Single file, straightforward change | "Change the button text from 'Submit' to 'Send'" |
| **Minor CSS tweaks** | Small styling adjustment | "Make the header padding 20px instead of 16px" |
| **Bug fixes** | Fixing existing code, not creating new design | "Fix the broken link in the footer" |
| **Content updates** | Changing text, images, or data | "Update the hero section copy" |
| **Single component updates** | Modifying one existing component | "Add a new prop to the Button component" |
| **Quick prototypes** | Throwaway code for testing | "Create a quick HTML mockup to test an idea" |
---
## Delegation Checklist
Before delegating to frontend-specialist, ensure:
- [ ] **Task is UI/design focused** (not backend, logic, or data)
- [ ] **Task requires design expertise** (layout, theme, animations)
- [ ] **Task benefits from staged workflow** (layout → theme → animation → implement)
- [ ] **Task needs context discovery** (design systems, UI libraries, standards)
- [ ] **User has approved the approach** (never delegate before approval)
---
## How to Delegate
### Step 1: Discover Context (Optional but Recommended)
If you're unsure what context the frontend-specialist will need:
```javascript
task(
subagent_type="ContextScout",
description="Find frontend design context",
prompt="Find design system standards, UI component patterns, animation guidelines, and responsive breakpoint conventions for frontend work."
)
```
### Step 2: Propose Approach
Present a plan to the user:
```markdown
## Implementation Plan
**Task**: Create landing page with hero section, features grid, and CTA
**Approach**: Delegate to frontend-specialist subagent
**Why**:
- Requires design system implementation
- Needs responsive layout across breakpoints
- Includes animations and micro-interactions
- Benefits from staged workflow (layout → theme → animation → implement)
**Context Needed**:
- Design system standards (ui/web/design-systems.md)
- UI styling standards (ui/web/ui-styling-standards.md)
- Animation patterns (ui/web/animation-patterns.md)
**Approval needed before proceeding.**
```
### Step 3: Get Approval
Wait for explicit user approval before delegating.
### Step 4: Delegate with Context
**For simple delegation** (no session needed):
```javascript
task(
subagent_type="frontend-specialist",
description="Create landing page design",
prompt="Context to load:
- .opencode/context/ui/web/design-systems.md
- .opencode/context/ui/web/ui-styling-standards.md
- .opencode/context/ui/web/animation-basics.md
Task: Create a landing page with:
- Hero section with headline, subheadline, CTA button
- Features grid (3 columns on desktop, 1 on mobile)
- Smooth scroll animations
Requirements:
- Use Tailwind CSS + Flowbite
- Mobile-first responsive design
- Animations <400ms
- Save to design_iterations/landing_1.html
Follow your staged workflow:
1. Layout (ASCII wireframe)
2. Theme (CSS theme file)
3. Animation (micro-interactions)
4. Implement (HTML file)
Request approval between each stage."
)
```
**For complex delegation** (with session):
Create session context file first, then delegate with session path.
---
## Common Patterns
### Pattern 1: New Landing Page
**Trigger**: User asks for a new landing page, marketing page, or product page
**Decision**: ✅ Delegate to frontend-specialist
**Why**: Requires full design workflow (layout, theme, animations, implementation)
**Example**:
```
User: "Create a landing page for our SaaS product"
You: [Propose approach] → [Get approval] → [Delegate to frontend-specialist]
```
### Pattern 2: Design System Implementation
**Trigger**: User wants to implement or update a design system
**Decision**: ✅ Delegate to frontend-specialist
**Why**: Needs ContextScout for standards, ExternalScout for UI library docs
**Example**:
```
User: "Implement our design system using Tailwind and Shadcn"
You: [Propose approach] → [Get approval] → [Delegate to frontend-specialist]
```
### Pattern 3: Component Library Integration
**Trigger**: User wants to integrate a UI component library (Flowbite, Radix, etc.)
**Decision**: ✅ Delegate to frontend-specialist
**Why**: Requires ExternalScout for current docs, proper integration patterns
**Example**:
```
User: "Add Flowbite components to our app"
You: [Propose approach] → [Get approval] → [Delegate to frontend-specialist]
```
### Pattern 4: Animation Work
**Trigger**: User wants animations, transitions, or micro-interactions
**Decision**: ✅ Delegate to frontend-specialist
**Why**: Requires animation patterns, performance optimization (<400ms)
**Example**:
```
User: "Add smooth animations to the dashboard"
You: [Propose approach] → [Get approval] → [Delegate to frontend-specialist]
```
### Pattern 5: Simple HTML Edit
**Trigger**: User wants to change text, fix a link, or update content
**Decision**: Handle directly (don't delegate)
**Why**: Simple edit, no design work needed
**Example**:
```
User: "Change the button text to 'Get Started'"
You: [Edit the HTML file directly]
```
### Pattern 6: CSS Bug Fix
**Trigger**: User reports a styling bug or broken layout
**Decision**: Handle directly (don't delegate)
**Why**: Bug fix, not new design work
**Example**:
```
User: "The header is overlapping the content on mobile"
You: [Read the CSS, fix the issue directly]
```
---
## Red Flags (Don't Delegate)
**User just wants a quick fix** Handle directly
**Task is backend/logic focused** Wrong subagent (use coder-agent or handle directly)
**Task is a single line change** Handle directly
**Task is content update** Handle directly
**Task is testing/validation** Wrong subagent (use tester)
**Task is code review** Wrong subagent (use reviewer)
---
## Green Flags (Delegate)
**User wants a new UI design** Delegate
**Task involves design systems** Delegate
**Task requires responsive layouts** Delegate
**Task includes animations** Delegate
**Task needs UI library integration** Delegate
**Task benefits from staged workflow** Delegate
**Task requires design expertise** Delegate
---
## Frontend-Specialist Capabilities
**What it does well**:
- Create complete UI designs from scratch
- Implement design systems (Tailwind, Shadcn, Flowbite)
- Build responsive layouts (mobile-first)
- Add animations and micro-interactions
- Integrate UI component libraries
- Create themes with OKLCH colors
- Follow staged workflow (layout theme animation implement)
- Version designs (design_iterations/ folder)
**What it doesn't do**:
- Backend logic or API integration
- Database queries or data processing
- Testing or validation
- Code review or refactoring
- Simple HTML/CSS edits (overkill)
- Content updates (just text changes)
---
## Context Files Frontend-Specialist Uses
The frontend-specialist will automatically load these via ContextScout:
**Design System**:
- `ui/web/design-systems.md` - Theme templates, color systems
- `ui/web/ui-styling-standards.md` - Tailwind, Flowbite, responsive design
- `ui/web/design-assets.md` - Images, icons, fonts
**Patterns**:
- `ui/web/animation-patterns.md` - Animation syntax, micro-interactions
- `development/frontend/react/react-patterns.md` - React patterns (if React project)
**Workflows**:
- `core/workflows/design-iteration-overview.md` - Design iteration workflow
---
## Best Practices
### Do's ✅
- **Propose before delegating** - Show user the plan first
- **Get approval** - Never delegate without user approval
- **Provide context** - List context files the subagent should load
- **Set clear requirements** - Specify design system, breakpoints, animations
- **Use staged workflow** - Let frontend-specialist follow its process
- **Trust the specialist** - It knows design patterns and best practices
### Don'ts ❌
- **Don't delegate simple edits** - Handle directly for efficiency
- **Don't skip approval** - Always get user sign-off first
- **Don't delegate backend work** - Wrong subagent
- **Don't micromanage** - Let the specialist follow its workflow
- **Don't delegate without context** - Provide context files to load
- **Don't delegate bug fixes** - Handle directly unless it's a design issue
---
## Examples
### Example 1: Landing Page (Delegate)
**User Request**: "Create a landing page for our SaaS product with a hero section, features, and pricing"
**Your Response**:
```markdown
## Implementation Plan
**Task**: Create SaaS landing page
**Approach**: Delegate to frontend-specialist subagent
**Why**:
- Requires full design workflow (layout, theme, animations)
- Needs responsive design across breakpoints
- Benefits from design system standards
**Context Needed**:
- Design system standards
- UI styling standards
- Animation patterns
**Approval needed before proceeding.**
```
**After Approval**:
```javascript
task(
subagent_type="frontend-specialist",
description="Create SaaS landing page",
prompt="Context to load:
- .opencode/context/ui/web/design-systems.md
- .opencode/context/ui/web/ui-styling-standards.md
- .opencode/context/ui/web/animation-basics.md
Task: Create a SaaS landing page with:
- Hero section (headline, subheadline, CTA)
- Features section (3-column grid)
- Pricing section (3 tiers)
- Footer
Requirements:
- Tailwind CSS + Flowbite
- Mobile-first responsive
- Smooth scroll animations
- Modern design system
Follow staged workflow and request approval between stages."
)
```
### Example 2: Button Text Change (Direct)
**User Request**: "Change the 'Submit' button to say 'Send Message'"
**Your Response**:
```markdown
I'll update the button text directly.
```
**Action**: Read the HTML file, edit the button text, done. No delegation needed.
---
### Example 3: Design System Implementation (Delegate)
**User Request**: "Implement our design system using Tailwind and Shadcn components"
**Your Response**:
```markdown
## Implementation Plan
**Task**: Implement design system with Tailwind + Shadcn
**Approach**: Delegate to frontend-specialist subagent
**Why**:
- Requires UI library integration (Shadcn)
- Needs ExternalScout for current Shadcn docs
- Benefits from design system standards
**Context Needed**:
- Design system standards
- UI styling standards
- External docs (Shadcn)
**Approval needed before proceeding.**
```
**After Approval**:
```javascript
task(
subagent_type="frontend-specialist",
description="Implement Tailwind + Shadcn design system",
prompt="Context to load:
- .opencode/context/ui/web/design-systems.md
- .opencode/context/ui/web/ui-styling-standards.md
Task: Implement design system using Tailwind CSS and Shadcn/ui
Requirements:
- Call ExternalScout for current Shadcn docs
- Set up Tailwind config
- Integrate Shadcn components
- Create theme file with OKLCH colors
- Document component usage
Follow staged workflow and request approval between stages."
)
```
---
## Summary
**Delegate to frontend-specialist when**:
- New UI designs from scratch
- Design system implementation
- Complex responsive layouts
- Animation work
- UI library integration
- Multi-stage design iterations
**Handle directly when**:
- Simple HTML/CSS edits
- Bug fixes
- Content updates
- Single component updates
- Quick prototypes
**Always**:
- Propose approach first
- Get user approval
- Provide context files
- Trust the specialist's workflow
---
## Related Context
- **Frontend Specialist Agent** `../../../agent/subagents/development/frontend-specialist.md`
- **Design Systems** `../../ui/web/design-systems.md`
- **UI Styling Standards** `../../ui/web/ui-styling-standards.md`
- **Animation Patterns** `../../ui/web/animation-patterns.md`
- **Delegation Workflow** `../../core/workflows/task-delegation-basics.md`
- **React Patterns** `react/react-patterns.md`

View File

@@ -0,0 +1,75 @@
<!-- Context: development/navigation | Priority: low | Version: 1.0 | Updated: 2026-02-15 -->
# Full-Stack Development Navigation
**Scope**: End-to-end application development
---
## Common Stacks
### MERN (MongoDB, Express, React, Node)
```
Frontend: development/frontend/react/ [future]
Backend: development/backend/nodejs/express-patterns.md [future]
Data: development/data/nosql-patterns/mongodb.md [future]
API: development/backend/api-patterns/rest-design.md [future]
```
### T3 Stack (Next.js, tRPC, Prisma, Tailwind)
```
Frontend: development/frontend/react/ + ui/web/ui-styling-standards.md [future]
Backend: development/backend/nodejs/ + api-patterns/trpc-patterns.md [future]
Data: development/data/orm-patterns/prisma.md [future]
```
### Python Full-Stack (FastAPI + React)
```
Frontend: development/frontend/react/ [future]
Backend: development/backend/python/fastapi-patterns.md [future]
Data: development/data/sql-patterns/ or nosql-patterns/ [future]
API: development/backend/api-patterns/rest-design.md [future]
```
---
## Quick Routes
| Layer | Navigate To |
|-------|-------------|
| **Frontend** | `ui-navigation.md` |
| **Backend** | `backend-navigation.md` |
| **Data** | `data/navigation.md` [future] |
| **Integration** | `integration/navigation.md` [future] |
| **Infrastructure** | `infrastructure/navigation.md` [future] |
---
## Common Workflows
**New API endpoint**:
1. `principles/api-design.md` (principles)
2. `backend/api-patterns/rest-design.md` (approach) [future]
3. `backend/nodejs/express-patterns.md` (implementation) [future]
**New React feature**:
1. `frontend/react/component-architecture.md` (structure) [future]
2. `frontend/react/hooks-patterns.md` (logic) [future]
3. `ui/web/ui-styling-standards.md` (styling)
**Database integration**:
1. `data/sql-patterns/` or `data/nosql-patterns/` (approach) [future]
2. `data/orm-patterns/` (if using ORM) [future]
3. `backend/nodejs/` or `backend/python/` (implementation) [future]
**Third-party service**:
1. `integration/third-party-services/` (patterns) [future]
2. `integration/api-integration/` (consuming APIs) [future]
---
## Related Context
- **Clean Code** → `principles/clean-code.md`
- **API Design** → `principles/api-design.md`
- **Core Standards** → `../core/standards/navigation.md`

View File

@@ -0,0 +1,33 @@
<!-- Context: development/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
# Infrastructure Navigation
**Purpose**: DevOps and deployment patterns
**Status**: 🚧 Placeholder - Content coming soon
---
## Planned Structure
```
infrastructure/
├── navigation.md
├── docker/
│ ├── dockerfile-patterns.md
│ ├── compose-patterns.md
│ └── optimization.md
└── ci-cd/
├── github-actions.md
├── deployment-patterns.md
└── testing-pipelines.md
```
---
## Related Context
- **Core Standards** → `../../core/standards/code-quality.md`
- **Testing** → `../../core/standards/test-coverage.md`

View File

@@ -0,0 +1,38 @@
<!-- Context: development/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
# Integration Navigation
**Purpose**: Connecting systems and services
**Status**: 🚧 Placeholder - Content coming soon
---
## Planned Structure
```
integration/
├── navigation.md
├── package-management/
│ ├── npm-patterns.md
│ ├── pnpm-patterns.md
│ └── monorepo-patterns.md
├── api-integration/
│ ├── rest-client-patterns.md
│ ├── error-handling.md
│ └── retry-strategies.md
└── third-party-services/
├── stripe-integration.md
├── sendgrid-integration.md
└── cloudinary-integration.md
```
---
## Related Context
- **Backend Navigation** → `../backend-navigation.md`
- **API Design** → `../principles/api-design.md`

View File

@@ -0,0 +1,94 @@
<!-- Context: development/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
# Development Navigation
**Purpose**: Software development across all stacks
---
## Structure
```
development/
├── navigation.md
├── ui-navigation.md # Specialized
├── backend-navigation.md # Specialized
├── fullstack-navigation.md # Specialized
├── principles/ # Universal (language-agnostic)
│ ├── navigation.md
│ ├── clean-code.md
│ └── api-design.md
├── frameworks/ # Full-stack frameworks
│ ├── navigation.md
│ └── tanstack-start/
├── ai/ # AI & Agents
│ ├── navigation.md
│ └── mastra-ai/
├── frontend/ # Client-side
│ ├── navigation.md
│ ├── when-to-delegate.md # When to use frontend-specialist
│ └── react/
│ ├── navigation.md
│ └── react-patterns.md
├── backend/ # Server-side (future)
│ ├── navigation.md
│ ├── api-patterns/
│ ├── nodejs/
│ ├── python/
│ └── authentication/
├── data/ # Data layer (future)
│ ├── navigation.md
│ ├── sql-patterns/
│ ├── nosql-patterns/
│ └── orm-patterns/
├── integration/ # Connecting systems (future)
│ ├── navigation.md
│ ├── package-management/
│ ├── api-integration/
│ └── third-party-services/
└── infrastructure/ # DevOps (future)
├── navigation.md
├── docker/
└── ci-cd/
```
---
## Quick Routes
| Task | Path |
|------|------|
| **UI/Frontend** | `ui-navigation.md` |
| **When to delegate frontend** | `frontend/when-to-delegate.md` |
| **Backend/API** | `backend-navigation.md` |
| **Full-stack** | `fullstack-navigation.md` |
| **Clean code** | `principles/clean-code.md` |
| **API design** | `principles/api-design.md` |
---
## By Concern
**Principles** → Universal development practices
**Frameworks** → Full-stack frameworks (Tanstack Start, Next.js)
**AI** → AI frameworks and agent runtimes (MAStra AI)
**Frontend** → React patterns and component design
**Backend** → APIs, Node.js, Python, auth (future)
**Data** → SQL, NoSQL, ORMs (future)
**Integration** → Packages, APIs, services (future)
**Infrastructure** → Docker, CI/CD (future)
---
## Related Context
- **Core Standards** → `../core/standards/navigation.md`
- **UI Patterns** → `../ui/navigation.md`

View File

@@ -0,0 +1,417 @@
<!-- Context: development/api-design | Priority: low | Version: 1.0 | Updated: 2026-02-15 -->
# API Design Patterns
**Category**: development
**Purpose**: REST API design principles, GraphQL patterns, and API versioning strategies
**Used by**: opencoder
---
## Overview
This guide covers best practices for designing robust, scalable, and maintainable APIs, including REST, GraphQL, and versioning strategies.
## REST API Design
### 1. Resource-Based URLs
**Use nouns, not verbs**:
```
# Bad
GET /getUsers
POST /createUser
POST /updateUser/123
# Good
GET /users
POST /users
PUT /users/123
PATCH /users/123
DELETE /users/123
```
### 2. HTTP Methods
**Use appropriate HTTP methods**:
- `GET` - Retrieve resources (idempotent, safe)
- `POST` - Create new resources
- `PUT` - Replace entire resource (idempotent)
- `PATCH` - Partial update (idempotent)
- `DELETE` - Remove resource (idempotent)
### 3. Status Codes
**Use standard HTTP status codes**:
```
2xx Success
200 OK - Successful GET, PUT, PATCH
201 Created - Successful POST
204 No Content - Successful DELETE
4xx Client Errors
400 Bad Request - Invalid input
401 Unauthorized - Missing/invalid auth
403 Forbidden - Authenticated but not authorized
404 Not Found - Resource doesn't exist
409 Conflict - Resource conflict (e.g., duplicate)
422 Unprocessable Entity - Validation errors
5xx Server Errors
500 Internal Server Error - Unexpected error
503 Service Unavailable - Temporary unavailability
```
### 4. Consistent Response Format
**Standardize response structure**:
```json
// Success response
{
"data": {
"id": "123",
"name": "John Doe",
"email": "john@example.com"
},
"meta": {
"timestamp": "2024-01-01T00:00:00Z"
}
}
// Error response
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input data",
"details": [
{
"field": "email",
"message": "Invalid email format"
}
]
},
"meta": {
"timestamp": "2024-01-01T00:00:00Z",
"requestId": "abc-123"
}
}
// Collection response
{
"data": [...],
"meta": {
"total": 100,
"page": 1,
"pageSize": 20,
"totalPages": 5
},
"links": {
"self": "/users?page=1",
"next": "/users?page=2",
"prev": null,
"first": "/users?page=1",
"last": "/users?page=5"
}
}
```
### 5. Filtering, Sorting, Pagination
**Support common query operations**:
```
# Filtering
GET /users?status=active&role=admin
# Sorting
GET /users?sort=createdAt:desc,name:asc
# Pagination
GET /users?page=2&pageSize=20
# Field selection
GET /users?fields=id,name,email
# Search
GET /users?q=john
```
### 6. Nested Resources
**Handle relationships appropriately**:
```
# Good - Shallow nesting
GET /users/123/posts
GET /posts?userId=123
# Avoid - Deep nesting
GET /users/123/posts/456/comments/789
# Better
GET /comments/789
```
## GraphQL Patterns
### 1. Schema Design
**Design clear, intuitive schemas**:
```graphql
type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
createdAt: DateTime!
}
type Post {
id: ID!
title: String!
content: String!
author: User!
comments: [Comment!]!
publishedAt: DateTime
}
type Query {
user(id: ID!): User
users(filter: UserFilter, page: Int, pageSize: Int): UserConnection!
post(id: ID!): Post
}
type Mutation {
createUser(input: CreateUserInput!): User!
updateUser(id: ID!, input: UpdateUserInput!): User!
deleteUser(id: ID!): Boolean!
}
input CreateUserInput {
name: String!
email: String!
}
input UserFilter {
status: UserStatus
role: UserRole
search: String
}
```
### 2. Resolver Patterns
**Implement efficient resolvers**:
```javascript
const resolvers = {
Query: {
user: async (_, { id }, { dataSources }) => {
return dataSources.userAPI.getUser(id);
},
users: async (_, { filter, page, pageSize }, { dataSources }) => {
return dataSources.userAPI.getUsers({ filter, page, pageSize });
}
},
User: {
posts: async (user, _, { dataSources }) => {
// Use DataLoader to batch requests
return dataSources.postAPI.getPostsByUserId(user.id);
}
},
Mutation: {
createUser: async (_, { input }, { dataSources, user }) => {
// Check authorization
if (!user) throw new AuthenticationError('Not authenticated');
// Validate input
const validatedInput = validateUserInput(input);
// Create user
return dataSources.userAPI.createUser(validatedInput);
}
}
};
```
### 3. DataLoader for N+1 Prevention
**Batch and cache database queries**:
```javascript
import DataLoader from 'dataloader';
const userLoader = new DataLoader(async (userIds) => {
const users = await db.users.findMany({
where: { id: { in: userIds } }
});
// Return in same order as input
return userIds.map(id => users.find(u => u.id === id));
});
// Usage in resolver
const user = await userLoader.load(userId);
```
## Frontend API Client Patterns (TanStack Query)
**Use TanStack Query for optimal client-side API consumption**:
### REST Integration
```javascript
// Optimal REST client with TanStack Query v5
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
const apiClient = {
getUsers: (filters) =>
fetch(`/api/v1/users?${new URLSearchParams(filters)}`).then(r => r.json())
};
function UsersList() {
const { data, isPending, error } = useQuery({
queryKey: ['users', filters],
queryFn: () => apiClient.getUsers(filters),
staleTime: 5 * 60 * 1000, // 5 minutes
});
return (
<div>
{isPending && <div>Loading...</div>}
{error && <div>Error: {error.message}</div>}
{data?.data.map(user => <UserCard key={user.id} user={user} />)}
</div>
);
}
## API Versioning
### 1. URL Versioning
**Version in the URL path**:
```
GET /v1/users
GET /v2/users
```
**Pros**: Clear, easy to route
**Cons**: URL changes, harder to maintain multiple versions
### 2. Header Versioning
**Version in Accept header**:
```
GET /users
Accept: application/vnd.myapi.v2+json
```
**Pros**: Clean URLs, flexible
**Cons**: Less visible, harder to test
### 3. Deprecation Strategy
**Communicate deprecation clearly**:
```javascript
// Response headers
Deprecation: true
Sunset: Sat, 31 Dec 2024 23:59:59 GMT
Link: <https://api.example.com/v2/users>; rel="successor-version"
// Response body
{
"data": {...},
"meta": {
"deprecated": true,
"deprecationDate": "2024-12-31",
"migrationGuide": "https://docs.example.com/migration/v1-to-v2"
}
}
```
## Authentication & Authorization
### 1. JWT Tokens
**Use JWT for stateless auth**:
```javascript
// Token structure
{
"sub": "user-123",
"email": "user@example.com",
"role": "admin",
"iat": 1516239022,
"exp": 1516242622
}
// Middleware
function authenticateToken(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (error) {
return res.status(401).json({ error: 'Invalid token' });
}
}
```
### 2. Role-Based Access Control
**Implement RBAC**:
```javascript
function authorize(...roles) {
return (req, res, next) => {
if (!req.user) {
return res.status(401).json({ error: 'Not authenticated' });
}
if (!roles.includes(req.user.role)) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
next();
};
}
// Usage
app.delete('/users/:id',
authenticateToken,
authorize('admin'),
deleteUser
);
```
## Best Practices
1. **Use HTTPS everywhere** - Encrypt all API traffic
2. **Implement rate limiting** - Prevent abuse and ensure fair usage
3. **Validate all inputs** - Never trust client data
4. **Use proper error handling** - Return meaningful error messages
5. **Document your API** - Use OpenAPI/Swagger or GraphQL introspection
6. **Version your API** - Plan for breaking changes
7. **Implement CORS properly** - Configure allowed origins carefully
8. **Log requests and errors** - Enable debugging and monitoring
9. **Use caching** - Implement ETags, Cache-Control headers
10. **Test thoroughly** - Unit, integration, and contract tests
## Anti-Patterns
-**Exposing internal IDs** - Use UUIDs or opaque identifiers
-**Returning too much data** - Support field selection
-**Ignoring idempotency** - PUT/PATCH/DELETE should be idempotent
-**Inconsistent naming** - Use camelCase or snake_case consistently
-**Missing pagination** - Always paginate collections
-**No rate limiting** - Protect against abuse
-**Verbose error messages** - Don't leak implementation details
-**Synchronous long operations** - Use async jobs for long tasks
## References
- REST API Design Rulebook by Mark Masse
- GraphQL Best Practices (graphql.org)
- API Design Patterns by JJ Geewax
- OpenAPI Specification (swagger.io)

View File

@@ -0,0 +1,178 @@
<!-- Context: development/clean-code | Priority: low | Version: 1.0 | Updated: 2026-02-15 -->
# Clean Code Principles
**Category**: development
**Purpose**: Core coding standards and best practices for writing clean, maintainable code
**Used by**: frontend-specialist, devops-specialist, opencoder
---
## Overview
Clean code is code that is easy to read, understand, and maintain. It follows consistent patterns, uses meaningful names, and is well-organized. This guide provides principles and patterns for writing clean code across all languages.
## Core Principles
### 1. Meaningful Names
**Use intention-revealing names**:
- Variable names should reveal intent
- Function names should describe what they do
- Class names should describe what they represent
**Examples**:
```javascript
// Bad
const d = new Date();
const x = getUserData();
// Good
const currentDate = new Date();
const activeUserProfile = getUserData();
```
### 2. Functions Should Do One Thing
**Single Responsibility**:
- Each function should have one clear purpose
- Functions should be small (ideally < 20 lines)
- Extract complex logic into separate functions
**Example**:
```javascript
// Bad
function processUser(user) {
validateUser(user);
saveToDatabase(user);
sendEmail(user);
logActivity(user);
}
// Good
function processUser(user) {
const validatedUser = validateUser(user);
const savedUser = saveUserToDatabase(validatedUser);
notifyUser(savedUser);
return savedUser;
}
```
### 3. Avoid Deep Nesting
**Keep nesting shallow**:
- Use early returns
- Extract nested logic into functions
- Prefer guard clauses
**Example**:
```javascript
// Bad
function processOrder(order) {
if (order) {
if (order.items.length > 0) {
if (order.total > 0) {
// process order
}
}
}
}
// Good
function processOrder(order) {
if (!order) return;
if (order.items.length === 0) return;
if (order.total <= 0) return;
// process order
}
```
### 4. DRY (Don't Repeat Yourself)
**Eliminate duplication**:
- Extract common logic into reusable functions
- Use composition over inheritance
- Create utility functions for repeated patterns
### 5. Error Handling
**Handle errors explicitly**:
- Use try-catch for expected errors
- Provide meaningful error messages
- Don't ignore errors silently
**Example**:
```javascript
// Bad
function fetchData() {
try {
return api.getData();
} catch (e) {
return null;
}
}
// Good
async function fetchData() {
try {
return await api.getData();
} catch (error) {
logger.error('Failed to fetch data', { error });
throw new DataFetchError('Unable to retrieve data', { cause: error });
}
}
```
## Best Practices
1. **Write self-documenting code** - Code should explain itself through clear naming and structure
2. **Keep functions pure when possible** - Avoid side effects, return new values instead of mutating
3. **Use consistent formatting** - Follow language-specific style guides (Prettier, ESLint, etc.)
4. **Write tests first** - TDD helps design better APIs and catch issues early
5. **Refactor regularly** - Improve code structure as you learn more about the domain
6. **Comment why, not what** - Code shows what, comments explain why
7. **Use type systems** - TypeScript, type hints, or static analysis tools
8. **Favor composition** - Build complex behavior from simple, reusable pieces
## Anti-Patterns
- **Magic numbers** - Use named constants instead of hardcoded values
- **God objects** - Classes that do too much or know too much
- **Premature optimization** - Optimize for readability first, performance second
- **Clever code** - Simple and clear beats clever and complex
- **Long parameter lists** - Use objects or configuration patterns instead
- **Boolean flags** - Often indicate a function doing multiple things
- **Mutable global state** - Leads to unpredictable behavior and bugs
## Language-Specific Guidelines
### JavaScript/TypeScript
- Use `const` by default, `let` when needed, never `var`
- Prefer arrow functions for callbacks
- Use async/await over raw promises
- Destructure objects and arrays for clarity
### Python
- Follow PEP 8 style guide
- Use list comprehensions for simple transformations
- Prefer context managers (`with` statements)
- Use type hints for function signatures
### Go
- Follow effective Go guidelines
- Use defer for cleanup
- Handle errors explicitly
- Keep interfaces small
### Rust
- Embrace ownership and borrowing
- Use pattern matching
- Prefer iterators over loops
- Handle errors with Result types
## References
- Clean Code by Robert C. Martin
- The Pragmatic Programmer by Hunt & Thomas
- Refactoring by Martin Fowler

View File

@@ -0,0 +1,46 @@
<!-- Context: development/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
# Development Principles Navigation
**Purpose**: Universal development principles (language-agnostic)
---
## Files
| File | Topic | Priority | Load When |
|------|-------|----------|-----------|
| `clean-code.md` | Clean code practices | ⭐⭐⭐⭐ | Writing any code |
| `api-design.md` | API design principles | ⭐⭐⭐⭐ | Designing APIs |
---
## Loading Strategy
**For general development**:
1. Load `clean-code.md` (high)
2. Also load: `../../core/standards/code-quality.md` (critical)
**For API development**:
1. Load `api-design.md` (high)
2. Also load: `../../core/standards/code-quality.md` (critical)
---
## Scope
**This directory**: Development-specific principles
**Core standards**: Universal standards (all projects, all languages)
| Location | Scope | Examples |
|----------|-------|----------|
| `core/standards/` | **Universal** (all projects) | Code quality, testing, docs, security |
| `development/principles/` | **Development-specific** | Clean code, API design, error handling |
---
## Related
- **Core Standards** → `../../core/standards/navigation.md`
- **Backend Patterns** → `../backend-navigation.md`
- **Frontend Patterns** → `../ui-navigation.md`

View File

@@ -0,0 +1,53 @@
<!-- Context: development/navigation | Priority: low | Version: 1.0 | Updated: 2026-02-15 -->
# UI Development Navigation
**Scope**: Frontend code + visual design
---
## Structure
```
Frontend Code (development/frontend/):
└── react/
├── navigation.md
└── react-patterns.md
Visual Design (ui/web/):
├── animation-patterns.md
├── ui-styling-standards.md
├── design-systems.md
└── design/
├── concepts/
└── examples/
```
---
## Quick Routes
| Task | Path |
|------|------|
| **React patterns** | `frontend/react/react-patterns.md` |
| **Animations** | `../../ui/web/animation-patterns.md` |
| **Styling** | `../../ui/web/ui-styling-standards.md` |
| **Design systems** | `../../ui/web/design-systems.md` |
---
## By Framework
**React**`frontend/react/`
## By Concern
**Code patterns**`development/frontend/`
**Visual design**`ui/web/`
---
## Related Context
- **Core Standards** → `../core/standards/code-quality.md`
- **UI Category** → `../ui/navigation.md`