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,152 @@
<!-- Context: standards/analysis | Priority: high | Version: 2.0 | Updated: 2025-01-21 -->
# Analysis Guidelines
## Quick Reference
**Process**: Context → Gather → Patterns → Impact → Recommendations
**Report Format**: Context, Findings, Patterns, Issues (🔴🟡🔵), Recommendations, Trade-offs, Next Steps
**Be**: Thorough, Objective, Specific, Actionable
**Checklist**: Context stated, Evidence gathered, Patterns identified, Issues prioritized, Recommendations specific, Trade-offs considered
---
## Purpose
Framework for analyzing code, patterns, and technical issues systematically.
## When to Use
Reference this when:
- Analyzing codebase patterns
- Investigating bugs or issues
- Evaluating architectural decisions
- Assessing code quality
- Researching solutions
## Analysis Process
### 1. Understand Context
- What are we analyzing and why?
- What's the goal or question?
- What's the scope?
- What constraints exist?
### 2. Gather Information
- Read relevant code / data points
- Check documentation
- Search for patterns
- Review related issues
- Examine dependencies
### 3. Identify Patterns
- What's consistent across the codebase?
- What conventions are followed?
- What patterns are repeated?
- What's inconsistent or unusual?
### 4. Assess Impact
- What are the implications?
- What are the trade-offs?
- What could break?
- What are the risks?
### 5. Provide Recommendations
- What should be done?
- Why this approach?
- What are alternatives?
- What's the priority?
## Analysis Report Format
```markdown
## Analysis: {Topic}
**Context:** {What we're analyzing and why}
**Findings:**
- {Key finding 1}
- {Key finding 2}
- {Key finding 3}
**Patterns Observed:**
- {Pattern 1}: {Description}
- {Pattern 2}: {Description}
**Issues Identified:**
- 🔴 Critical: {Issue requiring immediate attention}
- 🟡 Warning: {Issue to address soon}
- 🔵 Suggestion: {Nice-to-have improvement}
**Recommendations:**
1. {Recommendation 1} - {Why}
2. {Recommendation 2} - {Why}
**Trade-offs:**
- {Approach A}: {Pros/Cons}
- {Approach B}: {Pros/Cons}
**Next Steps:**
- {Action 1}
- {Action 2}
```
## Common Analysis Types
### Code Quality Analysis
- Complexity (cyclomatic, cognitive)
- Duplication
- Test coverage
- Documentation completeness
- Naming consistency
- Error handling patterns
### Architecture Analysis
- Module dependencies
- Coupling and cohesion
- Separation of concerns
- Scalability considerations
- Performance bottlenecks
### Bug Investigation
- Reproduce the issue
- Identify root cause
- Assess impact and severity
- Propose fix with rationale
- Consider edge cases
### Pattern Discovery
- Search for similar implementations
- Identify common approaches
- Document conventions
- Note inconsistencies
- Recommend standardization
## Best Practices
### Be Thorough
- Check multiple examples
- Consider edge cases
- Look for exceptions
- Verify assumptions
### Be Objective
- Base conclusions on evidence
- Avoid assumptions
- Consider multiple perspectives
- Acknowledge limitations
### Be Specific
- Provide concrete examples
- Include file names and line numbers
- Show code snippets
- Quantify when possible
### Be Actionable
- Clear recommendations
- Prioritize findings
- Explain rationale
- Suggest next steps

View File

@@ -0,0 +1,164 @@
<!-- Context: standards/code | Priority: critical | Version: 2.0 | Updated: 2025-01-21 -->
# Code Standards
## Quick Reference
**Core Philosophy**: Modular, Functional, Maintainable
**Golden Rule**: If you can't easily test it, refactor it
**Critical Patterns** (use these):
- ✅ Pure functions (same input = same output, no side effects)
- ✅ Immutability (create new data, don't modify)
- ✅ Composition (build complex from simple)
- ✅ Small functions (< 50 lines)
- Explicit dependencies (dependency injection)
**Anti-Patterns** (avoid these):
- Mutation, side effects, deep nesting
- God modules, global state, large functions
---
## Core Philosophy
**Modular**: Everything is a component - small, focused, reusable
**Functional**: Pure functions, immutability, composition over inheritance
**Maintainable**: Self-documenting, testable, predictable
## Principles
### Modular Design
- Single responsibility per module
- Clear interfaces (explicit inputs/outputs)
- Independent and composable
- < 100 lines per component (ideally < 50)
### Functional Approach
- **Pure functions**: Same input = same output, no side effects
- **Immutability**: Create new data, don't modify existing
- **Composition**: Build complex from simple functions
- **Declarative**: Describe what, not how
### Component Structure
```
component/
├── index.js # Public interface
├── core.js # Core logic (pure functions)
├── utils.js # Helpers
└── tests/ # Tests
```
## Patterns
### Pure Functions
```javascript
// ✅ Pure
const add = (a, b) => a + b;
const formatUser = (user) => ({ ...user, fullName: `${user.firstName} ${user.lastName}` });
// ❌ Impure (side effects)
let total = 0;
const addToTotal = (value) => { total += value; return total; };
```
### Immutability
```javascript
// ✅ Immutable
const addItem = (items, item) => [...items, item];
const updateUser = (user, changes) => ({ ...user, ...changes });
// ❌ Mutable
const addItem = (items, item) => { items.push(item); return items; };
```
### Composition
```javascript
// ✅ Compose small functions
const processUser = pipe(validateUser, enrichUserData, saveUser);
const isValidEmail = (email) => validateEmail(normalizeEmail(email));
// ❌ Deep inheritance
class ExtendedUserManagerWithValidation extends UserManager { }
```
### Declarative
```javascript
// ✅ Declarative
const activeUsers = users.filter(u => u.isActive).map(u => u.name);
// ❌ Imperative
const names = [];
for (let i = 0; i < users.length; i++) {
if (users[i].isActive) names.push(users[i].name);
}
```
## Naming
- **Files**: lowercase-with-dashes.js
- **Functions**: verbPhrases (getUser, validateEmail)
- **Predicates**: isValid, hasPermission, canAccess
- **Variables**: descriptive (userCount not uc), const by default
- **Constants**: UPPER_SNAKE_CASE
## Error Handling
```javascript
// ✅ Explicit error handling
function parseJSON(text) {
try {
return { success: true, data: JSON.parse(text) };
} catch (error) {
return { success: false, error: error.message };
}
}
// ✅ Validate at boundaries
function createUser(userData) {
const validation = validateUserData(userData);
if (!validation.isValid) {
return { success: false, errors: validation.errors };
}
return { success: true, user: saveUser(userData) };
}
```
## Dependency Injection
```javascript
// ✅ Dependencies explicit
function createUserService(database, logger) {
return {
createUser: (userData) => {
logger.info('Creating user');
return database.insert('users', userData);
}
};
}
// ❌ Hidden dependencies
import db from './database.js';
function createUser(userData) { return db.insert('users', userData); }
```
## Anti-Patterns
**Mutation**: Modifying data in place
**Side effects**: console.log, API calls in pure functions
**Deep nesting**: Use early returns instead
**God modules**: Split into focused modules
**Global state**: Pass dependencies explicitly
**Large functions**: Keep < 50 lines
## Best Practices
Pure functions whenever possible
Immutable data structures
Small, focused functions (< 50 lines)
Compose small functions into larger ones
Explicit dependencies (dependency injection)
Validate at boundaries
Self-documenting code
Test in isolation
**Golden Rule**: If you can't easily test it, refactor it.

View File

@@ -0,0 +1,150 @@
<!-- Context: standards/docs | Priority: critical | Version: 2.0 | Updated: 2025-01-21 -->
# Documentation Standards
## Quick Reference
**Golden Rule**: If users ask the same question twice, document it
**Document** (✅ DO):
- WHY decisions were made
- Complex algorithms/logic
- Public APIs, setup, common use cases
**Don't Document** (❌ DON'T):
- Obvious code (i++ doesn't need comment)
- What code does (should be self-explanatory)
**Principles**: Audience-focused, Show don't tell, Keep current
---
## Principles
**Audience-focused**: Write for users (what/how), developers (why/when), contributors (setup/conventions)
**Show, don't tell**: Code examples, real use cases, expected output
**Keep current**: Update with code changes, remove outdated info, mark deprecations
## README Structure
```markdown
# Project Name
Brief description (1-2 sentences)
## Features
- Key feature 1
- Key feature 2
## Installation
```bash
bun --bun install package-name
```
## Quick Start
```javascript
const result = doSomething();
```
## Usage
[Detailed examples]
## API Reference
[If applicable]
## Contributing
[Link to CONTRIBUTING.md]
## License
[License type]
```
## Function Documentation
```javascript
/**
* Calculate total price including tax
*
* @param {number} price - Base price
* @param {number} taxRate - Tax rate (0-1)
* @returns {number} Total with tax
*
* @example
* calculateTotal(100, 0.1) // 110
*/
function calculateTotal(price, taxRate) {
return price * (1 + taxRate);
}
```
## What to Document
### ✅ DO
- **WHY** decisions were made
- Complex algorithms/logic
- Non-obvious behavior
- Public APIs
- Setup/installation
- Common use cases
- Known limitations
- Workarounds (with explanation)
### ❌ DON'T
- Obvious code (i++ doesn't need comment)
- What code does (should be self-explanatory)
- Redundant information
- Outdated/incorrect info
## Comments
### Good
```javascript
// Calculate discount by tier (Bronze: 5%, Silver: 10%, Gold: 15%)
const discount = getDiscountByTier(customer.tier);
// HACK: API returns null instead of [], normalize it
const items = response.items || [];
// TODO: Use async/await when Node 18+ is minimum
```
### Bad
```javascript
// Increment i
i++;
// Get user
const user = getUser();
```
## API Documentation
```markdown
### POST /api/users
Create a new user
**Request:**
```json
{ "name": "John", "email": "john@example.com" }
```
**Response:**
```json
{ "id": "123", "name": "John", "email": "john@example.com" }
```
**Errors:**
- 400 - Invalid input
- 409 - Email exists
```
## Best Practices
✅ Explain WHY, not just WHAT
✅ Include working examples
✅ Show expected output
✅ Cover error handling
✅ Use consistent terminology
✅ Keep structure predictable
✅ Update when code changes
**Golden Rule**: If users ask the same question twice, document it.

View File

@@ -0,0 +1,66 @@
<!-- Context: core/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
# Core Standards Navigation
**Purpose**: Universal standards for all development work
---
## Files
| File | Topic | Priority | Load When |
|------|-------|----------|-----------|
| `code-quality.md` | Code quality rules | ⭐⭐⭐⭐⭐ | Writing/reviewing code |
| `test-coverage.md` | Testing standards | ⭐⭐⭐⭐⭐ | Writing tests |
| `documentation.md` | Documentation rules | ⭐⭐⭐⭐ | Writing docs |
| `security-patterns.md` | Security best practices | ⭐⭐⭐⭐ | Security review, patterns |
| `project-intelligence.md` | What and why | ⭐⭐⭐⭐ | Onboarding, understanding projects |
| `project-intelligence-management.md` | How to manage | ⭐⭐⭐ | Managing intelligence files |
| `code-analysis.md` | Analysis approaches | ⭐⭐⭐ | Analyzing code, debugging |
| `typescript.md` | Universal TypeScript patterns | ⭐⭐⭐⭐ | Writing/reviewing TypeScript code |
| `csharp.md` | Universal C# / .NET patterns | ⭐⭐⭐⭐ | Writing/reviewing C# code |
| `csharp-project-structure.md` | ASP.NET Core project structure (Minimal APIs, CQRS, EF Core + PostgreSQL) | ⭐⭐⭐⭐ | Starting or structuring a C# API project |
---
## Loading Strategy
**For code implementation**:
1. Load `code-quality.md` (critical)
2. Load `security-patterns.md` (high)
**For TypeScript code**:
1. Load `typescript.md` (critical)
2. Load `code-quality.md` (high)
**For C# / .NET code**:
1. Load `csharp.md` (critical)
2. Load `code-quality.md` (high)
**For C# API project structure**:
1. Load `csharp-project-structure.md` (critical)
2. Load `csharp.md` (high)
**For testing**:
1. Load `test-coverage.md` (critical)
2. Depends on: `code-quality.md`
**For documentation**:
1. Load `documentation.md` (critical)
**For code review**:
1. Load `code-quality.md` (critical)
2. Load `security-patterns.md` (high)
3. Load `test-coverage.md` (high)
**For project onboarding/understanding**:
1. Load `project-intelligence.md` (high)
2. Then load: `../../project-intelligence/` folder for full project context
---
## Related
- **Workflows** → `../workflows/navigation.md`
- **Development Principles** → `../../development/principles/`
- **Project Intelligence** → `../../project-intelligence/navigation.md` (full project context)

View File

@@ -0,0 +1,249 @@
<!-- Context: standards/intelligence-mgmt | Priority: high | Version: 1.0 | Updated: 2025-01-12 -->
# Project Intelligence Management
> **What**: How to manage project intelligence files and folders.
> **When**: Use this guide when adding, updating, or removing intelligence files.
> **Related**: See `project-intelligence.md` for what and why.
## Quick Reference
| Action | Do This |
|--------|---------|
| Update existing file | Edit + bump frontmatter version |
| Add new file | Create `.md` + add to navigation.md |
| Add subfolder | Create folder + `navigation.md` + update parent nav |
| Remove file | Rename `.deprecated.md` + archive, don't delete |
---
## Update Existing Files
**When**:
- Business changes → Update `business-domain.md`
- New decision → Add to `decisions-log.md`
- New issues → Update `living-notes.md`
- Feature launch → Update `business-tech-bridge.md`
- Stack changes → Update `technical-domain.md`
**Process**:
1. Edit the file
2. Update frontmatter:
```html
<!-- Context: {category} | Priority: {level} | Version: {X.Y} | Updated: {YYYY-MM-DD} -->
```
3. Keep under 200 lines
4. Commit with message like: `docs: Update business-domain.md with new market focus`
---
## Add New Files
**When**:
- New domain area needs dedicated docs
- Existing file exceeds 200 lines
- Specialized context requires separation
**Naming**:
- Kebab-case: `user-research.md`, `api-docs.md`
- Descriptive: filename tells you what's inside
**Template**:
```html
<!-- Context: project-intelligence/{filename} | Priority: {high|medium} | Version: 1.0 | Updated: {YYYY-MM-DD} -->
# File Title
> One-line purpose statement
## Quick Reference
- **Purpose**: [What this covers]
- **Update When**: [Triggers]
- **Related Files**: [Links]
## Content
[Follow patterns from existing files]
## Related Files
- [File 1] - [Description]
```
**Process**:
1. Create file in `project-intelligence/`
2. Add frontmatter with `project-intelligence/{filename}`
3. Follow existing file patterns
4. Keep under 200 lines
5. Add to `navigation.md`
---
## Create Subfolders
**When**:
- 5+ related files need grouping
- Subdomain warrants separation (e.g., `api/`, `mobile/`, `integrations/`)
- Improves navigation clarity
**Structure**:
```
project-intelligence/
├── navigation.md # Root nav
├── [new-subfolder]/ # Create this
│ ├── navigation.md # Subfolder nav required
│ ├── file-1.md
│ └── file-2.md
```
**Process**:
1. Create folder: `mkdir project-intelligence/{name}/`
2. Create `navigation.md` inside:
```html
<!-- Context: project-intelligence/{name}/nav | Priority: medium | Version: 1.0 | Updated: {YYYY-MM-DD} -->
# {Name} Navigation
> Quick overview
## Files
| File | Purpose |
|------|---------|
| `file-1.md` | [Desc] |
```
3. Add content files
4. Update root `navigation.md` with subfolder entry
**Rule**: Every subfolder MUST have `navigation.md`. Avoid nesting deeper than 2 levels (e.g., `project-intelligence/domain/subdomain/`) to prevent context fragmentation.
---
## Remove/Deprecate Files
**When**:
- Content moved elsewhere
- File no longer relevant
- Merged with another file
**Process**:
1. Rename: `filename.md` → `filename.deprecated.md`
2. Add frontmatter:
```html
<!-- DEPRECATED: {YYYY-MM-DD} - {Reason} -->
<!-- REPLACED BY: {new-file.md} -->
```
3. Add banner at top:
> ⚠️ **DEPRECATED**: See `new-file.md` for current info
4. Mark as deprecated in `navigation.md`
**Never Delete**:
- Decision history (archive instead)
- Lessons learned (move to `living-notes.md`)
- Context that might be needed later
---
## Version Tracking
**Frontmatter**:
```html
<!-- Context: {category} | Priority: {level} | Version: {MAJOR.MINOR} | Updated: {YYYY-MM-DD} -->
```
**Version Rules**:
| Change | Version |
|--------|---------|
| New file | 1.0 |
| Content addition/update | MINOR |
| Structure change | MAJOR |
| Typo fix | PATCH |
**Date**: Always `YYYY-MM-DD`
---
## Quality Standards
**Line Limits**:
- Files: <200 lines
- Sections: 3-7 per file
**Required Elements**:
- Frontmatter with all fields
- Quick Reference section
- Related files section
**Anti-Patterns**:
❌ Mix concerns in one file
❌ Exceed 200 lines
❌ Delete files (archive instead)
❌ Skip frontmatter
❌ Duplicate information
✅ Keep focused and scannable
✅ Archive deprecated content
✅ Use frontmatter consistently
✅ Link to related files
---
## Governance
**Ownership**:
| Area | Owner | Responsibility |
|------|-------|----------------|
| Business domain | Product Owner | Keep current, accurate |
| Technical domain | Tech Lead | Keep current, accurate |
| Decisions log | Tech Lead | Document decisions |
| Living notes | Team | Keep active items current |
**Review Cadence**:
| Activity | Frequency |
|----------|-----------|
| Quick review | Per PR |
| Full review | Quarterly |
| Archive review | Semi-annually |
---
## Checklist
### Add New Intelligence File
- [ ] Follow naming convention
- [ ] Add complete frontmatter
- [ ] Include Quick Reference
- [ ] Keep under 200 lines
- [ ] Add to navigation.md
- [ ] Link from related files
- [ ] Version: 1.0
### Update Existing File
- [ ] Make targeted changes
- [ ] Update version/date in frontmatter
- [ ] Verify <200 lines
- [ ] Update navigation if needed
- [ ] Update related files
### Create Subfolder
- [ ] Verify warranted (5+ files)
- [ ] Create folder with kebab-case name
- [ ] Create `navigation.md` inside
- [ ] Add subfolder to parent navigation
- [ ] Create content files
### Deprecate File
- [ ] Rename with `.deprecated.md`
- [ ] Add deprecation frontmatter
- [ ] Add deprecation banner
- [ ] Mark deprecated in navigation
- [ ] Document replacement
---
## Related Files
- **Standard**: `project-intelligence.md`
- **Project Intelligence**: `../../project-intelligence/navigation.md`
- **Context System**: `../context-system.md`

View File

@@ -0,0 +1,77 @@
<!-- Context: standards/intelligence | Priority: high | Version: 1.0 | Updated: 2025-01-12 -->
# Project Intelligence
> **What**: Living documentation that bridges business domain and technical implementation.
> **Why**: Quick project understanding and onboarding for developers, agents, and stakeholders.
> **Where**: `.opencode/context/project-intelligence/` (dedicated folder)
## Quick Reference
| What You Need | File | Description |
|---------------|------|-------------|
| Understand the "why" | `business-domain.md` | Problem, users, value |
| Understand the "how" | `technical-domain.md` | Stack, architecture |
| See the connection | `business-tech-bridge.md` | Business → technical mapping |
| Know the context | `decisions-log.md` | Why decisions were made |
| Current state | `living-notes.md` | Active issues, debt, questions |
## Why This Exists
Projects fail when:
- Business intent is lost in code
- Technical decisions aren't documented with context
- New members spend weeks instead of hours understanding the project
- Context lives only in people's heads (who leave)
This ensures **business and technical domains speak the same language**.
## Structure
```
.opencode/context/
├── project-intelligence/ # Project-specific context
│ ├── navigation.md # Quick overview & routes
│ ├── business-domain.md # Business context, problems solved
│ ├── technical-domain.md # Stack, architecture, decisions
│ ├── business-tech-bridge.md # How business needs → solutions
│ ├── decisions-log.md # Decisions with rationale
│ └── living-notes.md # Active issues, technical debt
└── core/ # Universal standards
```
## Onboarding Checklist
For new team members or agents:
- [ ] Read `navigation.md` (this file)
- [ ] Read `business-domain.md` to understand the "why"
- [ ] Read `technical-domain.md` to understand the "how"
- [ ] Review `business-tech-bridge.md` to see the connection
- [ ] Check `decisions-log.md` for context on key choices
- [ ] Review `living-notes.md` for current state
- [ ] Explore codebase with this context loaded
## How to Keep This Alive
| Trigger | Action |
|---------|--------|
| Business direction shifts | Update `business-domain.md` |
| New technical decision | Add to `decisions-log.md` |
| New issues or debt | Update `living-notes.md` |
| Feature launch | Update `business-tech-bridge.md` |
| Stack changes | Update `technical-domain.md` |
**Full Management Guide**: See `.opencode/context/core/standards/project-intelligence-management.md`
## Integration with Context System
- **Lazy Loading**: Load project intelligence first when joining a project
- **Layering**: Then load standards and specific context as needed
- **Reference**: See `.opencode/context/core/context-system.md` for system overview
## Related Files
- **Management Guide**: `.opencode/context/core/standards/project-intelligence-management.md`
- **Context System**: `.opencode/context/core/context-system.md`
- **Standards Index**: `.opencode/context/core/standards/navigation.md`

View File

@@ -0,0 +1,149 @@
<!-- Context: standards/patterns | Priority: high | Version: 2.0 | Updated: 2025-01-21 -->
# Essential Patterns - Core Knowledge Base
## Quick Reference
**Critical Patterns**: Error Handling, Validation, Security, Logging
**ALWAYS**: Handle errors gracefully, validate input, use env vars for secrets
**NEVER**: Expose sensitive info, hardcode credentials, skip input validation
**Language-agnostic**: Apply to all programming languages
---
These are language-agnostic patterns that apply to all programming languages. Language-specific implementations are loaded from context files based on project detection.
## Error Handling Pattern
**ALWAYS** handle errors gracefully:
- Catch specific errors, not generic ones
- Log errors with context
- Return meaningful error messages
- Don't expose internal implementation details
- Use language-specific error handling mechanisms (try/catch, Result, error returns)
## Validation Pattern
**ALWAYS** validate input data:
- Check for null/nil/None values
- Validate data types
- Validate data ranges and constraints
- Sanitize user input
- Return clear validation error messages
## Logging Pattern
**USE** consistent logging levels:
- **Debug**: Detailed information for debugging (development only)
- **Info**: Important events and milestones
- **Warning**: Potential issues that don't stop execution
- **Error**: Failures and exceptions
## Security Pattern
**NEVER** expose sensitive information:
- Don't log passwords, tokens, or API keys
- Don't expose internal error details to users
- Validate and sanitize all user input
- Use environment variables for secrets
- Follow principle of least privilege
## File System Safety Pattern
**ALWAYS** validate file paths:
- Prevent path traversal attacks
- Check file permissions before operations
- Use absolute paths when possible
- Handle file not found errors gracefully
- Close file handles properly
## Configuration Pattern
**ALWAYS** use environment variables for configuration:
- Never hardcode secrets or credentials
- Provide sensible defaults
- Validate required configuration on startup
- Document all configuration options
- Use different configs for dev/staging/production
## Testing Pattern
**ALWAYS** write testable code:
- Use dependency injection
- Keep functions pure when possible
- Write unit tests for business logic
- Write integration tests for external dependencies
- Use test fixtures and mocks appropriately
## Documentation Pattern
**DOCUMENT** complex logic and public APIs:
- Explain the "why", not just the "what"
- Document function parameters and return values
- Include usage examples
- Keep documentation up to date with code
- Use language-specific documentation tools
## Performance Pattern
**AVOID** unnecessary operations:
- Don't repeat expensive calculations
- Cache results when appropriate
- Use efficient data structures
- Profile before optimizing
- Consider time and space complexity
## Code Organization Pattern
**KEEP** code modular and focused:
- Single Responsibility Principle - one function, one purpose
- Don't Repeat Yourself (DRY)
- Separate concerns (business logic, data access, presentation)
- Use meaningful names for functions and variables
- Keep functions small and focused (< 50 lines ideally)
## Dependency Management
**MANAGE** dependencies carefully:
- Pin dependency versions for reproducibility
- Regularly update dependencies for security
- Minimize number of dependencies
- Audit dependencies for security vulnerabilities
- Document why each dependency is needed
## Version Control
**FOLLOW** git best practices:
- Write clear, descriptive commit messages
- Make atomic commits (one logical change per commit)
- Use feature branches for development
- Review code before merging
- Keep main/master branch stable
## Code Review Checklist
**REVIEW** for these common issues:
- Error handling is comprehensive
- Input validation is present
- No hardcoded secrets or credentials
- Tests cover new functionality
- Documentation is updated
- Code follows project conventions
- No obvious security vulnerabilities
- Performance considerations addressed

View File

@@ -0,0 +1,127 @@
<!-- Context: standards/tests | Priority: critical | Version: 2.0 | Updated: 2025-01-21 -->
# Testing Standards
## Quick Reference
**Golden Rule**: If you can't test it easily, refactor it
**AAA Pattern**: Arrange → Act → Assert
**Test** (✅ DO):
- Happy path, edge cases, error cases
- Business logic, public APIs
**Don't Test** (❌ DON'T):
- Third-party libraries, framework internals
- Simple getters/setters, private details
**Coverage**: Critical (100%), High (90%+), Medium (80%+)
---
## Principles
**Test behavior, not implementation**: Focus on what code does, not how
**Keep tests simple**: One assertion per test, clear names, minimal setup
**Independent tests**: No shared state, run in any order
**Fast and reliable**: Quick execution, no flaky tests, deterministic
## Test Structure (AAA Pattern)
```javascript
test('calculateTotal returns sum of item prices', () => {
// Arrange - Set up test data
const items = [{ price: 10 }, { price: 20 }, { price: 30 }];
// Act - Execute code
const result = calculateTotal(items);
// Assert - Verify result
expect(result).toBe(60);
});
```
## What to Test
### ✅ DO Test
- Happy path (normal usage)
- Edge cases (boundaries, empty, null, undefined)
- Error cases (invalid input, failures)
- Business logic (core functionality)
- Public APIs (exported functions)
### ❌ DON'T Test
- Third-party libraries
- Framework internals
- Simple getters/setters
- Private implementation details
## Coverage Goals
1. **Critical**: Business logic, data transformations (100%)
2. **High**: Public APIs, user-facing features (90%+)
3. **Medium**: Utilities, helpers (80%+)
4. **Low**: Simple wrappers, configs (optional)
## Testing Pure Functions
```javascript
function add(a, b) { return a + b; }
test('add returns sum', () => {
expect(add(2, 3)).toBe(5);
expect(add(-1, 1)).toBe(0);
expect(add(0, 0)).toBe(0);
});
```
## Testing with Dependencies
```javascript
// Testable with dependency injection
function createUserService(database) {
return {
getUser: (id) => database.findById('users', id)
};
}
// Test with mock
test('getUser retrieves from database', () => {
const mockDb = {
findById: jest.fn().mockReturnValue({ id: 1, name: 'John' })
};
const service = createUserService(mockDb);
const user = service.getUser(1);
expect(mockDb.findById).toHaveBeenCalledWith('users', 1);
expect(user).toEqual({ id: 1, name: 'John' });
});
```
## Test Naming
```javascript
// ✅ Good: Descriptive, clear expectation
test('calculateDiscount returns 10% off for premium users', () => {});
test('validateEmail returns false for invalid format', () => {});
test('createUser throws error when email exists', () => {});
// ❌ Bad: Vague, unclear
test('it works', () => {});
test('test user', () => {});
```
## Best Practices
✅ Test one thing per test
✅ Use descriptive test names
✅ Keep tests independent
✅ Mock external dependencies
✅ Test edge cases and errors
✅ Make tests readable
✅ Run tests frequently
✅ Fix failing tests immediately
**Golden Rule**: If you can't test it easily, refactor it.