Documentation Standards
Code Comments
#documentation #comments #code-clarity
Comments should explain why, not what. Code should be self-explanatory for the "what".
Good Examples:
// Bad: States the obvious
// Set timeout to 30 seconds
let timeout = from_secs;
// Good: Explains reasoning
// Use 30 second timeout to prevent hanging on slow networks
// while still allowing large file uploads to complete
let timeout = from_secs;
// Good: Explains non-obvious business logic
// We retry up to 3 times because the payment gateway
// sometimes returns 500 errors on successful charges
const MAX_RETRY_ATTEMPTS: usize = 3;When to Comment:
- Why a particular approach was chosen
- Trade-offs and alternatives considered
- Workarounds for bugs or limitations
- Context from requirements or business rules
- TODOs with issue tracker references
When NOT to Comment:
- Obvious code that matches function name
- Restating what types already convey
- Commented-out code (delete it, use git)
- Obsolete comments that don't match code
Function Documentation
#documentation #rustdoc #docstrings #jsdoc
Document public APIs with examples and edge cases.
Rust (rustdoc)
#rust #rustdoc #documentation
/// Searches for documents matching the given query.
///
/// This function performs semantic search using the knowledge graph
/// to expand queries with related concepts.
///
/// # Arguments
///
/// * `query` - The search term to look for
/// * `role` - The role context for search (uses default if None)
/// * `limit` - Maximum number of results to return
///
/// # Returns
///
/// A `Result` containing:
/// - `Ok(SearchResults)` - Documents matching the query with relevance scores
/// - `Err(ServiceError)` - If the search fails or role is invalid
///
/// # Errors
///
/// This function will return an error if:
/// - The role does not exist
/// - The knowledge graph is not initialized
/// - The search backend is unavailable
///
/// # Examples
///
/// ```rust
/// # use terraphim_service::*;
/// # async fn example() -> Result<()> {
/// let service = TerraphimService::new(config);
/// let results = service.search("async patterns", Some("Rust Engineer"), 10).await?;
///
/// for doc in results.documents {
/// println!("{}: {}", doc.url, doc.description);
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Performance
///
/// This function typically completes in 50-200ms depending on:
/// - Knowledge graph size (larger graphs take longer)
/// - Number of matching documents
/// - Whether results are cached
///
/// # See Also
///
/// - [`autocomplete_terms`] for term suggestions
/// - [`find_related_concepts`] for graph traversal
pub async Python (docstrings)
#python #docstrings #documentation
"""Search for documents matching the given query.
This function performs semantic search using the knowledge graph
to expand queries with related concepts.
Args:
query: The search term to look for
role: The role context for search (uses default if None)
limit: Maximum number of results to return
Returns:
SearchResults containing documents with relevance scores
Raises:
ValueError: If the role does not exist
ServiceError: If the search backend is unavailable
Examples:
>>> service = TerraphimService(config)
>>> results = service.search("async patterns", role="Rust Engineer")
>>> for doc in results.documents:
... print(f"{doc.url}: {doc.description}")
Note:
This function typically completes in 50-200ms depending on
knowledge graph size and result caching.
See Also:
- autocomplete_terms: For term suggestions
- find_related_concepts: For graph traversal
"""TypeScript (JSDoc)
#typescript #jsdoc #documentation
/**
* Searches for documents matching the given query.
*
* This function performs semantic search using the knowledge graph
* to expand queries with related concepts.
*
* @param query - The search term to look for
* @param role - The role context for search (uses default if undefined)
* @param limit - Maximum number of results to return
*
* @returns A Promise resolving to SearchResults with matching documents
*
* @throws {ValueError} If the role does not exist
* @throws {ServiceError} If the search backend is unavailable
*
* @example
* ```typescript
* const service = new TerraphimService(config);
* const results = await service.search("async patterns", "Rust Engineer", 10);
*
* for (const doc of results.documents) {
* console.log(`${doc.url}: ${doc.description}`);
* }
* ```
*
* @remarks
* This function typically completes in 50-200ms depending on
* knowledge graph size and result caching.
*
* @see {@link autocompleteTerms} for term suggestions
* @see {@link findRelatedConcepts} for graph traversal
*/
async function search(
query: string,
role?: string,
limit: number = 10
): Promise<SearchResults>Module Documentation
#modules #packages #overview
Every module should have a top-level comment explaining its purpose.
Rust
//! # User Session Management
//!
//! This module provides functionality for managing user sessions,
//! including authentication, authorization, and session lifecycle.
//!
//! ## Features
//!
//! - JWT-based authentication
//! - Role-based access control (RBAC)
//! - Automatic session refresh
//! - Multi-device session management
//!
//! ## Usage
//!
//! ```rust
//! use user_session::{SessionManager, SessionConfig};
//!
//! let config = SessionConfig::default();
//! let manager = SessionManager::new(config);
//!
//! let session = manager.create_session(&user).await?;
//! ```
//!
//! ## Architecture
//!
//! Sessions are stored in Redis with TTL-based expiration.
//! Each session contains:
//! - User ID
//! - Device fingerprint
//! - Permissions snapshot
//! - Expiration timestamp
Python
"""User Session Management
This module provides functionality for managing user sessions,
including authentication, authorization, and session lifecycle.
Features:
- JWT-based authentication
- Role-based access control (RBAC)
- Automatic session refresh
- Multi-device session management
Example:
>>> from user_session import SessionManager, SessionConfig
>>> config = SessionConfig()
>>> manager = SessionManager(config)
>>> session = manager.create_session(user)
Architecture:
Sessions are stored in Redis with TTL-based expiration.
Each session contains:
- User ID
- Device fingerprint
- Permissions snapshot
- Expiration timestamp
"""
Type Documentation
#types #structs #interfaces
Document complex types with field explanations.
Rust
/// Configuration for the Terraphim service.
///
/// This struct defines all runtime settings including knowledge graph
/// configuration, LLM providers, and haystack data sources.
TypeScript
/**
* Configuration for the Terraphim service.
*
* This interface defines all runtime settings including knowledge graph
* configuration, LLM providers, and haystack data sources.
*/
interface ServiceConfig {
/**
* The role name for this configuration.
* Must match an entry in the roles map.
*/
role: string;
/**
* Knowledge graph configuration.
* If undefined, knowledge graph features are disabled.
*/
kg?: KnowledgeGraphConfig;
/**
* Data sources for search and indexing.
* At least one haystack is required for search to work.
*/
haystacks: HaystackConfig[];
/**
* LLM provider: "ollama", "openrouter", or custom.
*/
llmProvider: string;
/**
* Base URL for LLM API.
* - For Ollama: "http://127.0.0.1:11434"
* - For OpenRouter: "https://openrouter.ai/api/v1"
*/
llmBaseUrl: string;
/**
* Model identifier.
* Examples: "llama3.2:3b", "anthropic/claude-3-opus"
*/
llmModel: string;
}TODO Comments
#todo #fixme #issues
Use TODO comments with issue tracker references.
Good Examples:
// TODO(#123): Implement pagination for large result sets
// FIXME(#456): Memory leak in session cleanup - need to investigate
// HACK(#789): Temporary workaround for upstream bug in dependency X
// NOTE: This approach was chosen to avoid breaking API compatibilityBad Examples:
// TODO: fix this
// FIXME: broken
// NOTE: weirdCategories:
TODO: Feature or improvement to implementFIXME: Known bug that needs fixingHACK: Workaround that should be replacedNOTE: Important context for maintainersWARN: Dangerous code requiring caution
Format: CATEGORY(#issue): Description
Example Documentation
#examples #tutorials #guides
Provide runnable examples for complex functionality.
/// # Examples
///
/// ## Basic Usage
///
/// ```rust
/// use terraphim_service::TerraphimService;
///
/// # async fn example() -> Result<()> {
/// let service = TerraphimService::new(config);
/// let results = service.search("async").await?;
/// # Ok(())
/// # }
/// ```
///
/// ## With Custom Role
///
/// ```rust
/// # use terraphim_service::*;
/// # async fn example() -> Result<()> {
/// let service = TerraphimService::new(config);
/// let results = service.search_with_role("async", "Rust Engineer").await?;
/// # Ok(())
/// # }
/// ```
///
/// ## Error Handling
///
/// ```rust
/// # use terraphim_service::*;
/// # async fn example() {
/// let service = TerraphimService::new(config);
///
/// match service.search("query").await {
/// Ok(results) => {
/// println!("Found {} results", results.len());
/// }
/// Err(ServiceError::RoleNotFound { role }) => {
/// eprintln!("Invalid role: {}", role);
/// }
/// Err(e) => {
/// eprintln!("Search failed: {}", e);
/// }
/// }
/// # }
/// ```README Files
#readme #documentation #getting-started
Every project and significant module should have a README.
Structure:
- Title and Description: What is this?
- Installation: How to get it?
- Quick Start: Simplest working example
- Usage: Common scenarios
- Configuration: Options and settings
- API Reference: Link to full docs
- Examples: More complex use cases
- Contributing: How to help
- License: Legal information
Example:
- ---
Changelog
#changelog #versioning #releases
Maintain a CHANGELOG.md following Keep a Changelog.
- -
-
- --
- -
-
-
- -
-
Related Patterns
See also:
- [[naming-conventions]] - Choosing good names
- [[code-organization]] - Structuring code
- [[testing]] - Test documentation
- [[api-design]] - Public API documentation