Back to skills
SkillHub ClubWrite Technical DocsFull StackBackendTech Writer

codebase-documenter

This skill should be used when writing documentation for codebases, including README files, architecture documentation, code comments, and API documentation. Use this skill when users request help documenting their code, creating getting-started guides, explaining project structure, or making codebases more accessible to new developers. The skill provides templates, best practices, and structured approaches for creating clear, beginner-friendly documentation.

Packaged view

This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.

Stars
0
Hot score
74
Updated
March 20, 2026
Overall rating
C0.0
Composite score
0.0
Best-practice grade
N/A

Install command

npx @skill-hub/cli install merllinsbeard-ai-claude-skills-collection-codebase-documenter
documentationcodebasereadmeapi-docsonboarding

Repository

merllinsbeard/ai-claude-skills-collection

Skill path: development/codebase-documenter

This skill should be used when writing documentation for codebases, including README files, architecture documentation, code comments, and API documentation. Use this skill when users request help documenting their code, creating getting-started guides, explaining project structure, or making codebases more accessible to new developers. The skill provides templates, best practices, and structured approaches for creating clear, beginner-friendly documentation.

Open repository

Best for

Primary workflow: Write Technical Docs.

Technical facets: Full Stack, Backend, Tech Writer.

Target audience: everyone.

License: Unknown.

Original source

Catalog source: SkillHub Club.

Repository owner: merllinsbeard.

This is still a mirrored public skill entry. Review the repository before installing into production workflows.

What it helps with

  • Install codebase-documenter into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
  • Review https://github.com/merllinsbeard/ai-claude-skills-collection before adding codebase-documenter to shared team environments
  • Use codebase-documenter for development workflows

Works across

Claude CodeCodex CLIGemini CLIOpenCode

Favorites: 0.

Sub-skills: 0.

Aggregator: No.

Original source / Raw SKILL.md

---
name: codebase-documenter
description: This skill should be used when writing documentation for codebases, including README files, architecture documentation, code comments, and API documentation. Use this skill when users request help documenting their code, creating getting-started guides, explaining project structure, or making codebases more accessible to new developers. The skill provides templates, best practices, and structured approaches for creating clear, beginner-friendly documentation.
---

# Codebase Documenter

## Overview

This skill enables creating comprehensive, beginner-friendly documentation for codebases. It provides structured templates and best practices for writing READMEs, architecture guides, code comments, and API documentation that help new users quickly understand and contribute to projects.

## Core Principles for Beginner-Friendly Documentation

When documenting code for new users, follow these fundamental principles:

1. **Start with the "Why"** - Explain the purpose before diving into implementation details
2. **Use Progressive Disclosure** - Present information in layers from simple to complex
3. **Provide Context** - Explain not just what the code does, but why it exists
4. **Include Examples** - Show concrete usage examples for every concept
5. **Assume No Prior Knowledge** - Define terms and avoid jargon when possible
6. **Visual Aids** - Use diagrams, flowcharts, and file tree structures
7. **Quick Wins** - Help users get something running within 5 minutes

## Documentation Types and When to Use Them

### 1. README Documentation

**When to create:** For project root directories, major feature modules, or standalone components.

**Structure to follow:**
```markdown
# Project Name

## What This Does
[1-2 sentence plain-English explanation]

## Quick Start
[Get users running the project in < 5 minutes]

## Project Structure
[Visual file tree with explanations]

## Key Concepts
[Core concepts users need to understand]

## Common Tasks
[Step-by-step guides for frequent operations]

## Troubleshooting
[Common issues and solutions]
```

**Best practices:**
- Lead with the project's value proposition
- Include setup instructions that actually work (test them!)
- Provide a visual overview of the project structure
- Link to deeper documentation for advanced topics
- Keep the root README focused on getting started

### 2. Architecture Documentation

**When to create:** For projects with multiple modules, complex data flows, or non-obvious design decisions.

**Structure to follow:**
```markdown
# Architecture Overview

## System Design
[High-level diagram and explanation]

## Directory Structure
[Detailed breakdown with purpose of each directory]

## Data Flow
[How data moves through the system]

## Key Design Decisions
[Why certain architectural choices were made]

## Module Dependencies
[How different parts interact]

## Extension Points
[Where and how to add new features]
```

**Best practices:**
- Use diagrams to show system components and relationships
- Explain the "why" behind architectural decisions
- Document both the happy path and error handling
- Identify boundaries between modules
- Include visual file tree structures with annotations

### 3. Code Comments

**When to create:** For complex logic, non-obvious algorithms, or code that requires context.

**Annotation patterns:**

**Function/Method Documentation:**
```javascript
/**
 * Calculates the prorated subscription cost for a partial billing period.
 *
 * Why this exists: Users can subscribe mid-month, so we need to charge
 * them only for the days remaining in the current billing cycle.
 *
 * @param {number} fullPrice - The normal monthly subscription price
 * @param {Date} startDate - When the user's subscription begins
 * @param {Date} periodEnd - End of the current billing period
 * @returns {number} The prorated amount to charge
 *
 * @example
 * // User subscribes on Jan 15, period ends Jan 31
 * calculateProratedCost(30, new Date('2024-01-15'), new Date('2024-01-31'))
 * // Returns: 16.13 (17 days out of 31 days)
 */
```

**Complex Logic Documentation:**
```python
# Why this check exists: The API returns null for deleted users,
# but empty string for users who never set a name. We need to
# distinguish between these cases for the audit log.
if user_name is None:
    # User was deleted - log this as a security event
    log_deletion_event(user_id)
elif user_name == "":
    # User never completed onboarding - safe to skip
    continue
```

**Best practices:**
- Explain "why" not "what" - the code shows what it does
- Document edge cases and business logic
- Add examples for complex functions
- Explain parameters that aren't self-explanatory
- Note any gotchas or counterintuitive behavior

### 4. API Documentation

**When to create:** For any HTTP endpoints, SDK methods, or public interfaces.

**Structure to follow:**

```markdown
## Endpoint Name

### What It Does
[Plain-English explanation of the endpoint's purpose]

### Endpoint
`POST /api/v1/resource`

### Authentication
[What auth is required and how to provide it]

### Request Format
[JSON schema or example request]

### Response Format
[JSON schema or example response]

### Example Usage
[Concrete example with curl/code]

### Common Errors
[Error codes and what they mean]

### Related Endpoints
[Links to related operations]
```

**Best practices:**
- Provide working curl examples
- Show both success and error responses
- Explain authentication clearly
- Document rate limits and constraints
- Include troubleshooting for common issues

## Documentation Workflow

### Step 1: Analyze the Codebase

Before writing documentation:

1. **Identify entry points** - Main files, index files, app initialization
2. **Map dependencies** - How modules relate to each other
3. **Find core concepts** - Key abstractions users need to understand
4. **Locate configuration** - Environment setup, config files
5. **Review existing docs** - Build on what's there, don't duplicate

### Step 2: Choose Documentation Type

Based on user request and codebase analysis:

- **New project or missing README** → Start with README documentation
- **Complex architecture or multiple modules** → Create architecture documentation
- **Confusing code sections** → Add inline code comments
- **HTTP/API endpoints** → Write API documentation
- **Multiple types needed** → Address in order: README → Architecture → API → Comments

### Step 3: Generate Documentation

Use the templates from `assets/templates/` as starting points:

- `assets/templates/README.template.md` - For project READMEs
- `assets/templates/ARCHITECTURE.template.md` - For architecture docs
- `assets/templates/API.template.md` - For API documentation

Customize templates based on the specific codebase:

1. **Fill in project-specific information** - Replace placeholders with actual content
2. **Add concrete examples** - Use real code from the project
3. **Include visual aids** - Create file trees, diagrams, flowcharts
4. **Test instructions** - Verify setup steps actually work
5. **Link related docs** - Connect documentation pieces together

### Step 4: Review for Clarity

Before finalizing documentation:

1. **Read as a beginner** - Does it make sense without project context?
2. **Check completeness** - Are there gaps in the explanation?
3. **Verify examples** - Do code examples actually work?
4. **Test instructions** - Can someone follow the setup steps?
5. **Improve structure** - Is information easy to find?

## Documentation Templates

This skill includes several templates in `assets/templates/` that provide starting structures:

### Available Templates

- **README.template.md** - Comprehensive README structure with sections for quick start, project structure, and common tasks
- **ARCHITECTURE.template.md** - Architecture documentation template with system design, data flow, and design decisions
- **API.template.md** - API endpoint documentation with request/response formats and examples
- **CODE_COMMENTS.template.md** - Examples and patterns for effective inline documentation

### Using Templates

1. **Read the appropriate template** from `assets/templates/`
2. **Customize for the specific project** - Replace placeholders with actual information
3. **Add project-specific sections** - Extend the template as needed
4. **Include real examples** - Use actual code from the codebase
5. **Remove irrelevant sections** - Delete parts that don't apply

## Best Practices Reference

For detailed documentation best practices, style guidelines, and advanced patterns, refer to:

- `references/documentation_guidelines.md` - Comprehensive style guide and best practices
- `references/visual_aids_guide.md` - How to create effective diagrams and file trees

Load these references when:
- Creating documentation for complex enterprise codebases
- Dealing with multiple stakeholder requirements
- Needing advanced documentation patterns
- Standardizing documentation across a large project

## Common Patterns

### Creating File Tree Structures

File trees help new users understand project organization:

```
project-root/
├── src/                    # Source code
│   ├── components/        # Reusable UI components
│   ├── pages/             # Page-level components (routing)
│   ├── services/          # Business logic and API calls
│   ├── utils/             # Helper functions
│   └── types/             # TypeScript type definitions
├── public/                # Static assets (images, fonts)
├── tests/                 # Test files mirroring src structure
└── package.json           # Dependencies and scripts
```

### Explaining Complex Data Flows

Use numbered steps with diagrams:

```
User Request Flow:
1. User submits form → 2. Validation → 3. API call → 4. Database → 5. Response

[1] components/UserForm.tsx
    ↓ validates input
[2] services/validation.ts
    ↓ sends to API
[3] services/api.ts
    ↓ queries database
[4] Database (PostgreSQL)
    ↓ returns data
[5] components/UserForm.tsx (updates UI)
```

### Documenting Design Decisions

Capture the "why" behind architectural choices:

```markdown
## Why We Use Redux

**Decision:** State management with Redux instead of Context API

**Context:** Our app has 50+ components that need access to user
authentication state, shopping cart, and UI preferences.

**Reasoning:**
- Context API causes unnecessary re-renders with this many components
- Redux DevTools helps debug complex state changes
- Team has existing Redux expertise

**Trade-offs:**
- More boilerplate code
- Steeper learning curve for new developers
- Worth it for: performance, debugging, team familiarity
```

## Output Guidelines

When generating documentation:

1. **Write for the target audience** - Adjust complexity based on whether documentation is for beginners, intermediate, or advanced users
2. **Use consistent formatting** - Follow markdown conventions, consistent heading hierarchy
3. **Provide working examples** - Test all code snippets and commands
4. **Link between documents** - Create a documentation navigation structure
5. **Keep it maintainable** - Documentation should be easy to update as code changes
6. **Add dates and versions** - Note when documentation was last updated

## Quick Reference

**Command to generate README:**
"Create a README file for this project that helps new developers get started"

**Command to document architecture:**
"Document the architecture of this codebase, explaining how the different modules interact"

**Command to add code comments:**
"Add explanatory comments to this file that help new developers understand the logic"

**Command to document API:**
"Create API documentation for all the endpoints in this file"


---

## Referenced Files

> The following files are referenced in this skill and included for context.

### assets/templates/README.template.md

```markdown
# [Project Name]

## What This Does

[Write 1-2 sentences explaining what this project does in plain English. Focus on the value it provides, not the technical implementation.]

Example: "This is a task management application that helps teams track project progress and collaborate on deliverables. It provides real-time updates and integrates with popular project management tools."

## Quick Start

Get up and running in under 5 minutes:

### Prerequisites

- [List required software/tools with versions]
- Example: Node.js 18+ or Python 3.9+
- Example: PostgreSQL 14+
- Example: API keys from [Service Name]

### Installation

```bash
# Clone the repository
git clone [repository-url]
cd [project-name]

# Install dependencies
[package-manager] install

# Set up environment variables
cp .env.example .env
# Edit .env with your configuration

# Run database migrations (if applicable)
[migration-command]

# Start the development server
[start-command]
```

### Verify It's Working

[Provide a quick way to verify the installation succeeded]
- Example: "Open http://localhost:3000 in your browser"
- Example: "Run `npm test` to verify all tests pass"
- Example: "You should see [specific output/page]"

## Project Structure

```
project-root/
├── src/                    # Source code
│   ├── components/        # [Explain what goes here]
│   ├── services/          # [Explain what goes here]
│   ├── utils/             # [Explain what goes here]
│   └── index.js           # [Explain what this file does]
├── tests/                 # Test files
├── public/                # Static assets
├── config/                # Configuration files
├── .env.example           # Environment variable template
├── package.json           # Dependencies and scripts
└── README.md              # This file
```

### Key Directories Explained

**src/components/** - [Detailed explanation of what goes in this directory and when to add files here]

**src/services/** - [Detailed explanation of what goes in this directory and when to add files here]

**src/utils/** - [Detailed explanation of what goes in this directory and when to add files here]

## Key Concepts

### [Concept 1 - Core Abstraction]

[Explain a key concept that users need to understand to work with this codebase]

**Why this matters:** [Explain why understanding this concept is important]

**Example:**
```javascript
// Show a concrete code example demonstrating this concept
```

### [Concept 2 - Important Pattern]

[Explain another important concept]

**Why this matters:** [Explain why understanding this concept is important]

**Example:**
```javascript
// Show a concrete code example demonstrating this concept
```

## Common Tasks

### [Task 1: Common Operation]

[Step-by-step guide for a task users will frequently perform]

1. First step with command: `command-here`
2. Second step with explanation
3. Third step with expected outcome

**Expected result:** [What should happen when this task succeeds]

### [Task 2: Another Common Operation]

[Step-by-step guide for another frequent task]

1. First step with command: `command-here`
2. Second step with explanation
3. Third step with expected outcome

**Expected result:** [What should happen when this task succeeds]

### [Task 3: Development Workflow]

[Explain the typical development workflow]

1. Create a new branch: `git checkout -b feature/your-feature`
2. Make your changes
3. Run tests: `[test-command]`
4. Commit your changes: `git commit -m "Description"`
5. Push and create pull request

## Configuration

### Environment Variables

| Variable | Description | Example | Required |
|----------|-------------|---------|----------|
| `VAR_NAME` | [What this variable controls] | `example-value` | Yes |
| `API_KEY` | [What this variable controls] | `sk_test_123abc` | Yes |
| `DEBUG` | [What this variable controls] | `true` | No |

### Configuration Files

**config/[file-name].js** - [Explain what this config file controls and when to modify it]

## Development

### Running Tests

```bash
# Run all tests
[test-command]

# Run specific test file
[specific-test-command]

# Run with coverage
[coverage-command]
```

### Code Style

[Explain code style conventions]
- [Convention 1]
- [Convention 2]
- Run linter: `[lint-command]`
- Format code: `[format-command]`

### Debugging

[Provide tips for debugging]

**Common debugging commands:**
```bash
# Command to enable debug mode
DEBUG=* [start-command]

# Command to see detailed logs
[log-command]
```

## Troubleshooting

### [Common Issue 1]

**Problem:** [Describe the problem users might encounter]

**Solution:** [Step-by-step solution]
```bash
# Commands to fix the issue
```

### [Common Issue 2]

**Problem:** [Describe the problem users might encounter]

**Solution:** [Step-by-step solution]
```bash
# Commands to fix the issue
```

### [Common Issue 3]

**Problem:** [Describe the problem users might encounter]

**Solution:** [Step-by-step solution]

## Additional Documentation

- [ARCHITECTURE.md](./ARCHITECTURE.md) - Detailed system architecture
- [API.md](./API.md) - API endpoint documentation
- [CONTRIBUTING.md](./CONTRIBUTING.md) - Contribution guidelines
- [Link to external docs if applicable]

## Getting Help

- Check existing issues: [link to issues]
- Join our community: [link to Discord/Slack/forum]
- Contact: [email or contact method]

## License

[License information]

```

### assets/templates/ARCHITECTURE.template.md

```markdown
# Architecture Overview

## What This Document Covers

This document explains the high-level architecture of [Project Name], including how different components interact, key design decisions, and where to make common changes.

**Target audience:** Developers who need to understand the system design before making significant changes.

## System Design

### High-Level Architecture

```
[Create a simple ASCII diagram or describe components]

┌─────────────┐      ┌─────────────┐      ┌─────────────┐
│   Frontend  │─────▶│   Backend   │─────▶│  Database   │
│  (React)    │◀─────│   (Node.js) │◀─────│ (Postgres)  │
└─────────────┘      └─────────────┘      └─────────────┘
       │                    │
       │                    ▼
       │             ┌─────────────┐
       └────────────▶│  API Layer  │
                     └─────────────┘
```

**Components:**

1. **Frontend** - [Explain what this component does and its responsibilities]
2. **Backend** - [Explain what this component does and its responsibilities]
3. **Database** - [Explain what data is stored and how it's organized]
4. **API Layer** - [Explain how components communicate]

### Technology Stack

| Layer | Technology | Why We Chose It |
|-------|-----------|-----------------|
| Frontend | [Technology] | [Reasoning for choice] |
| Backend | [Technology] | [Reasoning for choice] |
| Database | [Technology] | [Reasoning for choice] |
| Hosting | [Technology] | [Reasoning for choice] |

## Directory Structure

```
project-root/
├── src/
│   ├── components/          # Reusable UI components
│   │   ├── common/         # Shared components (buttons, inputs, etc.)
│   │   ├── features/       # Feature-specific components
│   │   └── layout/         # Layout components (header, footer, etc.)
│   │
│   ├── pages/              # Page-level components (one per route)
│   │   ├── Home/          # Home page and related components
│   │   ├── Dashboard/     # Dashboard page and related components
│   │   └── Settings/      # Settings page and related components
│   │
│   ├── services/           # Business logic and external integrations
│   │   ├── api.js         # API client configuration
│   │   ├── auth.js        # Authentication logic
│   │   └── [feature].js   # Feature-specific business logic
│   │
│   ├── store/              # State management (Redux/Context/etc.)
│   │   ├── slices/        # State slices by feature
│   │   └── store.js       # Store configuration
│   │
│   ├── utils/              # Helper functions and utilities
│   │   ├── validation.js  # Input validation helpers
│   │   ├── formatting.js  # Data formatting utilities
│   │   └── constants.js   # App-wide constants
│   │
│   ├── hooks/              # Custom React hooks
│   │   └── use[Feature].js # Feature-specific hooks
│   │
│   ├── types/              # TypeScript type definitions
│   │   ├── models.ts      # Data model types
│   │   └── api.ts         # API request/response types
│   │
│   └── index.js            # Application entry point
│
├── tests/                  # Test files (mirrors src/ structure)
├── public/                 # Static assets
├── config/                 # Configuration files
└── [build-output]/         # Build artifacts (gitignored)
```

### Directory Purpose and Rules

#### components/
**Purpose:** Reusable UI components that don't contain business logic.

**What goes here:**
- Presentational components (buttons, cards, modals)
- Layout components (headers, sidebars, containers)
- Feature-specific components used in multiple places

**What doesn't go here:**
- Business logic (put in `services/`)
- Page-level components (put in `pages/`)
- One-off components used in a single place (colocate with parent)

**When to add a file:** When you need a reusable component used in 2+ places.

#### services/
**Purpose:** Business logic, API calls, and external service integrations.

**What goes here:**
- API client functions
- Authentication and authorization logic
- Data transformation and validation
- Third-party service integrations

**What doesn't go here:**
- UI components (put in `components/`)
- State management (put in `store/`)
- Pure utility functions (put in `utils/`)

**When to add a file:** When you need to interact with external services or implement complex business logic.

#### utils/
**Purpose:** Pure utility functions with no side effects.

**What goes here:**
- Data formatting and parsing
- Validation helpers
- Constants and enumerations
- Date/time utilities

**What doesn't go here:**
- Functions that make API calls (put in `services/`)
- Functions that depend on React (make a custom hook in `hooks/`)
- Functions specific to one component (colocate with component)

**When to add a file:** When you have a pure function used in 3+ places.

## Data Flow

### [Feature Name] Flow

Explain how data flows through the system for a key feature:

```
User Action → Component → Service → API → Database
                ↓
            State Update
                ↓
            UI Re-render
```

**Step-by-step:**

1. **User triggers action** in `components/FeatureComponent.tsx`
   - User clicks button, submits form, etc.
   - Component calls `handleAction()` function

2. **Component dispatches action** to state management
   - Calls `dispatch(featureAction(data))`
   - State is updated optimistically

3. **Service layer processes request** in `services/feature.js`
   - Validates input data
   - Transforms data to API format
   - Makes HTTP request to backend

4. **Backend processes request** in `api/feature/route.js`
   - Validates authentication
   - Applies business logic
   - Updates database

5. **Response flows back** through the layers
   - Backend returns success/error
   - Service layer transforms response
   - State is updated with final result
   - Component re-renders with new data

### State Management

**Architecture:** [Describe state management approach - Redux, Context API, Zustand, etc.]

**State organization:**
```
Global State
├── auth          # User authentication state
├── user          # User profile data
├── [feature1]    # Feature-specific state
├── [feature2]    # Feature-specific state
└── ui            # UI state (modals, loading, etc.)
```

**Data flow rules:**
- Components read state via [hooks/selectors]
- Components update state via [dispatch/setState functions]
- Async operations handled in [middleware/thunks/services]

## Key Design Decisions

### Decision 1: [Architecture Choice]

**What we decided:** [Describe the decision made]

**Context:** [Explain the situation that required this decision]
- [Constraint or requirement 1]
- [Constraint or requirement 2]

**Why we decided this:**
- **Reason 1:** [Explain benefit]
- **Reason 2:** [Explain benefit]
- **Reason 3:** [Explain benefit]

**Trade-offs:**
- ✅ **Pros:** [What we gained]
- ❌ **Cons:** [What we sacrificed]
- 🤔 **When to reconsider:** [Conditions that might make this decision obsolete]

**Alternatives considered:**
- [Alternative 1]: Rejected because [reason]
- [Alternative 2]: Rejected because [reason]

### Decision 2: [Technology Choice]

**What we decided:** [Describe the decision made]

**Context:** [Explain the situation that required this decision]

**Why we decided this:**
- [Reason 1]
- [Reason 2]

**Trade-offs:**
- ✅ **Pros:** [What we gained]
- ❌ **Cons:** [What we sacrificed]

**Alternatives considered:**
- [Alternative 1]: Rejected because [reason]
- [Alternative 2]: Rejected because [reason]

## Module Dependencies

### Dependency Graph

```
pages/
  └─→ components/
        └─→ hooks/
              └─→ services/
                    └─→ utils/

store/
  └─→ services/
        └─→ utils/
```

**Dependency rules:**
1. **Lower layers can't depend on higher layers**
   - ❌ `services/` can't import from `components/`
   - ✅ `components/` can import from `services/`

2. **Same-level imports require careful consideration**
   - 🤔 Components importing other components: Usually OK
   - ⚠️ Services importing other services: Consider refactoring

3. **Avoid circular dependencies**
   - Use dependency injection or event systems when needed

### External Dependencies

| Package | Version | Used For | Notes |
|---------|---------|----------|-------|
| [package-name] | [version] | [purpose] | [Important notes or alternatives] |
| [package-name] | [version] | [purpose] | [Important notes or alternatives] |

## Extension Points

### Adding a New Feature

To add a new feature to the codebase:

1. **Create feature structure:**
   ```
   src/
   ├── components/features/[FeatureName]/
   ├── services/[featureName].js
   └── store/slices/[featureName]Slice.js
   ```

2. **Implement components:**
   - Create UI components in `components/features/[FeatureName]/`
   - Follow existing component patterns
   - Use shared components from `components/common/`

3. **Add business logic:**
   - Create service file in `services/[featureName].js`
   - Implement API calls and data transformations
   - Follow existing error handling patterns

4. **Set up state management:**
   - Create slice in `store/slices/[featureName]Slice.js`
   - Define actions and reducers
   - Export selectors for components

5. **Add routes (if applicable):**
   - Register new routes in `routes.js`
   - Create page component in `pages/[FeatureName]/`

6. **Add tests:**
   - Mirror structure in `tests/`
   - Test components, services, and state

### Common Modification Points

**Adding a new API endpoint:**
- Backend: Create route in `api/[feature]/route.js`
- Frontend: Add service function in `services/[feature].js`
- Update types in `types/api.ts`

**Adding a new database table:**
- Create migration in `migrations/`
- Add model in `models/[tableName].js`
- Update seed data if applicable

**Adding a new component library:**
- Install package: `npm install [package]`
- Create wrapper in `components/common/[ComponentName]/`
- Configure theme/styling in `config/theme.js`

## Performance Considerations

### Critical Performance Paths

1. **[Path 1: e.g., Initial page load]**
   - Current performance: [metrics]
   - Bottlenecks: [known issues]
   - Optimization strategy: [approach]

2. **[Path 2: e.g., Search functionality]**
   - Current performance: [metrics]
   - Bottlenecks: [known issues]
   - Optimization strategy: [approach]

### Caching Strategy

**What we cache:**
- [Data type 1]: Cached in [location] for [duration]
- [Data type 2]: Cached in [location] for [duration]

**Cache invalidation:**
- [Trigger 1]: Clears [cache type]
- [Trigger 2]: Clears [cache type]

## Security Architecture

### Authentication Flow

[Describe how users authenticate]

1. User submits credentials
2. Backend validates and issues [JWT/session/etc.]
3. Token stored in [location]
4. Subsequent requests include token

### Authorization

**Permission levels:**
- [Role 1]: Can [actions]
- [Role 2]: Can [actions]
- [Role 3]: Can [actions]

**Implementation:**
- Frontend: Check permissions in [location]
- Backend: Enforce permissions in [location]

### Data Security

- Sensitive data encrypted at rest: [Yes/No - how]
- API communications: [HTTPS/TLS version]
- Input validation: [Where and how]
- XSS protection: [Strategy]
- CSRF protection: [Strategy]

## Deployment Architecture

### Environments

| Environment | URL | Purpose | Auto-deploys |
|------------|-----|---------|--------------|
| Development | [url] | Local development | No |
| Staging | [url] | Testing before production | Yes (main branch) |
| Production | [url] | Live application | Yes (release tags) |

### Build Process

```bash
# Development build
[build-command-dev]

# Production build
[build-command-prod]
```

**Build artifacts:**
- Output location: [path]
- Artifacts: [list of generated files]

### Deployment Steps

1. [Step 1]
2. [Step 2]
3. [Step 3]

## Monitoring and Observability

### Logging

**Log levels:**
- ERROR: [What gets logged]
- WARN: [What gets logged]
- INFO: [What gets logged]

**Log destinations:**
- Development: [Console/file]
- Production: [Service name/location]

### Metrics

**Key metrics tracked:**
- [Metric 1]: [What it measures]
- [Metric 2]: [What it measures]

**Monitoring tools:**
- [Tool name]: [What we monitor with it]

## Troubleshooting

### Common Architecture Issues

**Issue: [Common problem]**
- **Symptoms:** [How to recognize it]
- **Cause:** [Why it happens]
- **Solution:** [How to fix it]

## Additional Resources

- [Link to API documentation]
- [Link to database schema]
- [Link to deployment guide]
- [Link to contributing guidelines]

## Questions and Feedback

If you have questions about the architecture or suggestions for improvements:
- [Contact method]
- [Issue tracker link]

```

### assets/templates/API.template.md

```markdown
# API Documentation

## Overview

This document provides comprehensive documentation for all API endpoints in [Project Name].

**Base URL:** `https://api.example.com/v1`

**API Version:** v1

**Last Updated:** [Date]

## Table of Contents

- [Authentication](#authentication)
- [Error Handling](#error-handling)
- [Rate Limiting](#rate-limiting)
- [Endpoints](#endpoints)
  - [Resource 1](#resource-1)
  - [Resource 2](#resource-2)

## Authentication

### Authentication Method

This API uses [JWT/API Keys/OAuth/etc.] for authentication.

**How to authenticate:**

1. [Step 1 to get credentials]
2. [Step 2 to use credentials]

**Example authentication header:**
```
Authorization: Bearer YOUR_API_TOKEN_HERE
```

**Getting your API token:**
```bash
# Example command or process to obtain token
curl -X POST https://api.example.com/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "[email protected]", "password": "password123"}'
```

**Response:**
```json
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expiresAt": "2024-12-31T23:59:59Z"
}
```

## Error Handling

### Error Response Format

All errors follow this format:

```json
{
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable error message",
    "details": {
      "field": "Additional context about the error"
    }
  }
}
```

### Common Error Codes

| Status Code | Error Code | Description | Solution |
|------------|------------|-------------|----------|
| 400 | `INVALID_REQUEST` | Request validation failed | Check request format and required fields |
| 401 | `UNAUTHORIZED` | Authentication required or failed | Provide valid authentication token |
| 403 | `FORBIDDEN` | Insufficient permissions | Check user permissions and role |
| 404 | `NOT_FOUND` | Resource doesn't exist | Verify resource ID and URL |
| 429 | `RATE_LIMIT_EXCEEDED` | Too many requests | Wait before retrying (check Retry-After header) |
| 500 | `INTERNAL_ERROR` | Server error | Contact support if persistent |

### Error Examples

**401 Unauthorized:**
```json
{
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Invalid or expired authentication token"
  }
}
```

**400 Invalid Request:**
```json
{
  "error": {
    "code": "INVALID_REQUEST",
    "message": "Validation failed",
    "details": {
      "email": "Invalid email format",
      "age": "Must be a positive number"
    }
  }
}
```

## Rate Limiting

**Rate limits:**
- **Authenticated requests:** 1000 requests per hour
- **Unauthenticated requests:** 100 requests per hour

**Rate limit headers:**
```
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200
```

**When rate limited:**
- Status code: `429 Too Many Requests`
- Response includes `Retry-After` header (seconds until reset)

## Endpoints

---

## [Resource 1 - e.g., Users]

### List [Resources]

Retrieve a paginated list of [resources].

**Endpoint:**
```
GET /api/v1/[resources]
```

**Authentication:** Required

**Query Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `page` | integer | No | 1 | Page number for pagination |
| `limit` | integer | No | 20 | Number of items per page (max 100) |
| `sort` | string | No | `created_at` | Sort field (e.g., `name`, `created_at`) |
| `order` | string | No | `desc` | Sort order (`asc` or `desc`) |
| `filter` | string | No | - | Filter by [field] |

**Example Request:**

```bash
curl -X GET "https://api.example.com/v1/users?page=1&limit=10&sort=created_at&order=desc" \
  -H "Authorization: Bearer YOUR_API_TOKEN"
```

**Example Response:**

```json
{
  "data": [
    {
      "id": "usr_123abc",
      "name": "John Doe",
      "email": "[email protected]",
      "role": "admin",
      "created_at": "2024-01-15T10:30:00Z",
      "updated_at": "2024-01-15T10:30:00Z"
    },
    {
      "id": "usr_456def",
      "name": "Jane Smith",
      "email": "[email protected]",
      "role": "user",
      "created_at": "2024-01-14T15:20:00Z",
      "updated_at": "2024-01-14T15:20:00Z"
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 10,
    "total": 42,
    "pages": 5
  }
}
```

**Response Fields:**

| Field | Type | Description |
|-------|------|-------------|
| `id` | string | Unique identifier |
| `name` | string | [Resource] name |
| `email` | string | Email address |
| `role` | string | User role (`admin`, `user`, `viewer`) |
| `created_at` | string (ISO 8601) | Creation timestamp |
| `updated_at` | string (ISO 8601) | Last update timestamp |

---

### Get [Resource]

Retrieve a single [resource] by ID.

**Endpoint:**
```
GET /api/v1/[resources]/{id}
```

**Authentication:** Required

**Path Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | string | Yes | [Resource] unique identifier |

**Example Request:**

```bash
curl -X GET "https://api.example.com/v1/users/usr_123abc" \
  -H "Authorization: Bearer YOUR_API_TOKEN"
```

**Example Response:**

```json
{
  "id": "usr_123abc",
  "name": "John Doe",
  "email": "[email protected]",
  "role": "admin",
  "profile": {
    "bio": "Software developer",
    "location": "San Francisco, CA"
  },
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-15T10:30:00Z"
}
```

**Possible Errors:**

- `404 NOT_FOUND` - [Resource] with specified ID doesn't exist
- `401 UNAUTHORIZED` - Invalid or missing authentication token
- `403 FORBIDDEN` - Insufficient permissions to view this [resource]

---

### Create [Resource]

Create a new [resource].

**Endpoint:**
```
POST /api/v1/[resources]
```

**Authentication:** Required

**Request Body:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | Yes | [Resource] name (3-100 characters) |
| `email` | string | Yes | Valid email address |
| `role` | string | No | User role (default: `user`) |
| `profile` | object | No | Additional profile information |

**Example Request:**

```bash
curl -X POST "https://api.example.com/v1/users" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Alice Johnson",
    "email": "[email protected]",
    "role": "user",
    "profile": {
      "bio": "Product designer",
      "location": "New York, NY"
    }
  }'
```

**Example Response:**

```json
{
  "id": "usr_789ghi",
  "name": "Alice Johnson",
  "email": "[email protected]",
  "role": "user",
  "profile": {
    "bio": "Product designer",
    "location": "New York, NY"
  },
  "created_at": "2024-01-16T14:20:00Z",
  "updated_at": "2024-01-16T14:20:00Z"
}
```

**Possible Errors:**

- `400 INVALID_REQUEST` - Validation failed (see error details)
- `401 UNAUTHORIZED` - Invalid or missing authentication token
- `403 FORBIDDEN` - Insufficient permissions to create [resource]
- `409 CONFLICT` - [Resource] with this email already exists

---

### Update [Resource]

Update an existing [resource].

**Endpoint:**
```
PATCH /api/v1/[resources]/{id}
```

**Authentication:** Required

**Path Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | string | Yes | [Resource] unique identifier |

**Request Body:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | No | [Resource] name (3-100 characters) |
| `email` | string | No | Valid email address |
| `role` | string | No | User role |
| `profile` | object | No | Additional profile information |

**Note:** Only include fields you want to update. Omitted fields remain unchanged.

**Example Request:**

```bash
curl -X PATCH "https://api.example.com/v1/users/usr_123abc" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "role": "admin",
    "profile": {
      "bio": "Senior Software Developer"
    }
  }'
```

**Example Response:**

```json
{
  "id": "usr_123abc",
  "name": "John Doe",
  "email": "[email protected]",
  "role": "admin",
  "profile": {
    "bio": "Senior Software Developer",
    "location": "San Francisco, CA"
  },
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-16T15:00:00Z"
}
```

**Possible Errors:**

- `400 INVALID_REQUEST` - Validation failed
- `401 UNAUTHORIZED` - Invalid or missing authentication token
- `403 FORBIDDEN` - Insufficient permissions to update this [resource]
- `404 NOT_FOUND` - [Resource] with specified ID doesn't exist

---

### Delete [Resource]

Delete a [resource].

**Endpoint:**
```
DELETE /api/v1/[resources]/{id}
```

**Authentication:** Required

**Path Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | string | Yes | [Resource] unique identifier |

**Example Request:**

```bash
curl -X DELETE "https://api.example.com/v1/users/usr_123abc" \
  -H "Authorization: Bearer YOUR_API_TOKEN"
```

**Example Response:**

```json
{
  "success": true,
  "message": "[Resource] deleted successfully"
}
```

**Possible Errors:**

- `401 UNAUTHORIZED` - Invalid or missing authentication token
- `403 FORBIDDEN` - Insufficient permissions to delete this [resource]
- `404 NOT_FOUND` - [Resource] with specified ID doesn't exist

---

## [Resource 2 - e.g., Projects]

[Repeat the same pattern for another resource: List, Get, Create, Update, Delete]

---

## Webhooks

### Overview

[If your API supports webhooks, document them here]

**Webhook endpoint requirements:**
- Must accept POST requests
- Must respond with 200 status within 5 seconds
- Must use HTTPS

### Available Events

| Event | Description | Triggered When |
|-------|-------------|----------------|
| `[resource].created` | [Resource] was created | New [resource] is created |
| `[resource].updated` | [Resource] was updated | [Resource] is modified |
| `[resource].deleted` | [Resource] was deleted | [Resource] is deleted |

### Webhook Payload

```json
{
  "event": "[resource].created",
  "timestamp": "2024-01-16T15:30:00Z",
  "data": {
    "id": "usr_123abc",
    "name": "John Doe",
    "email": "[email protected]"
  }
}
```

### Verifying Webhooks

[Explain how to verify webhook authenticity, e.g., signature verification]

---

## SDK Examples

### JavaScript/TypeScript

```javascript
// Install: npm install @example/api-client

import { APIClient } from '@example/api-client';

const client = new APIClient({
  apiKey: 'YOUR_API_TOKEN'
});

// List resources
const users = await client.users.list({
  page: 1,
  limit: 10
});

// Get single resource
const user = await client.users.get('usr_123abc');

// Create resource
const newUser = await client.users.create({
  name: 'Alice Johnson',
  email: '[email protected]'
});

// Update resource
const updatedUser = await client.users.update('usr_123abc', {
  role: 'admin'
});

// Delete resource
await client.users.delete('usr_123abc');
```

### Python

```python
# Install: pip install example-api-client

from example_api import APIClient

client = APIClient(api_key='YOUR_API_TOKEN')

# List resources
users = client.users.list(page=1, limit=10)

# Get single resource
user = client.users.get('usr_123abc')

# Create resource
new_user = client.users.create(
    name='Alice Johnson',
    email='[email protected]'
)

# Update resource
updated_user = client.users.update(
    'usr_123abc',
    role='admin'
)

# Delete resource
client.users.delete('usr_123abc')
```

---

## Best Practices

### Pagination

Always paginate list endpoints to avoid performance issues:
- Use `limit` parameter to control page size
- Don't request more than 100 items per page
- Use `page` parameter for subsequent pages

### Error Handling

Implement proper error handling:
```javascript
try {
  const user = await client.users.get('usr_123abc');
} catch (error) {
  if (error.code === 'NOT_FOUND') {
    console.log('User not found');
  } else if (error.code === 'UNAUTHORIZED') {
    console.log('Authentication failed');
  } else {
    console.log('Unexpected error:', error.message);
  }
}
```

### Rate Limiting

Monitor rate limit headers and implement backoff:
```javascript
const response = await fetch(url, options);
const remaining = response.headers.get('X-RateLimit-Remaining');

if (remaining < 10) {
  console.warn('Approaching rate limit');
}
```

---

## Support

**Questions or issues?**
- Documentation: [link]
- Support email: [email]
- Community forum: [link]
- Issue tracker: [link]

**API Status:**
- Status page: [link]
- Uptime: [link]

```

### references/documentation_guidelines.md

```markdown
# Documentation Guidelines

This reference provides comprehensive best practices and style guidelines for creating high-quality documentation.

## Writing Style Guide

### Voice and Tone

**Use active voice:**
- ✅ "The function returns a user object"
- ❌ "A user object is returned by the function"

**Be direct and concise:**
- ✅ "Install dependencies with `npm install`"
- ❌ "You can install the dependencies by running the npm install command"

**Use present tense:**
- ✅ "The API returns an error when..."
- ❌ "The API will return an error when..."

**Avoid unnecessary words:**
- ✅ "To start the server, run..."
- ❌ "In order to start the server, you will need to run..."

### Technical Writing Conventions

**Code formatting:**
- Use backticks for inline code: `variable`, `function()`, `npm install`
- Use code blocks for multi-line code with language specification
- Include command prompts (`$`, `>`) only when necessary for clarity

**Capitalization:**
- Use sentence case for headings: "Getting started" not "Getting Started"
- Capitalize proper nouns: "Docker", "PostgreSQL", "JavaScript"
- Lowercase for commands and file names: `npm`, `package.json`, `index.js`

**Punctuation:**
- Use periods for complete sentences
- No periods for list items that aren't complete sentences
- Use serial comma: "red, white, and blue"

**Lists:**
- Use numbered lists for sequential steps
- Use bullet lists for non-sequential items
- Indent sub-items consistently

## Structure Patterns

### Progressive Disclosure

Organize information from simple to complex:

```markdown
## Getting Started

[Basic usage example that works immediately]

## Core Concepts

[Key concepts needed to understand the system]

## Advanced Usage

[Complex scenarios and edge cases]

## API Reference

[Complete technical reference]
```

### Task-Oriented Structure

Organize by what users want to accomplish:

```markdown
## Common Tasks

### Adding a new feature
[Step-by-step instructions]

### Debugging issues
[Troubleshooting guide]

### Deploying to production
[Deployment instructions]
```

### The "Five-Minute Rule"

Every project should have a path that gets users to success in under 5 minutes:

1. **Quick Start** section at the top
2. Minimal setup steps
3. One working example
4. Clear success indicator ("You should see...")
5. Link to deeper docs for next steps

## Content Guidelines

### Code Examples

**Make examples realistic:**
- ✅ Use real-world variable names and scenarios
- ❌ Don't use `foo`, `bar`, `baz` unless explaining general concepts

```javascript
// ✅ GOOD: Realistic example
const user = await fetchUser('usr_123');
if (user.role === 'admin') {
  showAdminPanel();
}

// ❌ BAD: Unclear example
const foo = await bar('baz');
if (foo.x === 'y') {
  doThing();
}
```

**Include context:**
```javascript
// ✅ GOOD: Shows where this code lives
// src/services/auth.js

export async function login(email, password) {
  // Implementation
}

// ❌ BAD: No context about where to put this
async function login(email, password) {
  // Implementation
}
```

**Show complete examples:**
```javascript
// ✅ GOOD: Complete, runnable example
import { createUser } from './services/user';

async function example() {
  try {
    const user = await createUser({
      name: 'John Doe',
      email: '[email protected]'
    });
    console.log('User created:', user.id);
  } catch (error) {
    console.error('Failed to create user:', error);
  }
}

// ❌ BAD: Incomplete example
const user = await createUser({...});
```

### Error Documentation

**Document error messages:**
```markdown
### Common Errors

**Error: `ECONNREFUSED`**
- **Cause:** Database is not running
- **Solution:** Start the database with `docker-compose up -d postgres`
- **Prevention:** Run `docker-compose up -d` before starting the app

**Error: `Port 3000 is already in use`**
- **Cause:** Another process is using port 3000
- **Solution:** Kill the process with `lsof -ti:3000 | xargs kill -9`
- **Prevention:** Configure a different port in `.env` file
```

### Prerequisites and Dependencies

**Be explicit about requirements:**
```markdown
## Prerequisites

Before starting, ensure you have:

- **Node.js 18 or higher** - Check with `node --version`
  - Download from https://nodejs.org
  - Recommended: Use nvm for version management

- **PostgreSQL 14+** - Check with `psql --version`
  - macOS: `brew install postgresql`
  - Ubuntu: `sudo apt-get install postgresql`
  - Windows: Download from https://postgresql.org/download

- **API keys** - Required for authentication
  - Sign up at https://example.com/api
  - Create new API key in dashboard
  - Save key securely (you'll need it in setup)
```

### Configuration Documentation

**Document all configuration options:**

| Variable | Type | Required | Default | Description |
|----------|------|----------|---------|-------------|
| `PORT` | number | No | `3000` | Port for the server to listen on |
| `DATABASE_URL` | string | Yes | - | PostgreSQL connection string |
| `NODE_ENV` | enum | No | `development` | Environment mode (`development`, `production`, `test`) |
| `LOG_LEVEL` | enum | No | `info` | Logging verbosity (`error`, `warn`, `info`, `debug`) |
| `API_KEY` | string | Yes | - | Third-party API authentication key |

**Include examples:**
```bash
# Development
PORT=3000
DATABASE_URL=postgresql://localhost:5432/myapp_dev
NODE_ENV=development
LOG_LEVEL=debug
API_KEY=sk_test_123abc

# Production
PORT=8080
DATABASE_URL=postgresql://prod.example.com:5432/myapp
NODE_ENV=production
LOG_LEVEL=info
API_KEY=sk_live_789xyz
```

## Visual Aids

### File Tree Structures

Use ASCII art for directory structures:

```
project/
├── src/
│   ├── components/
│   │   ├── Button.tsx       # Reusable button component
│   │   └── Modal.tsx        # Reusable modal component
│   ├── pages/
│   │   ├── Home.tsx         # Home page component
│   │   └── About.tsx        # About page component
│   └── utils/
│       └── format.ts        # Formatting utilities
├── tests/
│   └── components/
│       └── Button.test.tsx  # Button component tests
└── package.json             # Dependencies and scripts
```

### Diagrams

Use ASCII diagrams for flows and relationships:

```
Authentication Flow:

User                     Frontend                 Backend                 Database
  |                         |                        |                        |
  |--- Submit Credentials-->|                        |                        |
  |                         |--- POST /auth/login -->|                        |
  |                         |                        |--- Query User -------->|
  |                         |                        |<------ User Data ------|
  |                         |                        |                        |
  |                         |                        |--- Verify Password --->|
  |                         |                        |<------ Result ---------|
  |                         |                        |                        |
  |                         |<------ JWT Token ------|                        |
  |<-- Login Success -------|                        |                        |
  |                         |                        |                        |
```

### Tables for Comparisons

Use tables to compare options:

| Feature | Option A | Option B | Option C |
|---------|----------|----------|----------|
| Performance | Fast | Medium | Slow |
| Ease of use | Complex | Simple | Medium |
| Flexibility | High | Low | Medium |
| Best for | Large projects | Prototypes | Medium projects |

## Accessibility

### Write for Screen Readers

- Use semantic markdown headings (`#`, `##`, `###`)
- Provide alt text for images: `![Diagram showing data flow](diagram.png)`
- Use descriptive link text: ✅ "Read the API documentation" vs ❌ "Click here"

### Support Multiple Learning Styles

Provide information in multiple formats:

1. **Visual:** Diagrams, screenshots, file trees
2. **Textual:** Written explanations, code comments
3. **Interactive:** Working examples, commands to try

## Maintenance

### Keep Documentation Current

**Add version information:**
```markdown
> **Note:** This documentation is for version 2.x. For version 1.x documentation, see [v1 docs](./v1/README.md).

Last updated: 2024-01-15
```

**Mark deprecated features:**
```markdown
## ⚠️ Deprecated: `legacyAuth()`

**Deprecated in:** v2.0.0
**Removed in:** v3.0.0
**Alternative:** Use `modernAuth()` instead

```javascript
// ❌ Old way (deprecated)
await legacyAuth(token);

// ✅ New way
await modernAuth(token);
```
```

**Document breaking changes:**
```markdown
## Breaking Changes in v2.0

### Changed: Authentication method

**Before (v1.x):**
```javascript
auth.login(username, password);
```

**After (v2.x):**
```javascript
auth.login({ email, password });
```

**Migration guide:**
Replace `username` with `email` and wrap parameters in an object.
```

## Documentation Types

### README Documentation

**Essential sections:**
1. What this does (1-2 sentences)
2. Quick start (< 5 minutes to running)
3. Project structure (visual overview)
4. Common tasks (step-by-step guides)
5. Configuration (environment variables, settings)
6. Troubleshooting (common issues)
7. Links to additional docs

**Keep it focused:**
- Root README should be high-level
- Link to detailed docs in subdirectories
- Aim for 500-1000 words max

### Architecture Documentation

**Essential sections:**
1. System design (high-level overview)
2. Directory structure (detailed breakdown)
3. Data flow (how data moves through system)
4. Key design decisions (why choices were made)
5. Module dependencies (how components interact)
6. Extension points (where to add features)

**Document the "why":**
- Explain architectural decisions
- Provide context for choices made
- Document alternatives considered
- Note trade-offs accepted

### API Documentation

**Essential sections:**
1. Authentication (how to authenticate)
2. Error handling (error format and codes)
3. Rate limiting (limits and headers)
4. Endpoints (all available endpoints)
5. Examples (realistic usage examples)

**For each endpoint:**
- What it does (plain-English explanation)
- Authentication requirements
- Request format (parameters, body)
- Response format (success and errors)
- Working example (curl or SDK)
- Common errors (what can go wrong)

### Inline Code Documentation

**Essential elements:**
1. Purpose (why this code exists)
2. Parameters (what inputs mean)
3. Return value (what output means)
4. Examples (how to use it)
5. Edge cases (special behavior)

**Comment style:**
- Use standard format (JSDoc, docstrings, etc.)
- Explain "why" not "what"
- Include examples for complex functions
- Document assumptions and constraints

## Testing Documentation

**Test all code examples:**
- Verify commands actually work
- Test setup instructions on clean environment
- Check that links aren't broken
- Validate code snippets compile/run

**Make documentation testable:**
```markdown
<!-- Example that can be tested automatically -->
```bash
npm install
npm test
# Expected output: All tests passed (10 tests)
```
```

## Documentation Review Checklist

Before publishing documentation, verify:

**Completeness:**
- [ ] All required sections included
- [ ] Prerequisites clearly listed
- [ ] Setup steps are complete
- [ ] Examples are realistic and tested
- [ ] Links work correctly

**Clarity:**
- [ ] Written for target audience
- [ ] Technical terms defined
- [ ] Examples include context
- [ ] Success criteria clear

**Accuracy:**
- [ ] Code examples work
- [ ] Commands produce expected output
- [ ] Version numbers correct
- [ ] Links point to correct locations

**Organization:**
- [ ] Logical information flow
- [ ] Progressive disclosure used
- [ ] Related topics linked
- [ ] Visual aids where helpful

**Maintenance:**
- [ ] Last updated date included
- [ ] Version information noted
- [ ] Deprecated features marked
- [ ] Breaking changes documented

## Anti-Patterns to Avoid

**Don't assume knowledge:**
- ❌ "Just use the standard approach"
- ✅ "Use dependency injection (see [guide](./di.md))"

**Don't use vague instructions:**
- ❌ "Configure the system appropriately"
- ✅ "Set `PORT=3000` in your `.env` file"

**Don't skip error handling:**
- ❌ Only show happy path examples
- ✅ Show both success and error handling

**Don't leave gaps:**
- ❌ "Install dependencies" → "Run the app"
- ✅ "Install dependencies" → "Configure environment" → "Run migrations" → "Run the app"

**Don't use jargon without explanation:**
- ❌ "Uses CRDT for eventual consistency"
- ✅ "Uses CRDT (Conflict-free Replicated Data Type) to ensure all users see the same data even when working offline"

## Internationalization

**Write for global audience:**
- Use international date format: 2024-01-15 (not 1/15/2024)
- Avoid idioms and colloquialisms
- Use simple sentence structure
- Define acronyms on first use

**Examples for clarity:**
```markdown
## Date Formatting

Dates should use ISO 8601 format: `YYYY-MM-DD`

Examples:
- January 15, 2024 → `2024-01-15`
- March 3, 2024 → `2024-03-03`
- December 25, 2024 → `2024-12-25`
```

## Summary

**Great documentation is:**
1. **Accurate** - Information is correct and up-to-date
2. **Complete** - No critical gaps in coverage
3. **Clear** - Easy to understand for target audience
4. **Organized** - Information is easy to find
5. **Tested** - Examples and instructions actually work
6. **Maintained** - Kept current as code changes
7. **Accessible** - Works for different learning styles
8. **Actionable** - Users can accomplish their goals

**Documentation serves users when it:**
- Gets them started quickly (< 5 minutes to success)
- Answers their questions (comprehensive coverage)
- Helps them when stuck (troubleshooting guides)
- Grows with them (beginner to advanced content)
- Stays current (regular updates and maintenance)

```

### references/visual_aids_guide.md

```markdown
# Visual Aids Guide

This guide provides patterns and techniques for creating effective visual aids in documentation, including diagrams, file trees, and flowcharts.

## Why Visual Aids Matter

Visual aids help users:
- **Understand structure** - See how components fit together
- **Follow flows** - Trace data and process flows
- **Navigate codebases** - Understand directory organization
- **Learn faster** - Visual information is processed 60,000x faster than text
- **Remember better** - People remember 80% of what they see vs 20% of what they read

## File Tree Structures

### Basic File Tree

Use ASCII characters to show hierarchy:

```
project-root/
├── src/
│   ├── components/
│   ├── services/
│   └── utils/
├── tests/
├── public/
└── package.json
```

**Characters to use:**
- `├──` for branches (items with siblings below)
- `└──` for last item in a list
- `│   ` for vertical connection
- `    ` for indentation where no connection

### Annotated File Tree

Add inline comments to explain purpose:

```
project-root/
├── src/                    # Source code
│   ├── components/        # Reusable UI components
│   │   ├── common/       # Shared components (buttons, inputs)
│   │   │   ├── Button.tsx
│   │   │   └── Input.tsx
│   │   └── features/     # Feature-specific components
│   │       ├── auth/     # Authentication components
│   │       └── dashboard/ # Dashboard components
│   ├── services/          # Business logic and API calls
│   │   ├── api.ts        # API client configuration
│   │   └── auth.ts       # Authentication service
│   ├── utils/             # Helper functions
│   │   └── format.ts     # Formatting utilities
│   └── index.tsx          # Application entry point
├── tests/                 # Test files (mirrors src/)
│   └── components/
│       └── Button.test.tsx
├── public/                # Static assets (images, fonts)
│   ├── images/
│   └── fonts/
├── .env.example           # Environment variable template
├── package.json           # Dependencies and scripts
└── README.md              # Project documentation
```

### File Tree with File Sizes

Show relative importance or complexity:

```
project-root/
├── src/                    [12 files, 5,200 lines]
│   ├── components/        [8 files, 3,800 lines] ← Most of the code
│   ├── services/          [3 files, 1,200 lines]
│   └── utils/             [1 file, 200 lines]
├── tests/                  [8 files, 2,100 lines]
└── config/                 [3 files, 150 lines]
```

### File Tree with Change Indicators

Show what's new or modified:

```
project-root/
├── src/
│   ├── components/
│   │   ├── Button.tsx      ← Modified for v2.0
│   │   └── Modal.tsx       ✨ New in v2.0
│   └── services/
│       └── legacy.ts       ⚠️ Deprecated, use auth.ts instead
└── README.md               ← Updated installation steps
```

## System Architecture Diagrams

### Component Diagram

Show how major pieces fit together:

```
┌─────────────────────────────────────────────────────────┐
│                      Application                         │
│                                                          │
│  ┌─────────────┐      ┌─────────────┐      ┌─────────┐ │
│  │   Frontend  │      │   Backend   │      │ Database│ │
│  │   (React)   │◄────►│   (Node.js) │◄────►│(Postgres│ │
│  └─────────────┘      └─────────────┘      └─────────┘ │
│         │                     │                          │
│         │                     │                          │
│         ▼                     ▼                          │
│  ┌─────────────┐      ┌─────────────┐                  │
│  │   Browser   │      │  File Store │                  │
│  │   Storage   │      │    (S3)     │                  │
│  └─────────────┘      └─────────────┘                  │
└─────────────────────────────────────────────────────────┘
```

**Symbols:**
- `┌─┐` `│` `└─┘` - Boxes for components
- `◄────►` - Bidirectional communication
- `────►` - Unidirectional flow
- `▼` - Downward dependency

### Layered Architecture

Show architectural layers:

```
┌───────────────────────────────────────┐
│        Presentation Layer             │  ← User Interface
│     (React Components, Pages)         │
├───────────────────────────────────────┤
│         Application Layer             │  ← Business Logic
│    (Services, State Management)       │
├───────────────────────────────────────┤
│          Data Access Layer            │  ← Database Operations
│     (Repositories, ORMs, APIs)        │
├───────────────────────────────────────┤
│        Infrastructure Layer           │  ← External Services
│  (Database, Cache, Message Queue)     │
└───────────────────────────────────────┘
```

### Network Architecture

Show how services communicate:

```
Internet
   │
   ▼
┌─────────────────┐
│  Load Balancer  │
└────────┬────────┘
         │
    ┌────┴────┐
    │         │
    ▼         ▼
┌────────┐ ┌────────┐
│ Web    │ │ Web    │
│ Server │ │ Server │
│   #1   │ │   #2   │
└───┬────┘ └───┬────┘
    │          │
    └────┬─────┘
         ▼
   ┌──────────┐
   │   API    │
   │  Server  │
   └────┬─────┘
        │
   ┌────┴─────┐
   │          │
   ▼          ▼
┌──────┐  ┌───────┐
│ DB   │  │ Cache │
│(Primary) │(Redis)│
└──────┘  └───────┘
```

## Data Flow Diagrams

### Linear Flow

Show a simple sequence:

```
User Input → Validation → Processing → Storage → Response

[1] Form Submit  →  [2] Check Data  →  [3] Transform  →  [4] Save  →  [5] Success
```

### Branching Flow

Show conditional logic:

```
User Login Attempt
        │
        ▼
   Check Credentials
        │
   ┌────┴────┐
   │         │
   ▼         ▼
Valid?      Invalid?
   │           │
   │           ▼
   │      Show Error
   │           │
   │           ▼
   │      Retry Count++
   │           │
   ▼           ▼
Generate    Max Retries?
  Token          │
   │        ┌────┴────┐
   │        ▼         ▼
   │       Yes        No
   │        │         │
   │        ▼         └──► Return to Check
   │    Lock
   │    Account
   │
   ▼
Return Token
```

### Detailed Step Flow

Show exactly where things happen in code:

```
User Registration Flow:

[1] User submits form
    └─► components/RegistrationForm.tsx: handleSubmit()

[2] Validate input
    └─► utils/validation.ts: validateRegistrationData()

[3] Check email uniqueness
    └─► services/user.ts: checkEmailExists()
         └─► Makes API call: GET /api/users?email={email}

[4] Create user account
    └─► services/user.ts: createUser()
         └─► Makes API call: POST /api/users
              └─► Backend: api/users/route.ts: POST handler
                   └─► Database: INSERT INTO users

[5] Send welcome email
    └─► services/email.ts: sendWelcomeEmail()
         └─► External API: Sendgrid

[6] Update UI with success
    └─► components/RegistrationForm.tsx: setState({success: true})
```

### Sequence Diagram

Show interactions over time:

```
User            Frontend              Backend            Database
  │                │                     │                   │
  │─── Click ─────►│                     │                   │
  │                │                     │                   │
  │                │─── GET /api/data ──►│                   │
  │                │                     │                   │
  │                │                     │─── SELECT * ─────►│
  │                │                     │                   │
  │                │                     │◄─── Results ──────│
  │                │                     │                   │
  │                │◄─── JSON Response ──│                   │
  │                │                     │                   │
  │◄─── Display ───│                     │                   │
  │                │                     │                   │
```

## State Diagrams

Show state transitions:

```
Order State Machine:

     ┌─────────┐
     │ Created │ ← Initial state
     └────┬────┘
          │
          │ User clicks "Pay"
          ▼
    ┌──────────┐
    │ Pending  │
    │ Payment  │
    └─────┬────┘
          │
     ┌────┴────┐
     │         │
     │         │ Payment fails
     ▼         ▼
┌────────┐  ┌──────────┐
│  Paid  │  │ Cancelled│ ← Terminal states
└───┬────┘  └──────────┘
    │
    │ Items shipped
    ▼
┌───────────┐
│ Fulfilled │ ← Terminal state
└───────────┘
```

## Database Schema Diagrams

### Entity Relationship

Show table relationships:

```
┌──────────────┐         ┌──────────────┐
│    users     │         │    posts     │
├──────────────┤         ├──────────────┤
│ id (PK)      │────┐    │ id (PK)      │
│ email        │    │    │ user_id (FK) │────┐
│ name         │    └───►│ title        │    │
│ created_at   │         │ content      │    │
└──────────────┘         │ created_at   │    │
                         └──────────────┘    │
                                             │
                         ┌──────────────┐    │
                         │   comments   │    │
                         ├──────────────┤    │
                         │ id (PK)      │    │
                         │ post_id (FK) │◄───┘
                         │ user_id (FK) │
                         │ content      │
                         │ created_at   │
                         └──────────────┘

Relationships:
- User has many Posts (1:N)
- Post has many Comments (1:N)
- User has many Comments (1:N)
```

### Simple Table View

```
users table:
┌────┬──────────────────┬──────────┬────────────┐
│ id │ email            │ name     │ role       │
├────┼──────────────────┼──────────┼────────────┤
│ 1  │ [email protected]│ Alice    │ admin      │
│ 2  │ [email protected]  │ Bob      │ user       │
│ 3  │ [email protected]│ Carol    │ user       │
└────┴──────────────────┴──────────┴────────────┘
```

## API Request/Response Flows

### REST API Flow

```
Client                          Server                       Database
  │                               │                              │
  │ GET /api/users/123            │                              │
  ├──────────────────────────────►│                              │
  │                               │                              │
  │                               │ SELECT * FROM users          │
  │                               │ WHERE id = 123               │
  │                               ├─────────────────────────────►│
  │                               │                              │
  │                               │          User data           │
  │                               │◄─────────────────────────────┤
  │                               │                              │
  │       200 OK                  │                              │
  │       {user data}             │                              │
  │◄──────────────────────────────┤                              │
  │                               │                              │
```

## Process Flowcharts

### Decision Tree

```
                    Start
                      │
                      ▼
             ┌────────────────┐
             │ User logged in?│
             └────────┬───────┘
                      │
            ┌─────────┴─────────┐
            │                   │
           Yes                 No
            │                   │
            ▼                   ▼
    ┌──────────────┐    ┌──────────────┐
    │ Show         │    │ Redirect to  │
    │ Dashboard    │    │ Login Page   │
    └──────┬───────┘    └──────────────┘
           │
           ▼
    ┌──────────────┐
    │ Has premium? │
    └──────┬───────┘
           │
    ┌──────┴──────┐
    │             │
   Yes           No
    │             │
    ▼             ▼
┌────────┐  ┌────────┐
│ Show   │  │ Show   │
│ All    │  │ Basic  │
│Features│  │Features│
└────────┘  └────────┘
```

## Module Dependency Graphs

### Simple Dependencies

```
pages/
  │
  └─► components/
        │
        ├─► hooks/
        │     │
        │     └─► services/
        │           │
        │           └─► utils/
        │
        └─► utils/
```

### Complex Dependencies

```
                  ┌──────────┐
                  │  pages/  │
                  └────┬─────┘
                       │
           ┌───────────┼───────────┐
           │           │           │
           ▼           ▼           ▼
    ┌──────────┐ ┌──────────┐ ┌──────────┐
    │components│ │  hooks/  │ │ services/│
    └─────┬────┘ └─────┬────┘ └─────┬────┘
          │            │            │
          └────────┬───┴────┬───────┘
                   ▼        ▼
              ┌────────────────┐
              │    utils/      │
              └────────────────┘

Legend:
─────► Direct dependency
```

## Timeline Diagrams

### Project Timeline

```
Q1 2024              Q2 2024              Q3 2024              Q4 2024
───┼───────────────────┼───────────────────┼───────────────────┼─────►
   │                   │                   │                   │
   ├─ v1.0 Release     ├─ v1.5 Release     ├─ v2.0 Release     ├─ v2.5
   │  • Basic features │  • API v2         │  • New UI         │  • Mobile
   │  • Core API       │  • Performance    │  • Webhooks       │  • Plugins
   │                   │                   │                   │
```

### Development Phases

```
Phase 1: Planning    Phase 2: Development    Phase 3: Testing    Phase 4: Launch
─────────────────────────────────────────────────────────────────────────────►
    2 weeks               6 weeks                3 weeks            1 week

│◄────────────►│◄───────────────────────────►│◄──────────────►│◄──────────►│
│              │                              │                │            │
│ • Research   │ • Feature development        │ • QA testing   │ • Deploy   │
│ • Design     │ • Code review                │ • Bug fixes    │ • Monitor  │
│ • Planning   │ • Unit tests                 │ • UAT          │ • Support  │
```

## Comparison Tables

### Feature Matrix

```
┌─────────────┬──────────┬──────────┬──────────┐
│   Feature   │ Plan A   │ Plan B   │ Plan C   │
├─────────────┼──────────┼──────────┼──────────┤
│ Storage     │ 10 GB    │ 100 GB   │ 1 TB     │
│ Users       │ 5        │ 25       │ Unlimited│
│ API Calls   │ 1,000/mo │ 10,000/mo│ Unlimited│
│ Support     │ Email    │ Email    │ 24/7     │
│ Price/month │ $10      │ $50      │ $200     │
└─────────────┴──────────┴──────────┴──────────┘
```

### Technology Comparison

```
┌────────────┬─────────┬─────────┬─────────┬─────────┐
│ Criteria   │ React   │ Vue     │ Angular │ Svelte  │
├────────────┼─────────┼─────────┼─────────┼─────────┤
│ Simplicity │ ★★★☆☆   │ ★★★★☆   │ ★★☆☆☆   │ ★★★★★   │
│ Performance│ ★★★★☆   │ ★★★★☆   │ ★★★☆☆   │ ★★★★★   │
│ Ecosystem  │ ★★★★★   │ ★★★★☆   │ ★★★★☆   │ ★★★☆☆   │
│ Jobs       │ ★★★★★   │ ★★★★☆   │ ★★★★☆   │ ★★☆☆☆   │
└────────────┴─────────┴─────────┴─────────┴─────────┘
```

## Best Practices

### Choose the Right Visual

| When you need to show... | Use... |
|--------------------------|--------|
| Code organization | File tree structure |
| System components | Architecture diagram |
| Process steps | Flow diagram or sequence diagram |
| Data movement | Data flow diagram |
| Conditional logic | Decision tree or flowchart |
| State changes | State diagram |
| Database structure | ER diagram |
| Module relationships | Dependency graph |
| Time-based changes | Timeline or Gantt chart |
| Feature comparison | Table or matrix |

### Keep It Simple

- **One concept per diagram** - Don't try to show everything
- **Limit complexity** - 5-7 items per diagram is ideal
- **Use consistent symbols** - Don't invent new notation
- **Label clearly** - Every box and arrow should be labeled
- **Add legends** - Explain any symbols used

### Make It Accessible

- **Use text descriptions** - Describe what the diagram shows
- **Provide alt text** - For accessibility tools
- **Use semantic formatting** - Code blocks for ASCII diagrams
- **High contrast** - Ensure diagrams are readable
- **Consider text-only** - Some readers can't see diagrams

### Test Your Visuals

- **Show to someone unfamiliar** - Can they understand it?
- **Print it out** - Does it work on paper?
- **View on mobile** - Is it readable on small screens?
- **Test with screen readers** - Is the content accessible?

## Tools for Creating Diagrams

### ASCII Art (Recommended for Documentation)

**Pros:**
- Works in any text editor
- Version control friendly
- Always renders correctly
- Accessible to screen readers

**Cons:**
- Time-consuming to create
- Limited visual appeal
- Hard to create complex diagrams

**When to use:** For simple diagrams in markdown documentation

### Mermaid (Code-Based Diagrams)

```mermaid
graph TD
    A[Start] --> B{Is it working?}
    B -->|Yes| C[Great!]
    B -->|No| D[Debug]
    D --> A
```

**Pros:**
- Text-based (version control friendly)
- Renders as nice graphics
- Supports many diagram types

**Cons:**
- Requires Mermaid renderer
- Learning curve for syntax
- Not all platforms support it

**When to use:** When your documentation platform supports Mermaid

### Draw.io / Lucidchart (Visual Tools)

**Pros:**
- Professional appearance
- Easy to create complex diagrams
- Many templates available

**Cons:**
- Binary files (not version control friendly)
- Requires separate tool
- Can become outdated

**When to use:** For complex diagrams or presentations

## Examples from Real Projects

### React Component Hierarchy

```
App
├── Header
│   ├── Logo
│   ├── Navigation
│   │   ├── NavItem
│   │   └── NavItem
│   └── UserMenu
├── Sidebar
│   ├── SidebarItem
│   └── SidebarItem
└── Content
    ├── Dashboard
    │   ├── StatsCard
    │   ├── Chart
    │   └── RecentActivity
    └── Footer
```

### Authentication Flow

```
1. User visits protected page
   └─► Check if token exists in localStorage

2. Token exists?
   ├─► YES: Validate token
   │   └─► Valid?
   │       ├─► YES: Allow access
   │       └─► NO: Redirect to login (expired token)
   │
   └─► NO: Redirect to login (not authenticated)

3. User logs in
   └─► POST /api/auth/login {email, password}
       └─► Success?
           ├─► YES: Store token in localStorage → Redirect to original page
           └─► NO: Show error message → Stay on login page
```

## Summary

Effective visual aids:
- **Clarify complex concepts** faster than text alone
- **Show relationships** between components
- **Guide users** through processes and flows
- **Organize information** spatially
- **Improve retention** of information

Choose diagrams that:
- **Match the concept** being explained
- **Stay simple** and focused
- **Use consistent notation**
- **Are accessible** to all users
- **Complement text** rather than replace it

```