document-code
Generates documentation for code including function/class docstrings, module READMEs, API documentation, inline comments, and architecture overviews. Use when the user says "document this", "add docs", "add comments", "generate README", "what does this code do?", "write API docs", or "this needs documentation".
What this skill does
# Document Code Skill When documenting code, follow this structured process. Good documentation explains WHY, not just WHAT. The code already shows what it does — documentation should explain the intent, context, trade-offs, and gotchas. ## 1. Understand Before Documenting Before writing any documentation: - **Read the code thoroughly** — understand the full context - **Identify the audience** — is this for new team members, API consumers, future maintainers, or yourself? - **Check existing docs** — don't duplicate or contradict what already exists - **Understand the architecture** — how does this code fit into the bigger picture? ## 2. Documentation Types Determine what kind of documentation is needed: | Type | When to Use | |------|-------------| | **Inline comments** | Complex logic, workarounds, non-obvious decisions | | **Function/method docstrings** | Every public function, method, and class | | **Module/file headers** | Every file that isn't self-explanatory from its name | | **README** | Every module, package, or service | | **API documentation** | Every endpoint consumers interact with | | **Architecture docs** | System design, data flow, component relationships | | **Changelog** | Tracking changes between versions | | **Migration guides** | Breaking changes that require action | ## 3. Inline Comments ### When to Comment - **Complex algorithms** — explain the approach, not each line - **Workarounds and hacks** — explain WHY and link to the issue/ticket - **Non-obvious business rules** — explain the domain logic - **Performance choices** — explain why a less readable approach was chosen - **Regex patterns** — always explain what they match - **Magic numbers** — explain where they come from ### When NOT to Comment - Don't restate what the code already says - Don't comment every line - Don't leave commented-out code (use version control) - Don't write TODOs without ticket numbers ``` // 🔴 BAD — restates the code // Set age to 18 const age = 18; // ✅ GOOD — explains WHY // Minimum age required by COPPA compliance (Children's Online Privacy Protection Act) const MINIMUM_AGE = 18; // 🔴 BAD — vague TODO // TODO: fix this later // ✅ GOOD — actionable TODO // TODO(JIRA-1234): Replace with batch query once the ORM supports it. Current N+1 // causes ~200ms latency on pages with 50+ items. // ✅ GOOD — explains a workaround // HACK: Safari doesn't support the CSS gap property in flex containers on iOS < 14.5. // Using margin-based spacing instead. Remove when we drop iOS 14 support. // See: https://bugs.webkit.org/show_bug.cgi?id=XXXXX // ✅ GOOD — explains regex // Matches email addresses: [email protected] // Allows: letters, numbers, dots, hyphens, underscores in local part // Requires: at least one dot in domain, 2-63 char TLD const EMAIL_REGEX = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$/; ``` ## 4. Function & Method Documentation Every public function should document: - **What it does** — one-line summary - **Parameters** — name, type, description, constraints, defaults - **Return value** — type, description, possible values - **Errors/exceptions** — what can go wrong and when - **Examples** — at least one usage example for non-trivial functions - **Side effects** — database writes, API calls, file changes, event emissions ## 5. Stack-Specific Docstring Formats ### TypeScript / JavaScript (TSDoc / JSDoc) ```typescript /** * Calculates the shipping cost for an order based on weight, destination, and shipping method. * * Uses the carrier's rate table for standard/express and falls back to flat-rate * pricing for international destinations not in the rate table. * * @param order - The order containing items with weight and dimensions * @param destination - Shipping address with country and postal code * @param method - Shipping method: 'standard' (5-7 days), 'express' (1-2 days), or 'overnight' * @returns The calculated shipping cost in cents (USD). Returns 0 for orders over $100 (free shipping promo) * @throws {InvalidAddressError} If the destination address cannot be validated * @throws {CarrierUnavailableError} If no carrier supports the destination country * * @example * const cost = await calculateShipping(order, { country: 'US', postal: '90210' }, 'standard'); * // Returns: 599 (i.e., $5.99) * * @see {@link ShippingRateTable} for carrier rate configuration * @since 2.1.0 */ async function calculateShipping( order: Order, destination: Address, method: ShippingMethod ): Promise<number> { ... } ``` ### TypeScript Interfaces and Types ```typescript /** * Represents a user account in the system. * * Created during registration and updated via the profile settings page. * Soft-deleted when the user requests account deletion (retained for 30 days per compliance policy). */ interface User { /** Unique identifier (UUIDv4), generated at creation */ id: string; /** User's email address, used for login. Must be unique and verified. */ email: string; /** Display name shown in the UI. 2-50 characters, no special characters. */ name: string; /** * User's role determining access level. * - 'viewer': Read-only access to shared resources * - 'editor': Can create and modify own resources * - 'admin': Full access including user management */ role: 'viewer' | 'editor' | 'admin'; /** ISO 8601 timestamp of account creation */ createdAt: string; /** ISO 8601 timestamp of last login, null if never logged in */ lastLoginAt: string | null; } ``` ### Python (Google Style Docstrings) ```python def calculate_shipping(order: Order, destination: Address, method: str = "standard") -> int: """Calculate shipping cost for an order based on weight and destination. Uses the carrier's rate table for domestic shipments and falls back to flat-rate pricing for international destinations not in the rate table. Args: order: The order containing items with weight and dimensions. destination: Shipping address with country and postal code. method: Shipping method. One of 'standard' (5-7 days), 'express' (1-2 days), or 'overnight'. Defaults to 'standard'. Returns: Shipping cost in cents (USD). Returns 0 for orders over $100 due to the free shipping promotion. Raises: InvalidAddressError: If the destination address cannot be validated against the carrier's address database. CarrierUnavailableError: If no carrier supports the destination country. Example: >>> cost = calculate_shipping(order, Address(country="US", postal="90210")) >>> print(cost) 599 # $5.99 Note: International rates are refreshed daily at midnight UTC from the carrier API. Cached rates may be up to 24 hours stale. """ ``` ### Python Classes ```python class OrderProcessor: """Processes orders from cart submission through fulfillment. Handles the complete order lifecycle: validation, payment capture, inventory reservation, and shipping label generation. Uses the saga pattern to ensure all steps complete or roll back atomically. Attributes: payment_gateway: The payment provider client (Stripe/PayPal). inventory_service: Service for checking and reserving stock. notification_service: Sends order confirmation emails and SMS. Example: >>> processor = OrderProcessor( ... payment_gateway=StripeClient(), ... inventory_service=InventoryService(), ... ) >>> result = await processor.process(cart, user) >>> print(result.order_id) 'ord_abc123' Note: This class is NOT thread-safe. Use one instance per request in web applications. """ ``` ### Go (Godoc) ```go // CalculateShipping returns the shipping cost in cents for the given order. // // It uses the carrier's rate table for domestic shipments and falls back // to flat-rate pricing fo
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.