agentleFS
mehdiozdemirmehdiozdemir/awesome-agent-skills/skills/documentation-generator/SKILL.md

documentation-generator

Skill2 starsChanged 10 months agoMITView on GitHub

Generates comprehensive documentation for code, APIs, projects, and systems. Use when creating README files, API documentation, inline code comments, JSDoc/TSDoc/PyDoc annotations, architecture diagrams, onboarding guides, or any technical documentation needs.

  • Reads credentials
  • Installs packages
  • Sends data out
  • Commits and pushes

3 other projects use a version of this.

Adopted by

Most recently taken up by

The file

Show its rules and text

We split this skill into the rules it gives an agent

14 rules. 0 are common, 14 are distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 3 edited versions we read keep these.

  • 14

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Write clear, concise prose

    line 74
  2. Distinctive:

    Add diagrams where helpful

    line 76
  3. Distinctive:

    Test links and references

    line 85
  4. Distinctive:

    Be clear and concise: - Avoid jargon, explain technical terms

    line 852
  5. Distinctive:

    Keep it current: - Update docs with code changes

    line 853
  6. Distinctive:

    Make it scannable: - Use headings, tables, bullet points

    line 857
  7. Distinctive:

    Include edge cases: - Document error conditions

    line 858
  8. Distinctive:

    Test examples: - Ensure code samples actually work

    line 861
  9. Distinctive:

    Don't leave TODOs: - Document or create issues

    line 868
  10. Distinctive:

    When generating documentation, provide:

    line 893
  11. Distinctive:

    Keep examples minimal but complete

    line 921
  12. Distinctive:

    Update documentation as part of the development process

    line 922
  13. Distinctive:

    Use diagrams for complex systems - a picture is worth 1000 words

    line 923
  14. Distinctive:

    Consider using documentation generators (Sphinx, JSDoc, Godoc) for consistency

    line 924

“Common” is measured: kept by at least 6 in 10 of the 3 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Documentation Generator Skill

This skill creates clear, comprehensive, and maintainable documentation for any codebase, API, or system. Use this whenever you need to document code, create README files, generate API references, write technical guides, or improve code comments.

Documentation Types

1. README Documentation

Project entry point documentation including:

  • Project overview and purpose
  • Installation instructions
  • Quick start guide
  • Configuration options
  • Usage examples
  • Contributing guidelines
  • License information

2. API Documentation

Interface documentation including:

  • Endpoint descriptions
  • Request/response schemas
  • Authentication details
  • Error codes and handling
  • Rate limiting information
  • SDK/client examples

3. Code Documentation

Inline and block documentation:

  • Function/method docstrings
  • Class and module descriptions
  • Type annotations
  • Parameter descriptions
  • Return value documentation
  • Example usage

4. Architecture Documentation

System design documentation:

  • High-level architecture overview
  • Component relationships
  • Data flow diagrams
  • Technology stack
  • Design decisions (ADRs)
  • Deployment architecture

5. User Guides

End-user focused documentation:

  • Getting started tutorials
  • Feature walkthroughs
  • Troubleshooting guides
  • FAQ sections
  • Best practices

Documentation Process

Step 1: Analyze the Subject

  1. Understand the code/system being documented
  2. Identify the target audience (developers, users, operators)
  3. Determine documentation scope and depth
  4. Review existing documentation (if any)
  5. Note dependencies and prerequisites

Step 2: Structure the Documentation

  1. Choose appropriate format and template
  2. Organize content hierarchically
  3. Plan sections and subsections
  4. Identify code examples needed
  5. Determine visual aids required

Step 3: Generate Content

  1. Write clear, concise prose
  2. Include relevant code examples
  3. Add diagrams where helpful
  4. Cross-reference related sections
  5. Maintain consistent terminology

Step 4: Review and Refine

  1. Verify technical accuracy
  2. Check for completeness
  3. Ensure readability
  4. Validate code examples
  5. Test links and references

README Template

# Project Name

> Brief tagline describing the project (one line)

[![License](badge-url)](license-url)
[![Build Status](badge-url)](build-url)
[![npm version](badge-url)](npm-url)

Short paragraph explaining what this project does, why it exists, and who it's for.

## ✨ Features

- **Feature 1**: Brief description
- **Feature 2**: Brief description
- **Feature 3**: Brief description

## 📋 Prerequisites

- Requirement 1 (version x.x+)
- Requirement 2 (version x.x+)

## 🚀 Quick Start

### Installation

```bash
# Using npm
npm install project-name

# Using yarn
yarn add project-name

# Using pip
pip install project-name

Basic Usage

import { feature } from 'project-name';

// Simple example
const result = feature.doSomething();
console.log(result);

📖 Documentation

  • Full Documentation
  • API Reference
  • Examples

⚙️ Configuration

OptionTypeDefaultDescription
option1string"default"Description
option2booleantrueDescription
option3number100Description

Environment Variables

PROJECT_API_KEY=your-api-key
PROJECT_DEBUG=true
PROJECT_TIMEOUT=5000

🔧 Development

Setup

# Clone the repository
git clone https://github.com/user/project.git
cd project

# Install dependencies
npm install

# Run tests
npm test

# Start development server
npm run dev

Project Structure

project/
├── src/
│   ├── components/     # UI components
│   ├── services/       # Business logic
│   ├── utils/          # Utility functions
│   └── index.js        # Entry point
├── tests/              # Test files
├── docs/               # Documentation
└── package.json

🤝 Contributing

Contributions are welcome! Please read our Contributing Guide first.

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

📝 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • Dependency 1 - What it provides
  • Inspiration source - Brief note
  • Contributors and maintainers

Made with ❤️ by Your Name


## API Documentation Template

### REST API Endpoint

```markdown
## Create User

Creates a new user account in the system.

### Endpoint

POST /api/v1/users


### Authentication

Requires API key authentication via `Authorization` header.

Authorization: Bearer <api-key>


### Request

#### Headers

| Header | Required | Description |
|--------|----------|-------------|
| `Content-Type` | Yes | Must be `application/json` |
| `Authorization` | Yes | Bearer token |
| `X-Request-ID` | No | Optional request tracking ID |

#### Body Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `email` | `string` | Yes | User's email address |
| `password` | `string` | Yes | Password (min 8 characters) |
| `name` | `string` | Yes | User's display name |
| `role` | `string` | No | User role (default: "user") |

#### Example Request

```bash
curl -X POST https://api.example.com/api/v1/users \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk_live_xxx" \
  -d '{
    "email": "user@example.com",
    "password": "SecureP@ss123",
    "name": "John Doe",
    "role": "admin"
  }'

Response

Success Response (201 Created)

{
  "id": "usr_abc123",
  "email": "user@example.com",
  "name": "John Doe",
  "role": "admin",
  "created_at": "2025-01-15T10:30:00Z",
  "updated_at": "2025-01-15T10:30:00Z"
}

Error Responses

StatusCodeDescription
400VALIDATION_ERRORInvalid request parameters
401UNAUTHORIZEDMissing or invalid API key
409CONFLICTEmail already exists
429RATE_LIMITEDToo many requests
500INTERNAL_ERRORServer error
Example Error Response
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request parameters",
    "details": [
      {
        "field": "email",
        "message": "Invalid email format"
      }
    ]
  }
}

Rate Limiting

  • 100 requests per minute per API key
  • Headers included in response:
    • X-RateLimit-Limit: Maximum requests allowed
    • X-RateLimit-Remaining: Requests remaining
    • X-RateLimit-Reset: Unix timestamp when limit resets

## Code Documentation Standards

### Python (Docstrings - Google Style)

```python
def calculate_discount(
    price: float,
    discount_percent: float,
    max_discount: float | None = None
) -> float:
    """Calculate the discounted price for a product.

    Applies a percentage discount to the given price, optionally
    capping the discount at a maximum value.

    Args:
        price: The original price of the product in dollars.
            Must be a positive number.
        discount_percent: The discount to apply as a percentage (0-100).
            For example, 15 means 15% off.
        max_discount: Optional maximum discount amount in dollars.
            If provided, the discount will not exceed this value.

    Returns:
        The final price after applying the discount.
        Always returns a value >= 0.

    Raises:
        ValueError: If price is negative or discount_percent is
            outside the range [0, 100].

    Examples:
        >>> calculate_discount(100.0, 20)
        80.0

        >>> calculate_discount(100.0, 50, max_discount=30)
        70.0  # Capped at $30 discount instead of $50

        >>> calculate_discount(50.0, 10)
        45.0

    Note:
        This function rounds the result to 2 decimal places
        for currency precision.
    """
    if price < 0:
        raise ValueError(f"Price must be non-negative, got {price}")
    if not 0 <= discount_percent <= 100:
        raise ValueError(f"Discount must be 0-100, got {discount_percent}")

    discount_amount = price * (discount_percent / 100)

    if max_discount is not None:
        discount_amount = min(discount_amount, max_discount)

    return round(price - discount_amount, 2)

Python (Class Documentation)

class UserService:
    """Service for managing user accounts and authentication.

    This service provides methods for creating, updating, and
    authenticating users. It handles password hashing, email
    verification, and session management.

    Attributes:
        db: Database connection for user persistence.
        cache: Redis cache for session storage.
        mailer: Email service for sending notifications.

    Example:
        >>> service = UserService(db, cache, mailer)
        >>> user = service.create_user("john@example.com", "password123")
        >>> print(user.id)
        'usr_abc123'

    Note:
        This class is thread-safe and can be used in
        multi-threaded applications.
    """

    def __init__(
        self,
        db: Database,
        cache: Redis,
        mailer: EmailService
    ) -> None:
        """Initialize the UserService with required dependencies.

        Args:
            db: Database connection instance.
            cache: Redis cache for session management.
            mailer: Email service for notifications.
        """
        self.db = db
        self.cache = cache
        self.mailer = mailer

JavaScript/TypeScript (JSDoc/TSDoc)

/**
 * Represents a user account in the system.
 *
 * @remarks
 * This interface defines the core user properties used throughout
 * the application. For extended user details, see {@link UserProfile}.
 *
 * @example
 * ```typescript
 * const user: User = {
 *   id: 'usr_abc123',
 *   email: 'john@example.com',
 *   name: 'John Doe',
 *   role: 'admin',
 *   createdAt: new Date()
 * };
 * ```
 */
interface User {
  /** Unique identifier for the user (format: usr_xxx) */
  id: string;

  /** User's email address (must be unique) */
  email: string;

  /** Display name shown in the UI */
  name: string;

  /** User's role determining permissions */
  role: 'user' | 'admin' | 'moderator';

  /** Timestamp when the user was created */
  createdAt: Date;

  /** Timestamp of last update (optional) */
  updatedAt?: Date;
}

/**
 * Authenticates a user with email and password.
 *
 * @param email - The user's email address
 * @param password - The user's password (will be hashed)
 * @param options - Optional authentication settings
 * @returns A promise resolving to the authenticated user with token
 *
 * @throws {@link AuthenticationError}
 * Thrown if credentials are invalid.
 *
 * @throws {@link RateLimitError}
 * Thrown if too many login attempts.
 *
 * @example
 * Basic usage:
 * ```typescript
 * try {
 *   const { user, token } = await authenticate(
 *     'john@example.com',
 *     'password123'
 *   );
 *   console.log(`Logged in as ${user.name}`);
 * } catch (error) {
 *   if (error instanceof AuthenticationError) {
 *     console.error('Invalid credentials');
 *   }
 * }
 * ```
 *
 * @example
 * With remember me option:
 * ```typescript
 * const result = await authenticate(email, password, {
 *   rememberMe: true,
 *   deviceId: 'device_xyz'
 * });
 * ```
 *
 * @see {@link logout} for ending the session
 * @see {@link refreshToken} for token renewal
 */
async function authenticate(
  email: string,
  password: string,
  options?: AuthOptions
): Promise<AuthResult> {
  // Implementation
}

Java (Javadoc)

/**
 * Service for processing payment transactions.
 *
 * <p>This service handles all payment-related operations including
 * charging cards, processing refunds, and managing subscriptions.
 * It integrates with multiple payment providers (Stripe, PayPal).
 *
 * <p>Example usage:
 * <pre>{@code
 * PaymentService service = new PaymentService(stripeClient);
 * PaymentResult result = service.charge(
 *     "cus_abc123",
 *     Money.of(99.99, USD)
 * );
 * if (result.isSuccessful()) {
 *     System.out.println("Payment ID: " + result.getPaymentId());
 * }
 * }</pre>
 *
 * @author Development Team
 * @version 2.0
 * @since 1.0
 * @see PaymentProvider
 * @see Subscription
 */
public class PaymentService {

    /**
     * Charges a customer's default payment method.
     *
     * <p>This method attempts to charge the customer's primary
     * payment method. If the charge fails, it will automatically
     * retry with backup payment methods if available.
     *
     * @param customerId the unique customer identifier
     *                   (format: cus_xxx)
     * @param amount the amount to charge (must be positive)
     * @return the payment result containing transaction details
     * @throws PaymentException if the charge fails after all retries
     * @throws CustomerNotFoundException if customer ID is invalid
     * @throws IllegalArgumentException if amount is not positive
     */
    public PaymentResult charge(String customerId, Money amount)
            throws PaymentException, CustomerNotFoundException {
        // Implementation
    }
}

Go (Godoc)

// Package auth provides authentication and authorization utilities.
//
// This package implements JWT-based authentication with support for
// multiple identity providers including OAuth2 and SAML.
//
// Basic usage:
//
//	auth := auth.New(auth.Config{
//	    SecretKey: os.Getenv("JWT_SECRET"),
//	    Issuer:    "my-app",
//	})
//
//	token, err := auth.GenerateToken(user)
//	if err != nil {
//	    log.Fatal(err)
//	}
//
// For more complex scenarios, see the examples directory.
package auth

// User represents an authenticated user in the system.
//
// The User struct contains core identity information and is
// typically obtained from the Authenticate or ValidateToken methods.
type User struct {
    // ID is the unique identifier for the user.
    ID string

    // Email is the user's email address (always lowercase).
    Email string

    // Roles contains the user's permission roles.
    Roles []string
}

// Authenticate verifies user credentials and returns a session.
//
// The email is case-insensitive. Password must match the stored
// hash using bcrypt comparison.
//
// Returns ErrInvalidCredentials if email or password is incorrect.
// Returns ErrAccountLocked if too many failed attempts.
//
// Example:
//
//	session, err := auth.Authenticate(ctx, "user@example.com", "password")
//	if err != nil {
//	    if errors.Is(err, auth.ErrInvalidCredentials) {
//	        http.Error(w, "Invalid login", http.StatusUnauthorized)
//	        return
//	    }
//	    http.Error(w, "Server error", http.StatusInternalServerError)
//	    return
//	}
//	// Use session.Token for subsequent requests
func (a *Auth) Authenticate(ctx context.Context, email, password string) (*Session, error) {
    // Implementation
}

Architecture Documentation Template

Architecture Decision Record (ADR)

# ADR-001: Use PostgreSQL for Primary Database

## Status

Accepted (2025-01-15)

## Context

We need to choose a primary database for storing user data, transactions,
and application state. The system requires:

- ACID compliance for financial transactions
- Support for complex queries and reporting
- Horizontal scalability for future growth
- Strong ecosystem and tooling

Options considered:
1. PostgreSQL
2. MySQL
3. MongoDB
4. CockroachDB

## Decision

We will use **PostgreSQL 16** as our primary database.

## Rationale

### Why PostgreSQL

1. **ACID Compliance**: Full transaction support essential for payment processing
2. **JSON Support**: Native JSONB for flexible schema where needed
3. **Performance**: Excellent query optimizer and indexing options
4. **Extensions**: PostGIS for location data, pg_cron for scheduled jobs
5. **Community**: Large community, extensive documentation
6. **Cost**: Open source with enterprise support options

### Why Not Alternatives

- **MySQL**: Weaker JSON support, less capable query planner
- **MongoDB**: Eventual consistency not suitable for transactions
- **CockroachDB**: Added complexity not justified at current scale

## Consequences

### Positive

- Strong data integrity guarantees
- Familiar SQL interface for team
- Excellent tooling (pgAdmin, Datagrip)
- Easy integration with ORMs (SQLAlchemy, Prisma)

### Negative

- Single node limits (can address with read replicas)
- Requires DBA expertise for optimization at scale
- Schema migrations require planning

### Risks and Mitigations

| Risk | Mitigation |
|------|------------|
| Write bottleneck | Implement caching layer (Redis) |
| Schema rigidity | Use JSONB for flexible attributes |
| Backup complexity | Automated daily backups to S3 |

## Implementation

1. Set up managed PostgreSQL instance (AWS RDS)
2. Configure connection pooling (PgBouncer)
3. Implement migration strategy (Alembic/Flyway)
4. Set up monitoring (pg_stat_statements)

## References

- [PostgreSQL Documentation](https://postgresql.org/docs)
- [Choosing the Right Database](internal-wiki-link)
- [Database Scaling Strategy](internal-wiki-link)

System Architecture Overview

# System Architecture

## Overview

This document describes the high-level architecture of the
E-Commerce Platform, a microservices-based system handling
1M+ daily active users.

## Architecture Diagram

┌─────────────────────────────────────────────────────────────────┐ │ CDN (CloudFlare) │ └─────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ Load Balancer (AWS ALB) │ └─────────────────────────────────────────────────────────────────┘ │ ┌─────────────────┼─────────────────┐ ▼ ▼ ▼ ┌───────────┐ ┌───────────┐ ┌───────────┐ │ Web App │ │ API │ │ Admin │ │ (Next.js) │ │ Gateway │ │ Portal │ └───────────┘ └─────┬─────┘ └───────────┘ │ ┌───────────────────────┼───────────────────────┐ │ │ │ ▼ ▼ ▼ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │ User │ │ Order │ │ Product │ │ Service │ │ Service │ │ Service │ │ (Python) │ │ (Go) │ │ (Node.js) │ └───────┬───────┘ └───────┬───────┘ └───────┬───────┘ │ │ │ ▼ ▼ ▼ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │ PostgreSQL │ │ PostgreSQL │ │ Elasticsearch │ │ (Users) │ │ (Orders) │ │ (Products) │ └───────────────┘ └───────────────┘ └───────────────┘

┌─────────────────────────────────────────────────────────────────┐ │ Message Queue (RabbitMQ) │ └─────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────┐ │ Cache Layer (Redis) │ └─────────────────────────────────────────────────────────────────┘


## Components

### Frontend Layer

| Component | Technology | Purpose |
|-----------|------------|---------|
| Web App | Next.js 14 | Customer-facing storefront |
| Admin Portal | React + Vite | Internal management |
| Mobile App | React Native | iOS/Android customers |

### API Layer

| Component | Technology | Purpose |
|-----------|------------|---------|
| API Gateway | Kong | Routing, rate limiting, auth |
| GraphQL | Apollo Server | Unified query interface |

### Service Layer

| Service | Language | Database | Responsibility |
|---------|----------|----------|----------------|
| User | Python | PostgreSQL | Auth, profiles, preferences |
| Order | Go | PostgreSQL | Orders, payments, fulfillment |
| Product | Node.js | Elasticsearch | Catalog, search, inventory |
| Notification | Python | Redis | Email, SMS, push notifications |
| Analytics | Python | ClickHouse | Metrics, reporting, BI |

### Data Layer

| Store | Technology | Purpose |
|-------|------------|---------|
| Primary DB | PostgreSQL 16 | Transactional data |
| Search | Elasticsearch 8 | Full-text search |
| Cache | Redis 7 | Session, hot data |
| Queue | RabbitMQ | Async messaging |
| Object Store | S3 | Images, documents |

## Data Flow

### Order Placement Flow

1. Customer submits order via Web App
2. API Gateway validates JWT token
3. Order Service receives request
4. User Service validates customer
5. Product Service checks inventory
6. Payment Service processes payment
7. Order Service persists order
8. Message published to order.created queue
9. Notification Service sends confirmation
10. Analytics Service records metrics

## Scaling Strategy

### Horizontal Scaling
- All services are stateless
- Kubernetes HPA based on CPU/memory
- Database read replicas for read-heavy services

### Caching Strategy
- L1: Application-level (in-memory)
- L2: Redis cluster (distributed)
- L3: CDN (static assets, API responses)

## Security

### Authentication
- JWT tokens (15min access, 7d refresh)
- OAuth2 for third-party integrations
- mTLS between services

### Data Protection
- Encryption at rest (AES-256)
- Encryption in transit (TLS 1.3)
- PII anonymization in logs

Documentation Best Practices

DO ✅

  • Be clear and concise - Avoid jargon, explain technical terms
  • Keep it current - Update docs with code changes
  • Use examples - Show real usage, not just descriptions
  • Be consistent - Same format, terminology throughout
  • Add context - Explain WHY, not just WHAT
  • Make it scannable - Use headings, tables, bullet points
  • Include edge cases - Document error conditions
  • Cross-reference - Link to related documentation
  • Version properly - Note which version docs apply to
  • Test examples - Ensure code samples actually work

DON'T ❌

  • Don't state the obvious - // increments i by 1 for i++
  • Don't use ambiguous pronouns - Be specific about "it" and "this"
  • Don't assume knowledge - Explain prerequisites
  • Don't leave TODOs - Document or create issues
  • Don't duplicate - Link instead of repeating
  • Don't mix audiences - Separate user vs developer docs
  • Don't forget updates - Stale docs are worse than none
  • Don't over-document - Focus on non-obvious aspects
  • Don't ignore formatting - Proper code blocks, indentation
  • Don't skip error docs - Users need to know what can go wrong

Quality Checklist

Before completing documentation:

  • All public APIs documented
  • Examples compile and run
  • Parameters and returns described
  • Error conditions documented
  • Prerequisites listed
  • Installation instructions tested
  • Links are valid
  • Spelling and grammar checked
  • Consistent formatting
  • Version information current

Output Format

When generating documentation, provide:

## Documentation Type
[README / API Doc / Code Doc / Architecture Doc / User Guide]

## Target Audience
[Developers / Users / Operators / All]

---

[Generated Documentation Here]

---

## Additional Recommendations
[Suggestions for improving or extending the documentation]

## Files to Create/Update
- `path/to/file.md` - Description
- `path/to/another.md` - Description

Notes

  • Adapt documentation depth to the complexity of the subject
  • Prioritize documentation that will be read most often
  • Code documentation should explain intent, not implementation
  • Keep examples minimal but complete
  • Update documentation as part of the development process
  • Use diagrams for complex systems - a picture is worth 1000 words
  • Consider using documentation generators (Sphinx, JSDoc, Godoc) for consistency

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.