Code Documenter
Overview
Analyzes source code to generate accurate, context-aware documentation at multiple levels: inline comments for complex logic, function/class docstrings, module-level overviews, architecture documents, and onboarding guides. Understands control flow, data transformations, side effects, and cross-module dependencies.
Instructions
When asked to document code:
Determine the documentation level needed:
- Inline: Function/method docstrings, JSDoc, Python docstrings, Go doc comments
- Module: README or header comment explaining the module's purpose and exports
- Architecture: High-level document showing how modules interact, data flows, key design decisions
- Onboarding: Getting-started guide for new team members
For function/method documentation, extract:
- Purpose: What does this function do? (one sentence)
- Parameters: name, type, description, default values, constraints
- Return value: type, description, possible values
- Side effects: database writes, API calls, file I/O, state mutations, cache invalidation
- Exceptions/errors: what can go wrong, when, and what error types
- Example usage: realistic call with realistic data
For complex logic, add inline comments explaining:
- WHY, not WHAT — explain the reasoning, not the obvious operation
- Business rules embedded in conditionals
- Performance-critical sections and why they're written a certain way
- Workarounds with links to issues/bugs if available in git history
- Non-obvious algorithm choices
For architecture documentation:
- Map module dependencies (imports/requires graph)
- Identify entry points (API handlers, CLI commands, event listeners)
- Trace key data flows through the system (e.g., "user signup" flow)
- Document configuration and environment variables
- List external service dependencies (databases, APIs, queues)
- Note design patterns used (repository pattern, event sourcing, CQRS, etc.)
Language-specific format:
- TypeScript/JavaScript: JSDoc with
@param, @returns, @throws, @example
- Python: Google-style docstrings with Args, Returns, Raises sections
- Go: Package-level and exported function doc comments per Go conventions
- Java: Javadoc with
@param, @return, @throws
- Rust:
/// doc comments with # Examples sections
Quality rules:
- Never state the obvious ("Increments counter by 1")
- Document the contract, not the implementation (what, not how — unless the how is surprising)
- Include realistic example values, not
foo, bar, test123
- Flag functions that are too complex and suggest refactoring before documenting
- Note when documentation reveals a likely bug (e.g., unhandled null case)
Examples
Example 1: Document a Python function
Input:
def process_payment(user_id, amount, currency, idempotency_key=None):
user = db.users.find(user_id)
if not user:
raise ValueError("User not found")
if user.balance < amount and not user.credit_enabled:
return {"status": "declined", "reason": "insufficient_funds"}
charge = stripe.charges.create(
amount=int(amount * 100),
currency=currency,
customer=user.stripe_id,
idempotency_key=idempotency_key
)
db.transactions.insert({
"user_id": user_id, "amount": amount,
"stripe_charge_id": charge.id, "created_at": datetime.utcnow()
})
if user.balance < amount:
user.balance = user.balance - amount
db.users.update(user)
return {"status": "success", "charge_id": charge.id}
Output:
def process_payment(user_id, amount, currency, idempotency_key=None):
"""Process a payment by charging the user's Stripe account.
Validates the user's balance (unless credit is enabled), creates a Stripe
charge, records the transaction, and deducts from the user's internal balance
if applicable.
Args:
user_id: Internal user identifier (e.g., "usr_8f2k3j").
amount: Charge amount in major currency units (e.g., 49.99).
currency: ISO 4217 currency code (e.g., "usd", "eur").
idempotency_key: Optional key to prevent duplicate charges on retry.
Recommended for all production calls.
Returns:
dict: {"status": "success", "charge_id": "ch_..."} on success,
{"status": "declined", "reason": "insufficient_funds"} if balance
is too low and credit is not enabled.
Raises:
ValueError: If user_id does not match any user in the database.
stripe.error.CardError: If the card is declined by Stripe.
stripe.error.InvalidRequestError: If Stripe parameters are invalid.
Side Effects:
- Creates a Stripe charge (external API call)
- Inserts a row into the transactions table
- May update the user's balance
Example:
>>> result = process_payment("usr_8f2k3j", 49.99, "usd", idempotency_key="pay_retry_001")
>>> result
{"status": "success", "charge_id": "ch_3Kx9mPqR2s"}
Note:
⚠ Potential bug: balance deduction only happens when balance < amount,
but the charge always goes through. If balance >= amount, the user is
charged via Stripe but their internal balance is not deducted.
"""
Example 2: Generate architecture overview
Input:
Document the architecture of our notification service in src/services/notifications/
Output:
# Notification Service — Architecture
## Purpose
Delivers user notifications across email, push, and in-app channels.
Handles template rendering, delivery scheduling, preference checking,
and delivery status tracking.
## Module Map
notifications/
├── router.ts — HTTP endpoints for notification preferences and history
├── service.ts — Core orchestration: resolves channel, renders template, dispatches
├── channels/
│ ├── email.ts — SendGrid integration (SMTP fallback)
│ ├── push.ts — Firebase Cloud Messaging
│ └── in-app.ts — WebSocket broadcast + database persistence
├── templates/
│ ├── renderer.ts — Handlebars template engine with i18n support
│ └── templates/ — .hbs files organized by notification type
├── preferences.ts — User channel preferences (opt-in/opt-out per type)
└── queue.ts — Bull queue consumer for async delivery
## Key Data Flow: Sending a Notification
1. API call or internal event → service.send(userId, type, data)
2. service.ts checks user preferences → skips opted-out channels
3. renderer.ts renders template with user's locale
4. Dispatch queued via Bull (Redis-backed) for reliability
5. Channel adapter delivers and records status in notifications table
## External Dependencies
- SendGrid API (email delivery)
- Firebase Cloud Messaging (push notifications)
- Redis (Bull queue backing store)
- PostgreSQL (notification history, preferences, templates metadata)
## Environment Variables
SENDGRID_API_KEY, FCM_SERVER_KEY, REDIS_URL, NOTIFICATION_FROM_EMAIL
Guidelines
- Read the code before documenting — understand the actual behavior, not just function names.
- When you spot bugs or inconsistencies during documentation, flag them explicitly.
- Architecture docs should be useful to a new engineer on day 1 — no assumed context.
- Keep docstrings focused on the contract. Move implementation details to inline comments.
- For modules with no tests, note it: "⚠ No test coverage — documented behavior is inferred from code."
- Update documentation when the code changes — stale docs are worse than no docs.
1---2name: code-documenter3description: >-4 Generate comprehensive documentation for undocumented or poorly documented5 codebases. Use when a user asks to document code, add JSDoc/docstrings,6 create README files, generate architecture docs, explain what a codebase does,7 produce onboarding guides, or document internal APIs. Works with any language.8license: Apache-2.09compatibility: "Supports TypeScript, JavaScript, Python, Go, Java, Rust, Ruby, C#, and PHP."10metadata:11 source: https://skillmd.com/skills/eliferjunior/code-documenter12 author: terminal-skills13 version: "1.0.0"14 category: development15 tags: ["documentation", "jsdoc", "docstrings", "architecture", "onboarding"]16---1718# Code Documenter1920## Overview2122Analyzes source code to generate accurate, context-aware documentation at multiple levels: inline comments for complex logic, function/class docstrings, module-level overviews, architecture documents, and onboarding guides. Understands control flow, data transformations, side effects, and cross-module dependencies.2324## Instructions2526When asked to document code:27281. **Determine the documentation level needed:**29 - **Inline**: Function/method docstrings, JSDoc, Python docstrings, Go doc comments30 - **Module**: README or header comment explaining the module's purpose and exports31 - **Architecture**: High-level document showing how modules interact, data flows, key design decisions32 - **Onboarding**: Getting-started guide for new team members33342. **For function/method documentation, extract:**35 - Purpose: What does this function do? (one sentence)36 - Parameters: name, type, description, default values, constraints37 - Return value: type, description, possible values38 - Side effects: database writes, API calls, file I/O, state mutations, cache invalidation39 - Exceptions/errors: what can go wrong, when, and what error types40 - Example usage: realistic call with realistic data41423. **For complex logic, add inline comments explaining:**43 - WHY, not WHAT — explain the reasoning, not the obvious operation44 - Business rules embedded in conditionals45 - Performance-critical sections and why they're written a certain way46 - Workarounds with links to issues/bugs if available in git history47 - Non-obvious algorithm choices48494. **For architecture documentation:**50 - Map module dependencies (imports/requires graph)51 - Identify entry points (API handlers, CLI commands, event listeners)52 - Trace key data flows through the system (e.g., "user signup" flow)53 - Document configuration and environment variables54 - List external service dependencies (databases, APIs, queues)55 - Note design patterns used (repository pattern, event sourcing, CQRS, etc.)56575. **Language-specific format:**58 - TypeScript/JavaScript: JSDoc with `@param`, `@returns`, `@throws`, `@example`59 - Python: Google-style docstrings with Args, Returns, Raises sections60 - Go: Package-level and exported function doc comments per Go conventions61 - Java: Javadoc with `@param`, `@return`, `@throws`62 - Rust: `///` doc comments with `# Examples` sections63646. **Quality rules:**65 - Never state the obvious ("Increments counter by 1")66 - Document the contract, not the implementation (what, not how — unless the how is surprising)67 - Include realistic example values, not `foo`, `bar`, `test123`68 - Flag functions that are too complex and suggest refactoring before documenting69 - Note when documentation reveals a likely bug (e.g., unhandled null case)7071## Examples7273### Example 1: Document a Python function7475**Input:**76```python77def process_payment(user_id, amount, currency, idempotency_key=None):78 user = db.users.find(user_id)79 if not user:80 raise ValueError("User not found")81 if user.balance < amount and not user.credit_enabled:82 return {"status": "declined", "reason": "insufficient_funds"}83 charge = stripe.charges.create(84 amount=int(amount * 100),85 currency=currency,86 customer=user.stripe_id,87 idempotency_key=idempotency_key88 )89 db.transactions.insert({90 "user_id": user_id, "amount": amount,91 "stripe_charge_id": charge.id, "created_at": datetime.utcnow()92 })93 if user.balance < amount:94 user.balance = user.balance - amount95 db.users.update(user)96 return {"status": "success", "charge_id": charge.id}97```9899**Output:**100```python101def process_payment(user_id, amount, currency, idempotency_key=None):102 """Process a payment by charging the user's Stripe account.103104 Validates the user's balance (unless credit is enabled), creates a Stripe105 charge, records the transaction, and deducts from the user's internal balance106 if applicable.107108 Args:109 user_id: Internal user identifier (e.g., "usr_8f2k3j").110 amount: Charge amount in major currency units (e.g., 49.99).111 currency: ISO 4217 currency code (e.g., "usd", "eur").112 idempotency_key: Optional key to prevent duplicate charges on retry.113 Recommended for all production calls.114115 Returns:116 dict: {"status": "success", "charge_id": "ch_..."} on success,117 {"status": "declined", "reason": "insufficient_funds"} if balance118 is too low and credit is not enabled.119120 Raises:121 ValueError: If user_id does not match any user in the database.122 stripe.error.CardError: If the card is declined by Stripe.123 stripe.error.InvalidRequestError: If Stripe parameters are invalid.124125 Side Effects:126 - Creates a Stripe charge (external API call)127 - Inserts a row into the transactions table128 - May update the user's balance129130 Example:131 >>> result = process_payment("usr_8f2k3j", 49.99, "usd", idempotency_key="pay_retry_001")132 >>> result133 {"status": "success", "charge_id": "ch_3Kx9mPqR2s"}134135 Note:136 ⚠ Potential bug: balance deduction only happens when balance < amount,137 but the charge always goes through. If balance >= amount, the user is138 charged via Stripe but their internal balance is not deducted.139 """140```141142### Example 2: Generate architecture overview143144**Input:**145```146Document the architecture of our notification service in src/services/notifications/147```148149**Output:**150```markdown151# Notification Service — Architecture152153## Purpose154Delivers user notifications across email, push, and in-app channels.155Handles template rendering, delivery scheduling, preference checking,156and delivery status tracking.157158## Module Map159 notifications/160 ├── router.ts — HTTP endpoints for notification preferences and history161 ├── service.ts — Core orchestration: resolves channel, renders template, dispatches162 ├── channels/163 │ ├── email.ts — SendGrid integration (SMTP fallback)164 │ ├── push.ts — Firebase Cloud Messaging165 │ └── in-app.ts — WebSocket broadcast + database persistence166 ├── templates/167 │ ├── renderer.ts — Handlebars template engine with i18n support168 │ └── templates/ — .hbs files organized by notification type169 ├── preferences.ts — User channel preferences (opt-in/opt-out per type)170 └── queue.ts — Bull queue consumer for async delivery171172## Key Data Flow: Sending a Notification173 1. API call or internal event → service.send(userId, type, data)174 2. service.ts checks user preferences → skips opted-out channels175 3. renderer.ts renders template with user's locale176 4. Dispatch queued via Bull (Redis-backed) for reliability177 5. Channel adapter delivers and records status in notifications table178179## External Dependencies180 - SendGrid API (email delivery)181 - Firebase Cloud Messaging (push notifications)182 - Redis (Bull queue backing store)183 - PostgreSQL (notification history, preferences, templates metadata)184185## Environment Variables186 SENDGRID_API_KEY, FCM_SERVER_KEY, REDIS_URL, NOTIFICATION_FROM_EMAIL187```188189## Guidelines190191- Read the code before documenting — understand the actual behavior, not just function names.192- When you spot bugs or inconsistencies during documentation, flag them explicitly.193- Architecture docs should be useful to a new engineer on day 1 — no assumed context.194- Keep docstrings focused on the contract. Move implementation details to inline comments.195- For modules with no tests, note it: "⚠ No test coverage — documented behavior is inferred from code."196- Update documentation when the code changes — stale docs are worse than no docs.