Skip to content

Latest commit

 

History

History
343 lines (253 loc) · 7.79 KB

AGENTS.md

File metadata and controls

343 lines (253 loc) · 7.79 KB

Project Instructions

This file provides instructions and guidelines for working with OpenCode on this project.

Table of Contents


Available Agents

Agent Purpose When to Use
planner Implementation planning Complex features, refactoring
architect System design Architectural decisions
tdd-guide Test-driven development New features, bug fixes
code-reviewer Code review After writing code
security-reviewer Security analysis Before commits
build-error-resolver Fix build errors When build fails
e2e-runner E2E testing Critical user flows
refactor-cleaner Dead code cleanup Code maintenance
doc-updater Documentation Updating docs

Agent Usage Guidelines

Immediate Usage (Without User Prompt)

ALWAYS invoke these agents proactively:

  • planner: When request involves multiple files or complex logic
  • tdd-guide: When writing new code or fixing bugs
  • code-reviewer: Immediately after any code modification
  • security-reviewer: When touching auth, APIs, or sensitive data
  • build-error-resolver: When build or type errors occur

Parallel Usage (Multi-Perspective Analysis)

For complex decisions, run agents in parallel:

User: "Add user authentication"

Invoke simultaneously:
- planner: Break down implementation steps
- architect: Design authentication system
- security-reviewer: Identify security requirements
- tdd-guide: Define test requirements

Coding Style

Core Principles

  1. MANY SMALL FILES - Keep files between 200-400 lines (800 max)
  2. Immutability - ALWAYS use spread operator, NEVER mutate directly
  3. Comprehensive Error Handling - Every async operation wrapped in try/catch
  4. Input Validation - All inputs validated at system boundaries

Immutability Pattern (CRITICAL)

// CORRECT: Immutability
function updateUser(user, name) {
  return {
    ...user,
    name
  }
}

// WRONG: Mutation
function updateUser(user, name) {
  user.name = name  // NEVER DO THIS
  return user
}

File Organization

src/
├── app/                    # Next.js App Router
│   ├── api/               # API routes
│   └── (pages)/           # Page components
├── components/            # React components
│   ├── ui/               # Generic UI components
│   └── forms/            # Form components
├── hooks/                # Custom React hooks
├── lib/                  # Utilities and configs
├── types/                # TypeScript types
└── styles/              # Global styles

Naming Conventions

  • Files: kebab-case.ts for utilities, PascalCase.tsx for components
  • Functions: camelCase, verb-noun pattern (e.g., fetchMarkets, calculateTotal)
  • Constants: SCREAMING_SNAKE_CASE
  • Types/Interfaces: PascalCase

Security Requirements

Mandatory Security Checks

BEFORE any code change, verify:

  1. No Hardcoded Secrets

    • API keys in environment variables
    • No credentials in source code
    • .env.local in .gitignore
  2. Input Validation

    • All user inputs validated with schemas (Zod)
    • File uploads restricted (size, type)
    • SQL injection prevention (parameterized queries)
  3. Authentication/Authorization

    • Tokens in httpOnly cookies
    • Authorization checks on every route
    • Row Level Security in Supabase

Secret Management

// ALWAYS: Environment variables
const apiKey = process.env.OPENAI_API_KEY

if (!apiKey) {
  throw new Error('OPENAI_API_KEY not configured')
}

// NEVER: Hardcoded secrets
const apiKey = "sk-abc123..."  // PROHIBITED

Security Response Protocol

If security vulnerability found:

  1. STOP current implementation
  2. DOCUMENT the vulnerability
  3. FIX before proceeding
  4. VERIFY fix is complete
  5. REVIEW with security-reviewer agent

Testing Requirements

Minimum Test Coverage: 80%

Test Types (ALL required):

  1. Unit Tests - Individual functions, utilities, components
  2. Integration Tests - API endpoints, database operations
  3. E2E Tests - Critical user flows (Playwright)

Test-Driven Development (MANDATORY)

1. Write test first (RED)
2. Run test - it should FAIL
3. Write minimal implementation (GREEN)
4. Run test - it should PASS
5. Refactor (IMPROVE)
6. Verify coverage (80%+)

Test Structure (AAA Pattern)

test('calculates similarity correctly', () => {
  // Arrange
  const vector1 = [1, 0, 0]
  const vector2 = [0, 1, 0]

  // Act
  const similarity = calculateCosineSimilarity(vector1, vector2)

  // Assert
  expect(similarity).toBe(0)
})

Common Patterns

API Response Format

interface ApiResponse<T> {
  success: boolean
  data?: T
  error?: string
  meta?: {
    total: number
    page: number
    limit: number
  }
}

Custom Hooks Pattern

export function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value)

  useEffect(() => {
    const handler = setTimeout(() => setDebouncedValue(value), delay)
    return () => clearTimeout(handler)
  }, [value, delay])

  return debouncedValue
}

Error Handling Pattern

async function fetchData(url: string) {
  try {
    const response = await fetch(url)

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }

    return await response.json()
  } catch (error) {
    console.error('Fetch failed:', error)
    throw new Error('Failed to fetch data')
  }
}

Performance Guidelines

Model Selection

  • Fast tasks: Use faster models for simple operations
  • Complex tasks: Use advanced models for architecture, planning
  • Code generation: Balance speed and quality

Context Management

Avoid large context windows for:

  • Large-scale refactoring
  • Feature implementation spanning multiple files
  • Debugging complex interactions

Good for lower context:

  • Single-file edits
  • Independent utility creation
  • Documentation updates
  • Simple bug fixes

Build Troubleshooting

If build fails:

  1. Use build-error-resolver agent
  2. Analyze error messages
  3. Fix incrementally
  4. Verify after each fix

Git Workflow

Commit Message Format (Conventional Commits)

<type>(<scope>): <description>

[optional body]

[optional footer]

Types:

  • feat: New feature
  • fix: Bug fix
  • docs: Documentation
  • style: Formatting
  • refactor: Code refactoring
  • test: Tests
  • chore: Maintenance

Branch Naming

<type>/<short-description>

Examples:

  • feat/add-google-auth
  • fix/handle-null-responses
  • docs/update-readme

Protected Branches

  • main (or master): Production-ready code
  • Direct commits NOT allowed
  • All changes through Pull Requests

Quick Reference

Commands Available

  • /plan - Create implementation plan
  • /tdd - Test-driven development workflow
  • /code-review - Review uncommitted changes
  • /build-fix - Fix build errors
  • /e2e - Run end-to-end tests
  • /verify - Run verification checks

Skills Available

  • backend-patterns - API and database patterns
  • frontend-patterns - React and Next.js patterns
  • tdd-workflow - Test-driven development
  • security-review - Security best practices
  • coding-standards - General coding guidelines

Remember: Quality over speed. Test before implementation. Security is not optional.