Reusable skill for adding comprehensive documentation to code across all tech stacks. Generates JSDoc (JavaScript/TypeScript), docstrings (Python), Javadoc (Java), improves comments, and ensures 100% method documentation. Used by all agents.
Scanned 9/5/2026
Install to Claude Code
npx -y skills add sharmapuneet1510/awesome-prompts --skill skills --agent claude-codeInstalls into .claude/skills of the current project.
Are you the author of Code Documentation Skill?
Add the live security badge to your README — it updates automatically with every re-scan.
[](https://www.skillsdirectory.com/skills/sharmapuneet1510-code-documentation-skill)More formats (shields.io, HTML) on the badges page.
---
name: Code Documentation Skill
version: 1.0
description: >
Reusable skill for adding comprehensive documentation to code across all tech stacks.
Generates JSDoc (JavaScript/TypeScript), docstrings (Python), Javadoc (Java),
improves comments, and ensures 100% method documentation. Used by all agents.
---
# Code Documentation Skill — v1.0
## Purpose
Add professional, comprehensive documentation to any codebase. Ensures every public method, class, and module has clear documentation with examples, parameters, return types, and exceptions.
This skill is **reusable** — called by agents, not invoked directly by users.
---
## What It Does
Generates three levels of documentation:
1. **Method-Level Documentation** — JSDoc/docstrings/Javadoc for every method
2. **Class-Level Documentation** — Describes purpose, usage, relationships
3. **Module-Level Documentation** — Overview, examples, exports/imports
---
## Tech-Specific Documentation Formats
### JavaScript / TypeScript (JSDoc)
```javascript
/**
* Fetch user by ID from database.
*
* @param {number} userId - The unique user identifier
* @param {Object} options - Optional configuration
* @param {boolean} options.includeProfile - Include user profile (default: true)
* @returns {Promise<User>} User object with profile if requested
* @throws {UserNotFoundError} If user does not exist
* @example
* const user = await getUser(123);
* const userWithProfile = await getUser(123, { includeProfile: true });
*/
async function getUser(userId, options = {}) {
// Implementation
}
```
**JSDoc Tags Used:**
- `@param` — Parameter documentation with type
- `@returns` / `@return` — Return value and type
- `@throws` — Exceptions that can be thrown
- `@example` — Usage examples
- `@deprecated` — Deprecated methods
- `@see` — Related methods
- `@async` — Async functions
- `@private` — Internal methods
### Python (Google-Style Docstrings)
```python
def get_user(user_id: int, include_profile: bool = True) -> dict:
"""
Fetch user by ID from database.
Args:
user_id (int): The unique user identifier.
include_profile (bool, optional): Include user profile. Defaults to True.
Returns:
dict: User object with keys:
- id (int): User ID
- email (str): User email
- profile (dict): User profile if requested
Raises:
UserNotFoundError: If user does not exist.
DatabaseError: If database connection fails.
Examples:
Get user without profile:
>>> user = get_user(123)
Get user with profile:
>>> user = get_user(123, include_profile=True)
"""
# Implementation
```
**Docstring Sections:**
- `Args:` — Function arguments with types
- `Returns:` — Return value description
- `Raises:` — Exceptions that can be raised
- `Examples:` — Usage examples
- `Note:` — Important notes
- `Deprecation:` — Deprecation information
### Java (Javadoc)
```java
/**
* Fetch user by ID from database.
*
* <p>Retrieves a user record from the database with optional profile inclusion.
* Performance: O(1) lookup with index on user_id.
*
* @param userId the unique user identifier
* @param includeProfile {@code true} to include user profile, {@code false} otherwise
* @return the {@code User} object with profile if requested
* @throws UserNotFoundException if the user does not exist
* @throws DatabaseException if database connection fails
* @see User
* @see UserRepository
* @example
* User user = userService.getUser(123, true);
*/
public User getUser(int userId, boolean includeProfile) throws UserNotFoundException {
// Implementation
}
```
**Javadoc Tags:**
- `@param` — Method parameters
- `@return` — Return value
- `@throws` — Checked exceptions
- `@see` — Related methods/classes
- `@example` — Usage example
- `@deprecated` — Deprecated methods
- `@author` — Method author
- `@since` — Version introduced
---
## Implementation Workflow
### Phase 1: Analyze Code Structure
```python
def analyze_code(file_path, tech_stack):
"""
Scan code to identify:
1. All public methods/functions
2. Classes and their responsibilities
3. Module-level exports
4. Existing documentation gaps
"""
structures = {
'methods': [
{'name': 'getUser', 'params': [...], 'return': '...', 'has_doc': False},
...
],
'classes': [...],
'modules': [...]
}
return structures
```
### Phase 2: Extract Type Information
For each method, determine:
- **Parameter types** (from code, type hints, or JSDoc comments)
- **Return types** (inferred from return statements or annotations)
- **Exceptions** (from try-catch, throw statements, or function signatures)
- **Async behavior** (for JavaScript/TypeScript)
### Phase 3: Generate Documentation
Based on tech stack, generate appropriate format:
```python
def generate_doc(method, tech_stack):
if tech_stack == 'javascript' or tech_stack == 'typescript':
return generate_jsdoc(method)
elif tech_stack == 'python':
return generate_docstring(method)
elif tech_stack == 'java':
return generate_javadoc(method)
```
### Phase 4: Add Examples
For each public method, create at least one example:
```javascript
// JavaScript example usage
/**
* ...
* @example
* const user = await userService.getUser(123);
* console.log(user.name);
*/
# Python example usage
def get_user(user_id):
"""
...
Examples:
>>> user = get_user(123)
>>> print(user['name'])
"""
```
### Phase 5: Improve Comments
Review and improve inline comments:
```python
# BEFORE: Unclear comment
# check if user exists
if not user:
return None
# AFTER: Clear, descriptive comment
# Return None if user was deleted or never existed.
# This allows callers to distinguish from permission errors.
if not user:
return None
```
---
## Documentation Quality Checklist
Every method should have:
- ✅ **Clear description** — What does it do? (1-2 sentences)
- ✅ **Parameters documented** — Type, name, purpose, defaults
- ✅ **Return value documented** — Type, structure, meaning
- ✅ **Exceptions documented** — What can go wrong? When?
- ✅ **Example provided** — How to use it
- ✅ **Edge cases mentioned** — What about null, empty, boundary values?
- ✅ **Performance note** (if relevant) — O(n), O(1), blocking vs. async?
- ✅ **Related methods linked** — @see in Java, links in Python/JS
---
## Tech Stack Specifics
### JavaScript / TypeScript
**Tools:** JSDoc parser, TypeScript compiler
**Coverage:**
- All exported functions
- All class methods (public + protected)
- Async functions marked with `@async`
- Callbacks with proper type annotations
**Example Structure:**
```typescript
/**
* Type-safe user fetching with optional caching.
* @template T - User type
* @param {number} userId - User ID
* @param {Object} options - Configuration
* @param {T} options.defaultValue - Default if not found
* @returns {Promise<T>}
*/
async function getUser<T = User>(userId: number, options?: GetUserOptions<T>): Promise<T>
```
### Python
**Tools:** ast (abstract syntax tree), type hints
**Coverage:**
- All public functions (no leading `_`)
- All class methods
- Properties with `@property` decorator
- Async functions with `async def`
**Example Structure:**
```python
from typing import Optional, TypeVar
T = TypeVar('T')
def get_user(user_id: int, default: Optional[T] = None) -> Optional[T]:
"""
Fetch user with type hints.
Args:
user_id: The user's unique identifier
default: Default value if user not found
Returns:
User object or default value if not found
"""
```
### Java
**Tools:** Javadoc generator, reflection
**Coverage:**
- All public methods
- All public classes
- Inner classes
- Enums
- Annotations
**Example Structure:**
```java
/**
* Fetch user with proper generics documentation.
*
* @param <T> the user type, must extend {@code AbstractUser}
* @param userId the user ID
* @return an {@code Optional} containing the user if found
*/
public <T extends AbstractUser> Optional<T> getUser(int userId) {
// Implementation
}
```
---
## Business vs. Technical Documentation
### Technical Documentation (Always)
```javascript
/**
* Parse JWT token and extract claims.
* @param {string} token - JWT token (format: header.payload.signature)
* @param {string} secret - Signing secret for validation
* @returns {Object} Decoded claims object
* @throws {TokenExpiredError} If token has expired
* @throws {InvalidSignatureError} If signature does not match
*/
```
### Business Documentation (From Requirements/JIRA)
```javascript
/**
* Parse JWT token and extract claims.
*
* Used to verify user identity during login flow (JIRA: AUTH-456).
* Validates that token was issued by our server and hasn't expired.
*
* @param {string} token - JWT token from login request
* @param {string} secret - Signing secret for validation
* @returns {Object} Decoded claims object with:
* - userId: User identifier (required by downstream services)
* - email: User email (used for audit logging)
* - roles: User roles (determines authorization level)
*
* @throws {TokenExpiredError} Token expired - user must re-login (business impact: force logout)
* @throws {InvalidSignatureError} Token tampered - reject request (security: prevent unauthorized access)
*
* @business AUTH-456: User authentication flow requires token validation
* @business PERF-789: Must validate within 50ms (login page timeout requirement)
*/
```
---
## When This Skill Is Used
Called by:
- **test-case-generator** — Document every test method with business requirement links
- **implementation_agent** — Document generated code (STEP 7)
- **code_review_agent** — Suggest missing documentation
- **writer_agent** — Generate comprehensive API docs
- **autonomous_dev_agent** — Document all generated code
---
## Documentation Debt Fixing
When improving existing code:
```python
# Priority 1: Methods with NO documentation
# (Major issue, fixes first)
# Priority 2: Methods with incomplete documentation
# (Missing examples, exceptions, edge cases)
# Priority 3: Unclear comments
# (Improve readability, explain WHY not WHAT)
# Priority 4: Missing type hints (Python) / JSDoc types (JS)
```
---
## Success Criteria
Documentation is complete when:
- ✅ 100% of public methods have full JSDoc/docstrings/Javadoc
- ✅ Every parameter is documented with type and purpose
- ✅ Every return value is documented with structure
- ✅ All possible exceptions are documented
- ✅ At least one usage example per method
- ✅ Business requirements linked (if from JIRA)
- ✅ No unclear comments (improved readability)
- ✅ Type hints/annotations present (where applicable)
---
## Example Outputs
### Before (No Documentation)
```python
def calculate_total_with_tax(items, tax_rate, discount=0):
subtotal = sum(item['price'] for item in items)
if discount:
subtotal *= (1 - discount / 100)
total = subtotal * (1 + tax_rate / 100)
return round(total, 2)
```
### After (Full Documentation)
```python
def calculate_total_with_tax(
items: list[dict],
tax_rate: float,
discount: float = 0
) -> float:
"""
Calculate final order total with tax and discount.
Applies discount first (e.g., coupon), then tax. Used in checkout flow (JIRA: CHECKOUT-234).
Follows accounting standard: discount before tax calculation.
Args:
items: List of cart items, each with 'price' key (in cents, as integer)
tax_rate: Tax percentage (e.g., 8.5 for 8.5%)
discount: Discount percentage (0-100), applied to subtotal
Returns:
float: Final total rounded to 2 decimal places (cents)
Raises:
ValueError: If tax_rate or discount is negative or > 100
KeyError: If any item missing 'price' key
Examples:
Simple order with tax:
>>> items = [{'price': 1000}, {'price': 500}] # $10 + $5
>>> calculate_total_with_tax(items, tax_rate=8.5)
16.27 # $15 + 8.5% tax
With discount (coupon):
>>> calculate_total_with_tax(items, tax_rate=8.5, discount=10)
14.64 # $13.50 after 10% discount + 8.5% tax
Note:
Discount is applied BEFORE tax (standard accounting practice).
This affects the tax base and final amount.
Business: CHECKOUT-234 requires discount before tax calculation
Performance: O(n) where n = number of items
"""
if tax_rate < 0 or tax_rate > 100:
raise ValueError(f"Tax rate must be 0-100, got {tax_rate}")
if discount < 0 or discount > 100:
raise ValueError(f"Discount must be 0-100, got {discount}")
subtotal = sum(item['price'] for item in items)
if discount:
subtotal *= (1 - discount / 100)
total = subtotal * (1 + tax_rate / 100)
return round(total, 2)
```
---
## Tool Integration
**Used by test-case-generator:**
```
Test Method → Apply code_documentation_skill → Add JSDoc/docstring
```
**Used by implementation_agent:**
```
Generated Code → Apply code_documentation_skill → Fully documented code
```
**Used by code_review_agent:**
```
Code Review → Check documentation coverage → Flag missing docs
```
---
## Future Enhancements
- Markdown documentation generation (README sections)
- API documentation (OpenAPI, Swagger)
- Architecture documentation diagrams
- Living documentation (auto-update from code changes)
- Documentation coverage tracking (%)
Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.
No comments yet. Be the first to comment!