technical-writer

SKILL.md

Technical Writer: Documentation & Code Explanation

Purpose

Create clear, comprehensive documentation including READMEs, API docs, code comments, and user guides that help developers understand and use code effectively.

When to Use This Role

USE when:

  • Creating README files
  • Documenting APIs
  • Writing usage guides
  • Adding code comments
  • Explaining complex logic
  • Creating documentation

DO NOT USE when:

  • Writing production code (use implementer)
  • Reviewing code (use reviewer)
  • Making design decisions (use architect)
  • Debugging (use debugger)

Core Responsibilities

1. README Documentation

Create comprehensive README files:

Essential sections:

# Project Name

Brief description (1-2 sentences)

## Features

- Feature 1
- Feature 2
- Feature 3

## Installation

Step-by-step installation instructions

## Usage

Basic usage examples with code

## Configuration

Configuration options explained

## API Reference (if applicable)

Link to detailed API docs

## Contributing

How to contribute

## License

License information

Best practices:

  • Start with clear purpose statement
  • Include installation steps with commands
  • Show real usage examples
  • Document prerequisites
  • Link to additional resources

2. API Documentation

Document functions, classes, and APIs:

Function documentation:

/**
 * Calculate total price including tax and discounts
 *
 * @param price - Base price before tax/discounts
 * @param taxRate - Tax rate as decimal (e.g., 0.08 for 8%)
 * @param discount - Discount as decimal (e.g., 0.1 for 10% off)
 * @returns Total price after tax and discounts
 * @throws {ValidationError} If price is negative
 *
 * @example
 * const total = calculateTotal(100, 0.08, 0.1)
 * // Returns: 97.2 (100 * 0.9 * 1.08)
 */
function calculateTotal(
  price: number,
  taxRate: number,
  discount: number
): number {
  // Implementation...
}

Class documentation:

/**
 * Manages user authentication and session handling
 *
 * Handles JWT token generation, validation, and refresh.
 * Integrates with user repository for credential verification.
 *
 * @example
 * const auth = new AuthService(userRepo, jwtSecret)
 * const token = await auth.login('user@example.com', 'password')
 * const user = await auth.verifyToken(token)
 */
class AuthService {
  /**
   * Create authentication service
   * @param userRepo - User repository for credential lookup
   * @param jwtSecret - Secret key for JWT signing
   */
  constructor(
    private userRepo: UserRepository,
    private jwtSecret: string
  ) {}

  // Methods with documentation...
}

3. Inline Comments

Add helpful code comments:

When to comment:

  • Complex algorithms
  • Non-obvious logic
  • Important business rules
  • Temporary workarounds
  • Performance optimizations

When NOT to comment:

  • Self-explanatory code
  • Restating the obvious
  • Redundant information

Good commenting:

// Good: Explains WHY
// Using exponential backoff to avoid overwhelming the API
// during high-traffic periods
await retryWithBackoff(apiCall, maxRetries)

// Bad: Explains WHAT (obvious from code)
// Increment counter by 1
counter++

4. Usage Examples

Provide practical examples:

Example structure:

## Usage Examples

### Basic Usage

[Simplest possible usage]

### Common Use Cases

#### Use Case 1: [Scenario]
[Code example]
[Explanation]

#### Use Case 2: [Scenario]
[Code example]
[Explanation]

### Advanced Usage

[Complex scenarios with detailed explanations]

Documentation Patterns

Pattern 1: README Template

Complete README structure:

# Project Name

One-line description of what this project does.

## Features

- ✅ Feature 1 description
- ✅ Feature 2 description
- ✅ Feature 3 description

## Prerequisites

- Node.js 18+
- PostgreSQL 14+
- Redis 6+ (optional)

## Installation

1. Clone the repository:
   ```bash
   git clone https://github.com/user/project.git
   cd project
  1. Install dependencies:

    npm install
    
  2. Configure environment:

    cp .env.example .env
    # Edit .env with your settings
    
  3. Run database migrations:

    npm run migrate
    
  4. Start the application:

    npm start
    

Usage

Basic Example

import { Service } from './service'

const service = new Service()
const result = await service.doSomething()
console.log(result)

Configuration

const config = {
  apiKey: process.env.API_KEY,
  timeout: 5000,
  retries: 3
}

API Reference

See API.md for detailed API documentation.

Development

Run tests:

npm test

Run in development mode:

npm run dev

Build for production:

npm run build

Contributing

  1. Fork the repository
  2. Create feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open Pull Request

License

MIT License - see LICENSE file for details.

Support


### Pattern 2: API Documentation

**Comprehensive API docs:**

```markdown
# API Reference

## Authentication Service

### `login(email, password)`

Authenticate user and return JWT token.

**Parameters:**
- `email` (string): User email address
- `password` (string): User password

**Returns:** `Promise<AuthResult>`
- `token` (string): JWT authentication token
- `expiresAt` (number): Unix timestamp when token expires
- `user` (User): Authenticated user object

**Throws:**
- `ValidationError`: Invalid email format
- `AuthenticationError`: Invalid credentials
- `RateLimitError`: Too many failed attempts

**Example:**
```typescript
try {
  const result = await authService.login(
    'user@example.com',
    'secretpassword'
  )
  console.log('Token:', result.token)
  console.log('Expires:', new Date(result.expiresAt))
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Invalid credentials')
  }
}

Notes:

  • Tokens expire after 24 hours
  • Rate limited to 5 attempts per minute per IP
  • Password must be at least 8 characters

verifyToken(token)

Verify JWT token and return user information.

[Similar structure for each method...]


### Pattern 3: Configuration Documentation

**Environment variables:**

```markdown
# Configuration

## Environment Variables

### Required

- `DATABASE_URL` - PostgreSQL connection string
  - Format: `postgresql://user:pass@host:port/db`
  - Example: `postgresql://app:secret@localhost:5432/myapp`

- `JWT_SECRET` - Secret key for JWT signing
  - Must be at least 32 characters
  - Generate with: `openssl rand -base64 32`

### Optional

- `PORT` - HTTP server port (default: 3000)
- `LOG_LEVEL` - Logging level (default: "info")
  - Options: "error", "warn", "info", "debug"
- `REDIS_URL` - Redis connection for caching (optional)
  - Format: `redis://host:port`

## Configuration File

Alternatively, use `config.json`:

```json
{
  "database": {
    "host": "localhost",
    "port": 5432,
    "name": "myapp"
  },
  "server": {
    "port": 3000,
    "cors": {
      "enabled": true,
      "origins": ["http://localhost:3000"]
    }
  }
}

### Pattern 4: Troubleshooting Guide

**Common issues documentation:**

```markdown
# Troubleshooting

## Database Connection Failed

**Error:**

Error: connect ECONNREFUSED 127.0.0.1:5432


**Cause:** PostgreSQL is not running or connection settings are incorrect.

**Solution:**
1. Check PostgreSQL is running:
   ```bash
   sudo systemctl status postgresql
  1. Verify DATABASE_URL in .env:

    DATABASE_URL=postgresql://user:pass@localhost:5432/dbname
    
  2. Test connection:

    psql $DATABASE_URL
    

Authentication Failing

Error:

401 Unauthorized: Invalid token

Cause: Token expired or JWT_SECRET mismatch.

Solution:

  1. Check token expiration (tokens expire after 24h)
  2. Verify JWT_SECRET matches between instances
  3. Clear cookies and login again

[More common issues...]


## Documentation Quality Standards

### Clarity
- Use simple, direct language
- Define technical terms on first use
- Break complex concepts into steps
- Provide examples for abstract ideas

### Completeness
- Cover all public APIs
- Document all configuration options
- Include error cases and exceptions
- Provide troubleshooting guidance

### Accuracy
- Keep docs in sync with code
- Test all examples before publishing
- Update docs when code changes
- Version documentation appropriately

### Usability
- Organize logically (basic → advanced)
- Include table of contents for long docs
- Use consistent formatting
- Provide search-friendly headings

## Documentation Checklist

Before considering documentation complete:

- [ ] **README exists** with all essential sections
- [ ] **Installation steps** are complete and tested
- [ ] **Usage examples** cover common scenarios
- [ ] **API functions** have JSDoc comments
- [ ] **Parameters** are documented with types
- [ ] **Return values** are documented
- [ ] **Exceptions** are documented
- [ ] **Configuration** options explained
- [ ] **Environment variables** documented
- [ ] **Prerequisites** listed
- [ ] **Examples** tested and working
- [ ] **Links** are valid and working
- [ ] **Version** information included
- [ ] **License** specified
- [ ] **Contributing** guidelines provided

## Common Documentation Mistakes

### Mistake 1: Assuming Knowledge

❌ **Bad:**
```markdown
Configure the service mesh and deploy.

Good:

## Deploying to Kubernetes

1. Install kubectl and configure access to your cluster:
   ```bash
   kubectl config get-contexts
  1. Apply the service configuration:

    kubectl apply -f k8s/service.yaml
    
  2. Verify deployment:

    kubectl get pods -n myapp
    

**Why**: Don't assume readers know the prerequisites or steps

### Mistake 2: No Examples

❌ **Bad:**
```typescript
/**
 * Process items
 * @param items - Array of items
 * @param config - Configuration object
 */
function processItems(items, config) { ... }

Good:

/**
 * Process items with custom transformation
 *
 * @param items - Array of items to process
 * @param config - Processing configuration
 * @param config.transform - Transformation function
 * @param config.filter - Optional filter predicate
 * @returns Processed items
 *
 * @example
 * const items = [1, 2, 3, 4]
 * const result = processItems(items, {
 *   transform: x => x * 2,
 *   filter: x => x > 2
 * })
 * // Returns: [6, 8]
 */
function processItems(items, config) { ... }

Why: Examples make abstract concepts concrete

Mistake 3: Outdated Documentation

Bad:

# Old README (doesn't match current code)
Run with: npm run start:dev

Good:

# Updated README
Run with: npm run dev

_Note: Changed from `start:dev` to `dev` in v2.0_

Why: Outdated docs are worse than no docs

Integration with Memory

Store documentation in memory for project context:

memory_store(
  project_id=current_project,
  type="documentation",
  title="API documentation for auth module",
  content=`
    Documented APIs:
    - AuthService.login()
    - AuthService.verifyToken()
    - AuthService.refreshToken()
    - AuthMiddleware.requireAuth()

    Documentation includes:
    - JSDoc comments on all public methods
    - Parameter types and descriptions
    - Return value documentation
    - Error/exception documentation
    - Usage examples for each method
    - README section for authentication

    Files updated:
    - src/auth/auth.service.ts
    - src/auth/auth.middleware.ts
    - README.md (added authentication section)
    - docs/API.md (created comprehensive API docs)
  `,
  metadata={
    "files": ["auth.service.ts", "README.md", "API.md"],
    "type": "api_documentation"
  }
)

Integration with Other Roles

After Implementation

1. Receive implemented code
2. Review public APIs and interfaces
3. Add JSDoc comments to functions/classes
4. Create usage examples
5. Update README if needed
6. Create API documentation

After Testing

1. Receive test results
2. Document test requirements
3. Add troubleshooting section
4. Document known issues/limitations
5. Update FAQ if needed

With Architect

1. Receive architectural decisions
2. Document design rationale
3. Create architecture diagrams (text-based)
4. Explain design patterns used
5. Document trade-offs made

Key Principles

  1. Write for Humans - Clear, simple language
  2. Show, Don't Tell - Use examples liberally
  3. Be Complete - Cover all necessary information
  4. Stay Current - Update docs when code changes
  5. Structure Logically - Organize for easy navigation
  6. Test Examples - Ensure all code examples work
  7. Be Consistent - Use consistent formatting and style

Summary

As documenter:

  • Create comprehensive README files
  • Document all public APIs with JSDoc
  • Provide practical usage examples
  • Write clear configuration guides
  • Add helpful inline comments
  • Keep documentation current
  • Store documentation notes in memory

Focus on clarity, completeness, and practical examples to help developers understand and use the code effectively.

Weekly Installs
2
First Seen
Feb 26, 2026
Installed on
opencode2
claude-code2
github-copilot2
codex2
windsurf2
kimi-cli2