Skip to content
Back to skills

Code Documentation Skill

ASecurity

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.

  • 3 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added September 5, 2026
documentationjavascripttypescriptpythongojavaapidatabasesecurityperformancedocumentation

Works with

  • api

Security analysis

A100/100

Pro scans all 21 files and shows the line behind each finding

Scanned October 1, 2026

npx -y skills add sharmapuneet1510/awesome-prompts --skill skills --agent claude-code

Installs 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 with every re-scan.

Security grade badge for Code Documentation Skill
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/sharmapuneet1510-code-documentation-skill/badge)](https://www.skillsdirectory.com/skills/sharmapuneet1510-code-documentation-skill)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: Code Documentation Skill
version: 1.1
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.
applies_to: [java, python, javascript, typescript, documentation]
---

# Code Documentation Skill — v1.1

## Quick Card

> Read this card first. Load a section below only when the task needs it.

| | |
|---|---|
| **Use when** | Adding or fixing Javadoc, docstrings, or JSDoc — `implementer:doc`, or the doc phase of `implementer:full` |
| **Skip when** | Architecture narrative — that is `context_builder_skill` / `current_tech_spec_skill` |
| **Inputs** | Source files, the public API surface, existing comments |
| **Produces** | Method, class, and module docs in the language's native format |
| **Steps** | 1. Find undocumented public API → 2. Write the one-line summary first → 3. Params, returns, throws → 4. Example for non-obvious use → 5. Link related APIs |
| **Done when** | Every public method has summary, params, return, and exceptions; nothing restates the method name |
| **Load on demand** | §Tech-Specific Formats · §Implementation Workflow · §Quality Checklist · §Documentation Debt Fixing |
| **Run report** | `html_report_skill` — adds: Documentation coverage before → after |
| **Pairs with** | `java_advanced_skill` §5, `python_advanced_skill` §6 |

---

## 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:**
```text
Test Method → Apply code_documentation_skill → Add JSDoc/docstring
```

**Used by implementation_agent:**
```text
Generated Code → Apply code_documentation_skill → Fully documented code
```

**Used by code_review_agent:**
```text
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 (%)

Files in this skill

  • README.md10.2 KB
  • adr_skill.md8.4 KB
  • agent_skill_design_skill.md3.1 KB
  • apache_camel_skill.md15.5 KB
  • apache_pulsar_skill.md17.1 KB
  • ba_create_skill.md18.9 KB
  • backend_skill.md22.1 KB
  • code_documentation_skill.md13.4 KB
  • code_formatting_skill.md11.7 KB
  • code_health_skill.md9.8 KB
  • code_review_skill.md36.7 KB
  • context_builder_skill.md11.7 KB
  • current_tech_spec_skill.md6.3 KB
  • database_skill.md18.4 KB
  • debugging_skill.md3.4 KB
  • error_handling_skill.md18.4 KB
  • frontend_skill.md23.6 KB
  • java_advanced_skill.md15 KB
  • jira_html_report_skill.md15.5 KB
  • jira_incremental_spec_generator_skill.md19.7 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments

Loading comments…