Generate comprehensive documentation for APIs, architecture, components, or features
Generates comprehensive documentation for APIs, architecture, components, or features with validation.
/plugin marketplace add squirrelsoft-dev/agency/plugin install agency@squirrelsoft-dev-toolstopic (api/architecture/component/feature/code/auto)Generate comprehensive, accurate documentation with examples and validation.
Generate documentation for: $ARGUMENTS
Follow the documentation lifecycle: detect scope → generate content → review quality → validate examples → publish.
IMMEDIATELY activate the agency workflow patterns skill:
Use the Skill tool to activate: agency-workflow-patterns
This skill contains critical orchestration patterns, agent selection guidelines, and workflow strategies you MUST follow.
Technology-Specific Skills: After detecting the project framework and documentation system, activate relevant skills:
typescript-5-expertnextjs-16-expertRefer to prompts/specialist-selection/skill-activation.md for complete skill activation guidelines.
Quickly gather project context to determine documentation approach and templates.
<!-- Component: prompts/context/framework-detection.md -->Execute framework detection to identify the project's primary technology stack. This determines:
Use the detection algorithm from prompts/context/framework-detection.md to identify frameworks like Next.js, Django, Laravel, FastAPI, etc.
Execute documentation system detection to identify existing documentation setup. This determines:
Use the detection algorithm from prompts/context/documentation-system-detection.md to identify systems like MkDocs, Docusaurus, Storybook, VitePress, Sphinx, TypeDoc, JSDoc, etc.
# Determine if this is a library, application, or API
if [ -f "package.json" ]; then
if grep -q '"main":' package.json || grep -q '"exports":' package.json; then
PROJECT_TYPE="Library/Package"
else
PROJECT_TYPE="Application"
fi
fi
# Check for API patterns
if [ -d "api" ] || [ -d "routes" ] || [ -d "endpoints" ]; then
HAS_API="Yes"
fi
# Check for component library
if [ -d "components" ] && [ -d ".storybook" ]; then
PROJECT_TYPE="Component Library"
fi
Use this context to:
Analyze $ARGUMENTS to determine documentation type:
API Documentation if:
$ARGUMENTS = "api" or "endpoints" or "rest" or "graphql"Architecture Documentation if:
$ARGUMENTS = "architecture" or "adr" or "design" or "decisions"Component Documentation if:
$ARGUMENTS = "component" or "components" or "ui"Feature Documentation if:
$ARGUMENTS = "feature" or specific feature nameCode Documentation if:
$ARGUMENTS = "code" or "jsdoc" or "typedoc" or "inline"Auto-Detect if:
$ARGUMENTS = "auto" or empty# Find API routes/endpoints
if [ -d "app/api" ]; then
# Next.js App Router API routes
find app/api -name "route.ts" -o -name "route.js" > .agency/documentation/api-routes.txt
elif [ -d "pages/api" ]; then
# Next.js Pages Router API routes
find pages/api -name "*.ts" -o -name "*.js" > .agency/documentation/api-routes.txt
elif [ -d "routes" ]; then
# Express/Flask routes
find routes -name "*.ts" -o -name "*.js" -o -name "*.py" > .agency/documentation/api-routes.txt
fi
# Count endpoints
ENDPOINT_COUNT=$(wc -l < .agency/documentation/api-routes.txt)
echo "Found $ENDPOINT_COUNT API endpoint files"
# Check for existing ADRs
if [ -d "docs/adr" ] || [ -d "docs/architecture" ]; then
echo "Existing architecture docs found"
ls -1 docs/adr/ 2>/dev/null || ls -1 docs/architecture/ 2>/dev/null
fi
# Identify key architectural decisions to document
# - Database choice
# - Authentication strategy
# - State management
# - API design
# - Deployment architecture
# Find components
if [ -d "components" ]; then
find components -name "*.tsx" -o -name "*.jsx" > .agency/documentation/components.txt
COMPONENT_COUNT=$(wc -l < .agency/documentation/components.txt)
echo "Found $COMPONENT_COUNT component files"
fi
# Check if specific component requested
if [[ "$ARGUMENTS" =~ ^[A-Z][a-zA-Z]+ ]]; then
# Looks like a component name (starts with capital letter)
COMPONENT_NAME="$ARGUMENTS"
echo "Documenting specific component: $COMPONENT_NAME"
fi
# Identify features to document
# Check for feature directories
if [ -d "features" ]; then
ls -1 features/ > .agency/documentation/features.txt
fi
# Or check for feature flags/config
if [ -f "features.config.js" ] || [ -f "feature-flags.json" ]; then
echo "Found feature configuration"
fi
# Find files missing documentation
# For TypeScript/JavaScript
if [ -f "tsconfig.json" ]; then
# Find exported functions/classes without JSDoc
grep -r "export " --include="*.ts" --include="*.tsx" src/ | wc -l
fi
# For Python
if [ -f "requirements.txt" ]; then
# Find functions without docstrings
grep -r "^def " --include="*.py" . | wc -l
fi
<!-- Component: prompts/progress/todo-initialization.md -->
Initialize progress tracking with TodoWrite:
[
{
"content": "Detect documentation scope",
"status": "in_progress",
"activeForm": "Detecting documentation scope"
},
{
"content": "Generate documentation content",
"status": "pending",
"activeForm": "Generating documentation content"
},
{
"content": "Review documentation quality",
"status": "pending",
"activeForm": "Reviewing documentation quality"
},
{
"content": "Validate code examples",
"status": "pending",
"activeForm": "Validating code examples"
},
{
"content": "Publish documentation",
"status": "pending",
"activeForm": "Publishing documentation"
}
]
<!-- Component: prompts/specialist-selection/user-approval.md -->
If scope is auto-detected or ambiguous, use AskUserQuestion to confirm:
Question: "What type of documentation should I generate?"
Options:
- "API Documentation (endpoints, request/response, examples)"
- "Architecture Documentation (ADR, system design, decisions)"
- "Component Documentation (props, usage, examples, Storybook)"
- "Feature Documentation (user guide, how-to, configuration)"
- "Code Documentation (JSDoc/TypeDoc inline comments)"
If specific scope detected, confirm:
Question: "Generate [TYPE] documentation for [SCOPE]?"
Options:
- "Yes, proceed"
- "Change scope or type"
Mark todo #1 as completed.
Mark todo #2 as in_progress.
# Create base documentation directory if doesn't exist
mkdir -p $DOC_DIR
# Create subdirectories based on documentation type
case "$DOC_TYPE" in
"api")
mkdir -p $DOC_DIR/api
mkdir -p $DOC_DIR/api/endpoints
mkdir -p $DOC_DIR/api/examples
;;
"architecture")
mkdir -p $DOC_DIR/architecture
mkdir -p $DOC_DIR/architecture/decisions
mkdir -p $DOC_DIR/architecture/diagrams
;;
"component")
mkdir -p $DOC_DIR/components
mkdir -p $DOC_DIR/components/examples
;;
"feature")
mkdir -p $DOC_DIR/features
mkdir -p $DOC_DIR/guides
;;
"code")
# Code documentation is inline
;;
esac
Based on documentation type, spawn the appropriate specialist:
| Documentation Type | Specialist Agent |
|---|---|
| API | Backend Architect or senior-developer |
| Architecture | Backend Architect or ArchitectUX |
| Component | Frontend Developer or UI Designer |
| Feature | Content Creator or Senior Developer |
| Code | Senior Developer |
Spawn specialist agent:
Task: Generate API documentation
Agent: Backend Architect
Context:
- Framework: [detected framework]
- API endpoints: [count] endpoints in [directories]
- Documentation format: [OpenAPI/Markdown]
Instructions:
1. Analyze all API endpoints in the codebase
2. For each endpoint, document:
- **Method & Path**: GET /api/users/:id
- **Description**: What this endpoint does
- **Authentication**: Required auth (API key, JWT, OAuth)
- **Request Parameters**:
- Path parameters
- Query parameters
- Request body (with schema)
- **Response**:
- Success response (200, 201, etc.) with schema
- Error responses (400, 401, 404, 500) with examples
- **Rate Limiting**: If applicable
- **Examples**:
- cURL example
- JavaScript/TypeScript fetch example
- Python requests example
3. Group endpoints by resource (users, posts, auth, etc.)
4. Generate in [OpenAPI 3.0 / Markdown] format
5. Include authentication overview
6. Include error code reference
Use this template structure:
# API Documentation
## Overview
[Brief description of the API]
## Base URL
[production/staging URLs]
## Authentication
[How to authenticate requests]
## Endpoints
### Users
#### GET /api/users
[Full endpoint documentation]
#### POST /api/users
[Full endpoint documentation]
[... more endpoints ...]
## Error Codes
[Standard error responses]
## Rate Limiting
[Rate limit details]
Save documentation to $DOC_DIR/api/README.md and individual endpoints to $DOC_DIR/api/endpoints/
Wait for specialist to complete API documentation.
Spawn specialist agent:
Task: Generate Architecture Decision Record (ADR)
Agent: Backend Architect
Context:
- Project: [framework and type]
- Decision to document: [database choice / auth strategy / deployment / etc.]
Instructions:
1. Create an ADR following this template:
# ADR-[NUMBER]: [Title of Decision]
**Date**: [YYYY-MM-DD]
**Status**: [Proposed / Accepted / Deprecated / Superseded]
**Deciders**: [List of people involved]
## Context
[Describe the context and problem statement]
- What forces are at play? (technical, political, social, project)
- What is driving the need for this decision?
## Decision
[Describe the decision that was made]
- Clear, concise statement of the decision
- What option was chosen?
## Rationale
[Why was this decision made?]
- What are the benefits?
- How does it address the context?
- What trade-offs were accepted?
## Consequences
### Positive Consequences
- [Benefit 1]
- [Benefit 2]
### Negative Consequences
- [Drawback 1]
- [Drawback 2]
### Neutral Consequences
- [Implication 1]
## Alternatives Considered
### Alternative 1: [Name]
- **Pros**: [List]
- **Cons**: [List]
- **Why rejected**: [Reason]
### Alternative 2: [Name]
- **Pros**: [List]
- **Cons**: [List]
- **Why rejected**: [Reason]
## Implementation Notes
[How this decision should be implemented]
- [Guideline 1]
- [Guideline 2]
## Related Decisions
- [ADR-XXX]: [Related decision]
## References
- [Link 1]
- [Link 2]
2. For common architectural decisions, document:
- Database choice (PostgreSQL, MongoDB, etc.)
- Authentication strategy (JWT, OAuth, sessions)
- State management (Redux, Context, Zustand)
- API design (REST, GraphQL, tRPC)
- Deployment architecture (containers, serverless, traditional)
3. Save to $DOC_DIR/architecture/decisions/ADR-[NUMBER]-[slug].md
4. Update $DOC_DIR/architecture/README.md with index of all ADRs
Wait for specialist to complete ADR.
Spawn specialist agent:
Task: Generate component documentation
Agent: Frontend Developer
Context:
- Framework: [React/Vue/Angular]
- Component: [specific component or all components]
- Documentation system: [Storybook / Markdown]
Instructions:
1. For each component, document:
# [ComponentName]
## Overview
[Brief description of what the component does]
## Usage
```tsx
import { [ComponentName] } from '@/components/[ComponentName]';
export function Example() {
return (
<[ComponentName]
prop1="value"
prop2={true}
/>
);
}
| Prop | Type | Default | Required | Description |
|---|---|---|---|---|
prop1 | string | undefined | Yes | [Description] |
prop2 | boolean | false | No | [Description] |
[Screenshot or code example]
[Screenshot or code example]
[Code]
[Code with more props]
[Real-world usage example]
[If using design system]
[How to test this component]
import { render, screen } from '@testing-library/react';
import { [ComponentName] } from './[ComponentName]';
test('renders correctly', () => {
render(<[ComponentName] />);
expect(screen.getByRole('[role]')).toBeInTheDocument();
});
Extract actual props from TypeScript interfaces/types
Capture all variants from the component code
Include real, working code examples
Save to $DOC_DIR/components/[ComponentName].md
If Storybook exists, also create/update stories:
import type { Meta, StoryObj } from '@storybook/react';
import { [ComponentName] } from './[ComponentName]';
const meta: Meta<typeof [ComponentName]> = {
title: 'Components/[ComponentName]',
component: [ComponentName],
tags: ['autodocs'],
};
export default meta;
type Story = StoryObj<typeof [ComponentName]>;
export const Default: Story = {
args: {
// Default props
},
};
export const [Variant]: Story = {
args: {
// Variant props
},
};
**Wait for specialist to complete component documentation.**
#### Feature Documentation Generation
Spawn specialist agent:
Task: Generate feature documentation
Agent: Content Creator or Senior Developer
Context:
Instructions:
[Brief description of the feature - 2-3 sentences]
Key Benefits:
[Step-by-step guide for new users]
[Common use cases with examples]
[Description and example]
[Code or steps]
[Description and example]
[Advanced features and techniques]
| Variable | Type | Default | Description |
|---|---|---|---|
VAR_NAME | string | "" | [Description] |
{
"feature": {
"option1": "value",
"option2": true
}
}
[If feature exposes an API]
functionName(params)[Description]
Parameters:
param1 (type): [Description]Returns: type - [Description]
Example:
const result = functionName({ param1: 'value' });
[For developers who need to understand internals]
[How the feature is structured]
[How data flows through the feature]
[Diagram or description]
[If relevant]
CREATE TABLE feature_data (
id SERIAL PRIMARY KEY,
...
);
describe('[Feature]', () => {
test('[test case]', () => {
// Test code
});
});
[How to test the feature end-to-end]
[Test scenarios for QA]
Symptoms:
Cause: [Root cause]
Solution:
[Same structure]
Q: [Question]? A: [Answer]
Q: [Question]? A: [Answer]
[Performance implications and optimization tips]
[Security best practices and warnings]
[Full, realistic example]
// Complete working code
[Another example]
**Wait for specialist to complete feature documentation.**
#### Code Documentation Generation
Spawn specialist agent:
Task: Generate inline code documentation
Agent: Senior Developer
Context:
Instructions:
/**
* [Brief description of function]
*
* [Longer description if needed - what it does, why it exists]
*
* @param param1 - [Description of param1]
* @param param2 - [Description of param2]
* @returns [Description of return value]
*
* @throws {ErrorType} [When this error is thrown]
*
* @example
* ```typescript
* const result = functionName('value', true);
* // result === [expected]
* ```
*
* @see {@link RelatedFunction} for related functionality
*/
export function functionName(param1: string, param2: boolean): ReturnType {
// Implementation
}
/**
* [Description of class]
*
* [Purpose and usage context]
*
* @example
* ```typescript
* const instance = new ClassName({ option: 'value' });
* instance.method();
* ```
*/
export class ClassName {
/**
* [Property description]
*/
private propertyName: string;
/**
* Creates an instance of ClassName
*
* @param options - [Description of options]
*/
constructor(options: Options) {
// Implementation
}
/**
* [Method description]
*
* @param param - [Description]
* @returns [Description]
*/
public methodName(param: string): ReturnType {
// Implementation
}
}
def function_name(param1: str, param2: bool) -> ReturnType:
"""
[Brief description of function]
[Longer description if needed]
Args:
param1: [Description of param1]
param2: [Description of param2]
Returns:
[Description of return value]
Raises:
ValueError: [When this error is raised]
Example:
>>> result = function_name('value', True)
>>> print(result)
[expected output]
"""
# Implementation
pass
Focus on:
Use Edit tool to add documentation inline
Generate API documentation from docstrings:
npx typedocpdocSave generated API docs to $DOC_DIR/api/
**Wait for specialist to complete code documentation.**
Mark todo #2 as completed.
---
## Phase 3: Documentation Review (5-10 min)
Mark todo #3 as in_progress.
### Select Review Specialist
Spawn an appropriate reviewer based on documentation type:
| Documentation Type | Reviewer |
|--------------------|----------|
| **API** | Backend Architect or reality-checker |
| **Architecture** | Backend Architect or ArchitectUX |
| **Component** | Frontend Developer or UI Designer |
| **Feature** | Content Creator or reality-checker |
| **Code** | Senior Developer |
### Spawn Documentation Reviewer
Task: Review documentation quality
Agent: [selected reviewer]
Context:
Instructions: Review the documentation for:
Accuracy:
Completeness:
Clarity:
Code Examples:
Consistency:
Links & References:
Provide feedback on:
Please review and provide specific, actionable feedback.
**Wait for reviewer to complete.**
### Incorporate Review Feedback
Based on reviewer feedback:
1. **Fix critical errors** immediately using Edit tool
2. **Add missing sections** that were identified
3. **Improve unclear explanations**
4. **Add requested examples**
5. **Fix broken links**
If substantial changes needed, re-delegate to original specialist:
Task: Update documentation based on review feedback
Agent: [original specialist]
Context:
Instructions: Update the documentation to address these issues:
Ensure all feedback is addressed completely.
Mark todo #3 as completed.
---
## Phase 4: Validation & Publishing (5-10 min)
Mark todo #4 as in_progress.
### Validate Code Examples
For each code example in the documentation, verify it works:
#### For TypeScript/JavaScript Examples
```bash
# Create temporary test file
cat > .agency/documentation/example-test.ts <<'EOF'
[code example from docs]
EOF
# Type check
npx tsc --noEmit .agency/documentation/example-test.ts
if [ $? -eq 0 ]; then
echo "✅ Example type checks"
else
echo "❌ Example has type errors - fix in documentation"
fi
# Clean up
rm .agency/documentation/example-test.ts
# Create temporary test file
cat > .agency/documentation/example_test.py <<'EOF'
[code example from docs]
EOF
# Syntax check
python3 -m py_compile .agency/documentation/example_test.py
if [ $? -eq 0 ]; then
echo "✅ Example syntax valid"
else
echo "❌ Example has syntax errors - fix in documentation"
fi
# Clean up
rm .agency/documentation/example_test.py
# Start development server if needed
# npm run dev &
# SERVER_PID=$!
# Test cURL examples
curl -X GET http://localhost:3000/api/endpoint
# Check response code
if [ $? -eq 0 ]; then
echo "✅ API endpoint accessible"
else
echo "⚠️ API endpoint returned error - verify docs are accurate"
fi
# Kill server
# kill $SERVER_PID
Fix any examples that don't work.
# Find all markdown links
grep -r "\[.*\](.*)" $DOC_DIR/ --include="*.md" > .agency/documentation/links.txt
# Check internal links (files exist)
# [Manual verification or use a tool like markdown-link-check]
# Check external links
# npm install -g markdown-link-check
# markdown-link-check $DOC_DIR/**/*.md
Fix broken links.
# Install aspell if available
# aspell check $DOC_DIR/README.md
# Or use VS Code spell checker extension
# Or manual review
Create or update main documentation index:
# Documentation
Welcome to the [Project Name] documentation.
## Quick Start
- [Getting Started](./guides/getting-started.md)
- [Installation](./guides/installation.md)
## API Documentation
- [API Overview](./api/README.md)
- [Authentication](./api/authentication.md)
- [Endpoints](./api/endpoints/)
## Architecture
- [Architecture Overview](./architecture/README.md)
- [Decision Records](./architecture/decisions/)
## Components
- [Component Library](./components/README.md)
- [Button](./components/Button.md)
- [Modal](./components/Modal.md)
## Features
- [Feature 1](./features/feature-1.md)
- [Feature 2](./features/feature-2.md)
## Guides
- [Deployment](./guides/deployment.md)
- [Testing](./guides/testing.md)
- [Contributing](./guides/contributing.md)
## Troubleshooting
- [Common Issues](./troubleshooting.md)
- [FAQ](./faq.md)
---
Last updated: [DATE]
Save to $DOC_DIR/README.md
Follow conventional commit standards for documentation:
# Add documentation to git
git add $DOC_DIR/
# Show what will be committed
git status
# Commit using heredoc format (see prompts/git/commit-formatting.md)
git commit -m "$(cat <<'EOF'
docs($ARGUMENTS): generate comprehensive [TYPE] documentation
Generated documentation includes:
- [Section 1]
- [Section 2]
- [Section 3]
[Any notable details]
EOF
)"
Refer to prompts/git/commit-formatting.md for complete commit message guidelines and templates.
Create a comprehensive report adapted from the implementation summary template:
File Location: .agency/documentation/doc-[topic]-[timestamp].md
Report Structure:
# Documentation Generation Summary: [Topic]
**Date**: [YYYY-MM-DD HH:MM:SS]
**Documentation Type**: [API/Architecture/Component/Feature/Code]
**Scope**: [what was documented]
**Specialist**: [Selected specialist]
**Duration**: [time spent]
**Status**: ✅ SUCCESS / ⚠️ PARTIAL / ❌ FAILED
---
## Objective
[Brief description of documentation goals - 1-3 sentences]
---
## Documentation Generated
### Files Created ([X] files)
- `$DOC_DIR/[path]` - [Description]
- `$DOC_DIR/[path]` - [Description]
### Files Modified ([Y] files)
- `$DOC_DIR/[path]` - [What changed]
**Total**: [N] documentation files, [X]KB of documentation
---
## Documentation Quality
### Completeness: [High/Medium/Low]
- ✅ All required sections present
- ✅ Examples included
- ✅ Troubleshooting guide included
- ⚠️ [Any gaps]
### Accuracy: [Verified/Needs Review]
- ✅ Code examples validated
- ✅ Links checked
- ✅ API schemas verified
### Code Examples: [N] examples
- ✅ All examples type-checked
- ✅ Realistic use cases
- ✅ Follow best practices
---
## Review Feedback Addressed
1. **[Feedback 1]**: [How addressed]
2. **[Feedback 2]**: [How addressed]
OR "No critical issues found"
---
## Next Steps
### Recommended Follow-up Documentation
1. **[Topic 1]**: [Why needed]
2. **[Topic 2]**: [Why needed]
### Maintenance
- **Update frequency**: [Recommended frequency]
- **Ownership**: [Who should maintain]
- **Review triggers**: [When to review - releases, major changes]
---
## Related Resources
- **Documentation System**: [MkDocs/Docusaurus/etc]
- **Build Command**: [command]
- **Deploy Command**: [command]
- **Commit**: [commit hash]
Save to .agency/documentation/doc-[topic]-[timestamp].md
Refer to prompts/reporting/summary-template.md for the complete template structure.
Mark todo #4 as completed.
Ambiguous Topic:
No Relevant Code Found:
Specialist Agent Error:
Missing Information:
Code Examples Don't Work:
Broken Links:
Formatting Issues:
Different Scope:
Different Format:
Additional Sections:
For API Docs:
For Architecture Docs:
For Component Docs:
For Feature Docs:
For Code Docs:
Documentation is a living thing:
Generators:
Static Site Generators:
Quality Tools:
Activate and reference these skills as needed:
Required:
agency-workflow-patterns - Orchestration patterns (ACTIVATE IMMEDIATELY)Technology-Specific (activate based on project):
nextjs-16-expert - Next.js documentation patternstypescript-5-expert - TypeScript documentation best practicesreact-documentation - Component documentation standardsapi-documentation-standards - REST/GraphQL API docsDocumentation Skills:
technical-writing - Writing clear, concise documentationmarkdown-mastery - Advanced markdown techniquesadr-writing - Architecture Decision Records (if available)/agency:work [issue] - Implement feature (may need documentation)/agency:review [pr] - Review PR (check for documentation updates)/agency:refactor [scope] - Refactor code (update documentation accordingly)Remember:
Good documentation multiplies the value of good code.
End of /agency:document command