skills/dnyoussef/when-documenting-code-use-doc-generator/SKILL.md
Automated comprehensive code documentation generation with API docs, README files, inline comments, and architecture diagrams
npx skillsauth add aiskillstore/marketplace when-documenting-code-use-doc-generatorInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
This skill provides automated, comprehensive documentation generation for codebases. It analyzes code structure, generates API documentation, creates README files, adds inline comments, and produces architecture diagrams using evidence-based documentation patterns.
Objective: Understand the codebase structure and documentation needs
Actions:
Deliverables:
Agent: code-analyzer
Example Analysis:
Project: express-api-server
Languages: JavaScript (TypeScript), 85% | JSON 10% | Markdown 5%
Frameworks: Express.js, Jest
Current Documentation:
- README.md: Exists (outdated, 3 months old)
- API Docs: None
- Inline Comments: 12% coverage
- Type Definitions: 45% coverage
Gaps Identified:
- ❌ No API documentation (12 endpoints undocumented)
- ❌ Missing installation instructions
- ❌ No architecture diagrams
- ⚠️ Low inline comment coverage
- ✅ Package.json well-documented
Recommended Strategy:
1. Generate OpenAPI 3.0 spec for REST API
2. Add JSDoc comments to all public functions
3. Create comprehensive README with badges
4. Generate architecture diagram (system overview)
5. Add usage examples for main features
Objective: Plan documentation hierarchy and templates
Actions:
Deliverables:
Example Structure:
Documentation Hierarchy:
docs/
├── README.md # Project overview
├── INSTALLATION.md # Setup guide
├── API.md # API reference
├── ARCHITECTURE.md # System design
├── CONTRIBUTING.md # Contribution guide
├── diagrams/
│ ├── system-overview.svg # High-level architecture
│ ├── data-flow.svg # Data flow diagram
│ └── api-endpoints.svg # API structure
└── examples/
├── basic-usage.md
└── advanced-features.md
Comment Standards:
- JSDoc for all exported functions
- TypeDoc for TypeScript interfaces
- File header with purpose and author
- Inline comments for complex logic only
API Documentation:
- OpenAPI 3.0 specification
- Example requests/responses
- Error code documentation
- Authentication guide
Objective: Design the documentation generation workflow
Actions:
Deliverables:
Pipeline Architecture:
┌─────────────────┐
│ Source Code │
│ Repository │
└────────┬────────┘
│
▼
┌─────────────────────────┐
│ Code Analyzer │
│ - AST Parsing │
│ - Extract Functions │
│ - Extract Types │
│ - Detect Patterns │
└────────┬────────────────┘
│
▼
┌─────────────────────────┐
│ Documentation Engine │
│ ├─ API Generator │
│ ├─ README Generator │
│ ├─ Comment Generator │
│ └─ Diagram Generator │
└────────┬────────────────┘
│
▼
┌─────────────────────────┐
│ Template Renderer │
│ - Mustache/Handlebars │
│ - Markdown Formatting │
│ - Syntax Highlighting │
└────────┬────────────────┘
│
▼
┌─────────────────────────┐
│ Validator │
│ - Link Checking │
│ - Spelling │
│ - Completeness │
└────────┬────────────────┘
│
▼
┌─────────────────────────┐
│ Output │
│ - docs/ │
│ - Inline Comments │
│ - Generated Diagrams │
└─────────────────────────┘
Objective: Execute documentation generation with quality checks
Actions:
Deliverables:
Generation Examples:
Before (Undocumented Function):
function calculateDiscount(price, customerType, quantity) {
const baseDiscount = customerType === 'premium' ? 0.15 : 0.05;
const volumeDiscount = quantity > 100 ? 0.1 : quantity > 50 ? 0.05 : 0;
return price * (1 - baseDiscount - volumeDiscount);
}
After (With JSDoc):
/**
* Calculates the final price after applying customer and volume discounts
*
* @param {number} price - The original price before discounts
* @param {('standard'|'premium')} customerType - Customer tier level
* @param {number} quantity - Number of items purchased
* @returns {number} The discounted price
*
* @example
* // Premium customer buying 60 items at $100 each
* calculateDiscount(100, 'premium', 60);
* // Returns: 80 (15% customer + 5% volume discount)
*
* @see {@link https://docs.example.com/pricing|Pricing Documentation}
*/
function calculateDiscount(price, customerType, quantity) {
// Premium customers receive 15% base discount, standard customers 5%
const baseDiscount = customerType === 'premium' ? 0.15 : 0.05;
// Volume discounts: 10% for 100+, 5% for 50+, 0% otherwise
const volumeDiscount = quantity > 100 ? 0.1 : quantity > 50 ? 0.05 : 0;
return price * (1 - baseDiscount - volumeDiscount);
}
API Documentation Generation:
# Generated OpenAPI 3.0 Specification
openapi: 3.0.0
info:
title: E-commerce API
version: 1.0.0
description: REST API for e-commerce platform with pricing and inventory
paths:
/api/v1/products/{id}/price:
get:
summary: Calculate product price with discounts
description: Returns the final price after applying customer tier and volume discounts
operationId: calculateProductPrice
tags:
- Pricing
parameters:
- name: id
in: path
required: true
schema:
type: string
description: Product ID
- name: quantity
in: query
required: true
schema:
type: integer
minimum: 1
description: Quantity to purchase
- name: customerType
in: query
required: false
schema:
type: string
enum: [standard, premium]
default: standard
description: Customer tier level
responses:
'200':
description: Price calculated successfully
content:
application/json:
schema:
type: object
properties:
originalPrice:
type: number
example: 100.00
discountedPrice:
type: number
example: 80.00
discountsApplied:
type: array
items:
type: object
properties:
type:
type: string
enum: [customer, volume]
percentage:
type: number
example: 0.15
'404':
description: Product not found
README Generation:
# E-commerce API Server
[](https://travis-ci.org/org/repo)
[](https://codecov.io/gh/org/repo)
[](LICENSE)
> Production-ready REST API for e-commerce platform with advanced pricing, inventory management, and order processing.
## Features
- ✅ Dynamic pricing with customer tiers and volume discounts
- ✅ Real-time inventory tracking
- ✅ Order processing and fulfillment
- ✅ JWT authentication with role-based access
- ✅ Rate limiting and security middleware
- ✅ Comprehensive API documentation (OpenAPI 3.0)
## Quick Start
### Prerequisites
- Node.js >= 18.0.0
- PostgreSQL >= 14.0
- Redis >= 7.0 (for caching)
### Installation
```bash
# Clone repository
git clone https://github.com/org/ecommerce-api.git
cd ecommerce-api
# Install dependencies
npm install
# Configure environment
cp .env.example .env
# Edit .env with your database credentials
# Run migrations
npm run migrate
# Start server
npm start
// Example: Calculate price with discounts
const response = await fetch(
'http://localhost:3000/api/v1/products/prod-123/price?quantity=60&customerType=premium'
);
const { discountedPrice } = await response.json();
console.log(`Final price: $${discountedPrice}`);
Full API documentation available at:
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | /api/v1/products | List all products |
| GET | /api/v1/products/{id} | Get product details |
| GET | /api/v1/products/{id}/price | Calculate price with discounts |
| POST | /api/v1/orders | Create new order |
| GET | /api/v1/orders/{id} | Get order status |
See ARCHITECTURE.md for detailed system design.
| Variable | Description | Default |
|----------|-------------|---------|
| PORT | Server port | 3000 |
| DATABASE_URL | PostgreSQL connection | - |
| REDIS_URL | Redis connection | - |
| JWT_SECRET | Authentication secret | - |
# Run all tests
npm test
# Run with coverage
npm run test:coverage
# Run integration tests
npm run test:integration
See CONTRIBUTING.md for contribution guidelines.
MIT © 2025 Your Organization
### Phase 5: COMPLETION - Integrate and Maintain Documentation
**Objective**: Ensure documentation stays synchronized with code
**Actions**:
1. Integrate documentation into build pipeline
2. Set up automated documentation updates
3. Configure pre-commit hooks for comment validation
4. Establish documentation review process
5. Create documentation maintenance schedule
**Deliverables**:
- CI/CD integration
- Git hooks for documentation
- Maintenance schedule
- Documentation metrics dashboard
**Integration Strategy**:
```yaml
# .github/workflows/docs.yml
name: Documentation
on:
push:
branches: [main, develop]
pull_request:
jobs:
generate-docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Generate API documentation
run: npm run docs:api
- name: Generate diagrams
run: npm run docs:diagrams
- name: Validate documentation
run: npm run docs:validate
- name: Check comment coverage
run: npm run docs:coverage
- name: Deploy to GitHub Pages
if: github.ref == 'refs/heads/main'
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./docs
Pre-commit Hook:
#!/bin/bash
# .git/hooks/pre-commit
echo "Checking documentation coverage..."
# Check for undocumented functions
undocumented=$(npm run --silent docs:check-coverage)
if [ $? -ne 0 ]; then
echo "❌ Documentation coverage below threshold"
echo "$undocumented"
echo ""
echo "Please add documentation to new functions before committing."
exit 1
fi
echo "✅ Documentation coverage acceptable"
# Generate all documentation
/doc-generate
# Generate specific documentation type
/doc-api # API documentation only
/doc-readme # README generation only
/doc-inline # Add inline comments only
/doc-diagrams # Generate diagrams only
# Generate with specific output format
npx claude-flow docs generate --format openapi --output docs/api.yml
# Generate for specific files
npx claude-flow docs generate --files "src/**/*.js" --type jsdoc
# Generate with custom templates
npx claude-flow docs generate --template custom-readme.hbs
# Update existing documentation
npx claude-flow docs update --incremental
# Validate documentation completeness
npx claude-flow docs validate --min-coverage 80
JavaScript/TypeScript (JSDoc):
/**
* Brief description (one sentence, under 100 chars)
*
* Detailed description explaining the purpose, behavior, and any
* important considerations. This can span multiple lines.
*
* @param {Type} paramName - Description of parameter
* @param {Type} [optionalParam=defaultValue] - Optional parameter
* @returns {Type} Description of return value
* @throws {ErrorType} When error occurs
*
* @example
* // Example usage
* const result = functionName(arg1, arg2);
*
* @see {@link RelatedFunction}
* @since 1.0.0
* @deprecated Use newFunction instead
*/
Python (Google Style):
def function_name(param1: str, param2: int = 0) -> bool:
"""Brief description (one sentence).
Detailed description explaining the purpose and behavior.
Can span multiple lines with proper formatting.
Args:
param1: Description of first parameter
param2: Description of optional parameter (default: 0)
Returns:
Description of return value
Raises:
ValueError: When invalid input provided
RuntimeError: When operation fails
Example:
>>> result = function_name("test", 5)
>>> print(result)
True
Note:
Important information or limitations
"""
# Project Title
> Brief description (one sentence tagline)
[Badges: Build, Coverage, License, Version]
## Features
- Key feature 1
- Key feature 2
- Key feature 3
## Quick Start
### Prerequisites
### Installation
### Basic Usage
## Documentation
- [API Reference](docs/API.md)
- [Architecture](docs/ARCHITECTURE.md)
- [Contributing](CONTRIBUTING.md)
- [Changelog](CHANGELOG.md)
## Examples
### Basic Example
### Advanced Example
## Configuration
## Testing
## Deployment
## Support
## License
Documentation Coverage Goals:
Validation Checks:
Issue: Generated docs missing some functions
export keyword usedIssue: Diagrams not rendering
brew install graphviz or apt install graphvizIssue: JSDoc comments not showing in IDE
tsconfig.jsonIssue: README badges not updating
Version: 1.0.0 Last Updated: 2025-10-30 Maintainer: Base Template Generator Status: Production Ready
development
Apple Human Interface Guidelines for content display components. Use this skill when the user asks about charts component, collection view, image view, web view, color well, image well, activity view, lockup, data visualization, content display, displaying images, rendering web content, color pickers, or presenting collections of items in Apple apps. Also use when the user says how should I display charts, what's the best way to show images, should I use a web view, how do I build a grid of items, what component shows media, or how do I present a share sheet. Cross-references: hig-foundations for color/typography/accessibility, hig-patterns for data visualization patterns, hig-components-layout for structural containers, hig-platforms for platform-specific component behavior.
tools
Automate HelpDesk tasks via Rube MCP (Composio): list tickets, manage views, use canned responses, and configure custom fields. Always search tools first for current schemas.
testing
Expert Haskell engineer specializing in advanced type systems, pure functional design, and high-reliability software. Use PROACTIVELY for type-level programming, concurrency, and architecture guidance.
tools
GraphQL gives clients exactly the data they need - no more, no less. One endpoint, typed schema, introspection. But the flexibility that makes it powerful also makes it dangerous. Without proper controls, clients can craft queries that bring down your server. This skill covers schema design, resolvers, DataLoader for N+1 prevention, federation for microservices, and client integration with Apollo/urql. Key insight: GraphQL is a contract. The schema is the API documentation. Design it carefully.