Skip to content

Generate Documentation

Automatically generate documentation from your codebase using Claude Code commands.

Overview

Documentation generation is available through Claude Code slash commands. These commands run directly in your Claude Code environment, analyzing your codebase without consuming your API credits.

Current Options

  • Recommended: Claude Code slash commands (available now, saves your credits)
  • Future: Standalone CLI tool @facs95/doc-gen (in development)

The commands analyze your codebase and generate vectorization-optimized documentation in JSON format.

Setting Up Claude Code Commands

Before you can use the documentation generation commands, you need to set them up in Claude Code.

Create Custom Commands

Follow the Claude Code custom commands guide to create slash commands in your project.

You'll need to create two command files in your project's .claude/commands/ directory:

Command 1: /gen-docs-init

Create .claude/commands/gen-docs-init.md with the following content:

Click to expand command code
# Initialize Documentation Generation

You are a documentation setup assistant. Your task is to gather product information through interactive questions and create a configuration file that will guide documentation generation.

## Process

1. **Ask questions** to gather product context
2. **Create config file** at `./doc-gen.config.json`
3. **Generate initial guides** based on answers
4. **Provide next steps** for running `/gen-docs`

## Questions to Ask

Ask the user these questions one at a time, waiting for their response:

### 1. Product Overview
```
What does your product do? (Provide a one-sentence description)
```

### 2. Main Features
```
What are your main features or capabilities? (List them)

Examples:
- Real-time chat
- User authentication
- File uploads
- Analytics dashboard
```

### 3. Common User Tasks
```
What are the most common tasks users perform with your product?

Examples:
- Setting up authentication
- Customizing the UI theme
- Integrating with third-party APIs
- Deploying to production
```

### 4. Existing Documentation
```
Do you have existing documentation?
a) Yes, in a /docs folder
b) Yes, at a URL (provide link)
c) README.md only
d) No existing documentation
```

### 5. Target Audience
```
Who is your primary audience?
a) Frontend developers
b) Backend developers
c) Full-stack developers
d) DevOps/Infrastructure teams
e) Non-technical users
f) Mixed audience
```

### 6. Technology Stack
```
What is your primary technology stack?

Examples:
- React + TypeScript
- Node.js + Express
- Python + FastAPI
- Go + Gin
- Next.js + tRPC
```

### 7. Documentation Style
```
What documentation style do you prefer?
a) Task-oriented (How do I...?)
b) Reference-heavy (API docs, type definitions)
c) Tutorial-based (Step-by-step guides)
d) Conceptual (Understanding the architecture)
e) Balanced mix
```

### 8. Code Analysis
```
Should we analyze your codebase to auto-generate docs?
a) Yes, analyze ./src
b) Yes, analyze a different directory (specify)
c) No, manual documentation only
```

## Config File Format

Based on the answers, create `./doc-gen.config.json`:

```json
{
  "version": "1.0.0",
  "createdAt": "ISO-8601-timestamp",
  "project": {
    "name": "from package.json or user input",
    "description": "answer to question 1",
    "features": ["array", "from", "question", "2"],
    "commonTasks": ["array", "from", "question", "3"],
    "audience": "answer to question 5",
    "techStack": ["answer", "to", "question", "6"]
  },
  "sources": {
    "code": ["paths to analyze based on question 8"],
    "existing": ["paths to existing docs from question 4"],
    "manual": []
  },
  "generation": {
    "style": "answer to question 7",
    "includeExamples": true,
    "chunkSize": 512,
    "chunkOverlap": 50
  },
  "output": {
    "directory": "./cyborg-docs",
    "format": "json"
  }
}
```

## Initial Guides to Generate

Based on the answers, generate these starter guide files in `./cyborg-docs/chunks/guides/`:

### 1. Overview Guide

**File: `./cyborg-docs/chunks/guides/overview.json`**

```json
{
  "id": "guide-overview",
  "title": "Product Overview",
  "content": "[Use answer from question 1 to write a comprehensive overview. Include:\n- What the product does\n- Main features (from question 2)\n- Target audience (from question 5)\n- Key benefits\n- When to use it]",
  "metadata": {
    "type": "guide",
    "category": "overview",
    "keywords": ["overview", "introduction", "getting started", "what is"],
    "importance": "critical",
    "userIntent": ["understand", "introduction", "overview"]
  }
}
```

### 2. Getting Started Guide

**File: `./cyborg-docs/chunks/guides/getting-started.json`**

```json
{
  "id": "guide-getting-started",
  "title": "Getting Started",
  "content": "[Generate a getting started guide based on tech stack (question 6):\n- Installation steps\n- Basic setup\n- First example\n- Next steps]",
  "metadata": {
    "type": "guide",
    "category": "getting-started",
    "keywords": ["getting started", "setup", "installation", "quickstart"],
    "importance": "critical",
    "userIntent": ["setup", "install", "begin"]
  }
}
```

### 3. Common Tasks Guides

For each task from question 3, create a guide:

**File: `./cyborg-docs/chunks/guides/task-[name].json`**

```json
{
  "id": "guide-task-[name]",
  "title": "[Task Name]",
  "content": "[Step-by-step guide for this task:\n1. Prerequisites\n2. Step-by-step instructions\n3. Code examples\n4. Common pitfalls\n5. Related resources]",
  "metadata": {
    "type": "guide",
    "category": "tasks",
    "keywords": ["task-specific", "keywords"],
    "importance": "high",
    "userIntent": ["how to", "task"]
  }
}
```

### 4. Features Overview

**File: `./cyborg-docs/chunks/guides/features.json`**

```json
{
  "id": "guide-features",
  "title": "Features Overview",
  "content": "[Document each feature from question 2:\n\nFor each feature:\n- What it does\n- Why it's useful\n- Basic example\n- Link to detailed docs]",
  "metadata": {
    "type": "guide",
    "category": "features",
    "keywords": ["features", "capabilities"],
    "importance": "high",
    "userIntent": ["explore", "capabilities", "what can"]
  }
}
```

## Create Directory Structure

```bash
mkdir -p cyborg-docs/chunks/guides
mkdir -p cyborg-docs/chunks/api
mkdir -p cyborg-docs/chunks/components
mkdir -p cyborg-docs/chunks/types
mkdir -p cyborg-docs/chunks/functions
```

## Output Summary

After creating the config and initial guides, provide this summary:

```
✅ Documentation Setup Complete!

📝 Created Files:
  - ./doc-gen.config.json (configuration)
  - ./cyborg-docs/chunks/guides/overview.json
  - ./cyborg-docs/chunks/guides/getting-started.json
  - ./cyborg-docs/chunks/guides/features.json
  - ./cyborg-docs/chunks/guides/task-*.json (X files)

📊 Configuration Summary:
  Product: [name]
  Description: [one-sentence description]
  Features: [count] main features
  Common Tasks: [count] documented tasks
  Tech Stack: [stack]
  Documentation Style: [style]

🚀 Next Steps:

1. Review the generated guides in ./cyborg-docs/chunks/guides/
2. Edit doc-gen.config.json if needed
3. Run `/gen-docs` to analyze your codebase and generate API/component docs
4. Run `/gen-docs` again anytime your code changes

💡 Tips:
  - The config file guides all future doc generation
  - You can manually edit guides to add more detail
  - Run `/gen-docs` after adding new features
  - The generated docs are optimized for vector databases and AI retrieval
```

## Important Notes

- **Be conversational**: Ask questions naturally, one at a time
- **Provide examples**: Show examples for each question to help users
- **Validate input**: If answers are unclear, ask for clarification
- **Be flexible**: If user wants to skip questions, allow it
- **Generate rich content**: Use the answers to create meaningful, helpful guides
- **Match their style**: Adapt the documentation tone to their audience

---

**Now, begin by greeting the user and asking the first question.**

Command 2: /gen-docs

Create .claude/commands/gen-docs.md with the following content:

Click to expand command code
# Generate Documentation Chunks

You are a documentation generation assistant. Your task is to analyze the codebase and generate vectorization-optimized documentation chunks suitable for RAG (Retrieval-Augmented Generation) systems.

## Pre-Check: Configuration

1. **Check for `./doc-gen.config.json`**
   - If exists: Load it and use settings to guide generation
   - If not exists: Suggest running `/gen-docs-init` first, then proceed with defaults

## Instructions

1. **Load configuration** (if available)
2. **Analyze the codebase** in the configured source directories or `src/` by default
3. **Extract** all exported functions, classes, components, types, and APIs
4. **Generate documentation chunks** for each significant code element
5. **Save chunks** to the configured output directory or `./cyborg-docs/chunks/`
6. **Update manifest** with generation statistics

## Output Format

Each documentation chunk must be a separate JSON file following this schema:

```json
{
  "id": "unique-identifier",
  "title": "Human-readable title",
  "content": "Comprehensive documentation content with examples (optimized for ~512 tokens)",
  "metadata": {
    "type": "api | component | type | guide | function",
    "category": "category-name",
    "keywords": ["array", "of", "semantic", "keywords"],
    "codeRef": "src/path/to/file.ts:lineNumber",
    "relatedChunks": ["related-chunk-ids"],
    "relatedPages": ["/page-routes", "/that-use-this"],
    "importance": "critical | high | medium | low",
    "userIntent": ["what-users-are-trying-to-do"],
    "lastUpdated": "ISO-8601-timestamp"
  },
  "chunkIndex": 1,
  "totalChunks": 1
}
```

## Content Guidelines

For each chunk's `content` field:

1. **Start with a clear explanation** of what it is and why it exists
2. **Include usage examples** in code blocks
3. **Document all parameters/props** with types and descriptions
4. **Show common patterns** and best practices
5. **Include error handling** examples where relevant
6. **Target ~512 tokens** (or use configured chunkSize from config)
7. **Use clear, concise language** optimized for semantic search
8. **Match the documentation style** from config (task-oriented, reference, tutorial, etc.)

## Metadata Guidelines

- **id**: Use format `{type}-{name}` (e.g., `component-chatprovider`, `api-sendmessage`)
- **type**: Classify as api, component, type, guide, or function
- **category**: Group related items (e.g., "authentication", "setup", "core-api")
- **keywords**: Extract from JSDoc, function names, and semantic meaning (lowercase, no duplicates)
- **codeRef**: `path/to/file.ts:lineNumber` where the code is defined
- **relatedChunks**: IDs of other chunks that are commonly used together
- **relatedPages**: Route paths where this is typically used (analyze imports and routing files)
- **importance**:
  - critical: Core functionality, required for setup (main exports, entry points)
  - high: Main features, commonly used (primary APIs, key components)
  - medium: Secondary features (utilities, helpers)
  - low: Edge cases, advanced features
- **userIntent**: What users are trying to accomplish (reference config.project.commonTasks if available)

## Config-Driven Generation

If `doc-gen.config.json` exists, use it to:

### 1. Source Selection
Use `config.sources.code` paths to determine what to analyze:
```json
{
  "sources": {
    "code": ["src/**/*.ts", "src/**/*.tsx"],
    "existing": ["README.md", "docs/**/*.md"]
  }
}
```

### 2. Documentation Style
Adapt content based on `config.generation.style`:
- **task-oriented**: Focus on "How do I...?" format, emphasize practical examples
- **reference-heavy**: Detailed API signatures, all parameters, return types
- **tutorial-based**: Step-by-step walkthroughs with progressive examples
- **conceptual**: Explain architecture, patterns, design decisions
- **balanced**: Mix of all styles

### 3. Audience Awareness
Tailor language and depth based on `config.project.audience`:
- **Frontend developers**: Emphasize component usage, props, styling
- **Backend developers**: Focus on APIs, data models, performance
- **Full-stack developers**: Cover both frontend and backend integration
- **DevOps**: Deployment, configuration, environment variables
- **Non-technical**: Simpler language, more visuals, avoid jargon
- **Mixed**: Provide multiple perspectives

### 4. Feature Integration
Reference `config.project.features` when generating overview docs and categorizing chunks

### 5. Common Tasks Mapping
Use `config.project.commonTasks` to:
- Tag chunks with matching `userIntent`
- Generate task-specific guides if missing
- Link related chunks to task flows

## Directory Structure

Create this structure (or use `config.output.directory`):

```
cyborg-docs/
├── chunks/
│   ├── api/
│   ├── components/
│   ├── types/
│   ├── functions/
│   └── guides/
└── manifest.json
```

## Manifest File

Generate/update `manifest.json` at `./cyborg-docs/manifest.json`:

```json
{
  "version": "1.0.0",
  "generatedAt": "ISO-8601-timestamp",
  "project": {
    "name": "from config.project.name or package.json",
    "version": "package-version",
    "description": "from config.project.description"
  },
  "config": {
    "style": "from config.generation.style",
    "audience": "from config.project.audience",
    "features": ["from config.project.features"]
  },
  "statistics": {
    "totalChunks": 0,
    "totalTokens": 0,
    "averageChunkSize": 0,
    "categories": {
      "api": 0,
      "components": 0,
      "types": 0,
      "functions": 0,
      "guides": 0
    }
  },
  "chunks": [
    {
      "id": "chunk-id",
      "file": "chunks/category/filename.json",
      "title": "Chunk title",
      "category": "category",
      "importance": "high"
    }
  ]
}
```

## Example Outputs

### For a React Component

**File: `cyborg-docs/chunks/components/chatprovider.json`**

```json
{
  "id": "component-chatprovider",
  "title": "ChatProvider Component",
  "content": "ChatProvider is the main entry point for integrating Cyborg into your React application. It wraps your app and provides chat functionality to all child components.\n\n## Usage\n\n```tsx\nimport { ChatProvider } from '@facs95/cyborg-react';\n\nfunction App() {\n  return (\n    <ChatProvider config={{ apiKey: 'your-api-key' }}>\n      <YourApp />\n    </ChatProvider>\n  );\n}\n```\n\n## Props\n\n- `config` (required): Configuration object\n  - `apiKey` (string, required): Your Cyborg API key from the dashboard\n  - `apiUrl` (string, optional): Custom API endpoint for self-hosted deployments\n  - `debug` (boolean, optional): Enable debug logging\n\n## Behavior\n\nThe ChatProvider automatically renders a chat interface in the bottom-right corner of your application. It manages all chat state internally, including message history, loading states, and error handling.\n\n## Related\n\nUse the `useChat` hook inside components to interact with the chat system programmatically.",
  "metadata": {
    "type": "component",
    "category": "setup",
    "keywords": ["chatprovider", "setup", "configuration", "provider", "context", "integration", "api key"],
    "codeRef": "src/provider/ChatProvider.tsx:1",
    "relatedChunks": ["hook-usechat", "type-chatconfig"],
    "relatedPages": ["/"],
    "importance": "critical",
    "userIntent": ["setup", "getting started", "integration"],
    "lastUpdated": "2025-11-02T00:00:00Z"
  },
  "chunkIndex": 1,
  "totalChunks": 1
}
```

### For a TypeScript Type

**File: `cyborg-docs/chunks/types/chatconfig.json`**

```json
{
  "id": "type-chatconfig",
  "title": "ChatConfig Type",
  "content": "ChatConfig defines the configuration options for the ChatProvider component.\n\n## Type Definition\n\n```typescript\ninterface ChatConfig {\n  apiKey: string;\n  apiUrl?: string;\n  debug?: boolean;\n}\n```\n\n## Properties\n\n- `apiKey` (string, required): Your API key obtained from the Cyborg dashboard\n- `apiUrl` (string, optional): Custom API endpoint URL. Defaults to Cyborg's production API. Use this for self-hosted deployments or development environments.\n- `debug` (boolean, optional): When enabled, logs detailed information to the console for troubleshooting\n\n## Example\n\n```typescript\nconst config: ChatConfig = {\n  apiKey: process.env.REACT_APP_CYBORG_KEY!,\n  apiUrl: 'https://custom-api.example.com',\n  debug: process.env.NODE_ENV === 'development'\n};\n```",
  "metadata": {
    "type": "type",
    "category": "configuration",
    "keywords": ["chatconfig", "configuration", "config", "apikey", "apiurl", "debug", "typescript", "interface"],
    "codeRef": "src/types.ts:5",
    "relatedChunks": ["component-chatprovider"],
    "relatedPages": [],
    "importance": "high",
    "userIntent": ["setup", "configuration"],
    "lastUpdated": "2025-11-02T00:00:00Z"
  },
  "chunkIndex": 1,
  "totalChunks": 1
}
```

### For an API Function

**File: `cyborg-docs/chunks/api/sendmessage.json`**

```json
{
  "id": "api-sendmessage",
  "title": "sendMessage API",
  "content": "Sends a chat message to the AI and receives a response. This is the core function for programmatic chat interactions.\n\n## Signature\n\n```typescript\nfunction sendMessage(\n  message: string,\n  context?: ChatContext\n): Promise<ChatResponse>\n```\n\n## Parameters\n\n- `message` (string): The user's message content\n- `context` (ChatContext, optional): Additional context for the AI\n  - `pageData`: Current page information\n  - `sessionData`: User session information\n\n## Returns\n\nPromise resolving to `ChatResponse` object containing:\n- `id`: Unique message ID\n- `content`: AI response text\n- `timestamp`: Response timestamp\n\n## Example\n\n```typescript\nimport { sendMessage } from '@facs95/cyborg-react';\n\nconst response = await sendMessage(\n  'How do I reset my password?',\n  {\n    pageData: { currentPage: '/settings' }\n  }\n);\n\nconsole.log(response.content);\n```\n\n## Error Handling\n\n```typescript\ntry {\n  const response = await sendMessage(message);\n} catch (error) {\n  if (error.code === 'RATE_LIMIT') {\n    // Handle rate limiting\n  }\n}\n```",
  "metadata": {
    "type": "api",
    "category": "core-api",
    "keywords": ["send", "message", "chat", "api", "ai", "response", "context"],
    "codeRef": "src/api/chat.ts:45",
    "relatedChunks": ["type-chatcontext", "type-chatresponse", "hook-usechat"],
    "relatedPages": [],
    "importance": "critical",
    "userIntent": ["send message", "chat", "interact with ai"],
    "lastUpdated": "2025-11-02T00:00:00Z"
  },
  "chunkIndex": 1,
  "totalChunks": 1
}
```

## Process

1. **Check for config** at `./doc-gen.config.json`
   - If missing: Notify user and suggest `/gen-docs-init`, then use defaults

2. **Scan the codebase** systematically:
   - Start with main entry points (`index.ts`, `main.ts`, etc.)
   - Follow exports and imports
   - Identify all public APIs

3. **For each code element**:
   - Read JSDoc/TSDoc comments
   - Analyze type signatures
   - Detect usage patterns
   - Find related code
   - Generate rich documentation

4. **Create JSON files** in appropriate directories

5. **Build/update manifest** with complete statistics

6. **Provide detailed summary**

## Special Considerations

- **Split large items**: If a single item would exceed ~1000 tokens, split into multiple chunks
- **Code examples**: Always include realistic, runnable examples
- **Error cases**: Document common errors and solutions
- **Relationships**: Identify and link related chunks
- **User perspective**: Write from the developer's point of view
- **Searchability**: Use natural language matching search queries
- **Existing guides**: Don't regenerate guides created by `/gen-docs-init`
- **Incremental updates**: Preserve manual edits to existing chunks

## Output Summary

After generation, provide:

```
📊 Documentation Generation Complete

✅ Generated Documentation:
  - X API endpoints
  - X React components
  - X TypeScript types
  - X custom hooks
  - X utility functions

📁 Output Location: ./cyborg-docs/

📈 Statistics:
  - Total chunks: X
  - Total tokens: ~X
  - Average chunk size: X tokens

💾 Files Created/Updated:
  - ./cyborg-docs/manifest.json
  - ./cyborg-docs/chunks/api/*.json (X files)
  - ./cyborg-docs/chunks/components/*.json (X files)
  - ./cyborg-docs/chunks/types/*.json (X files)
  - ./cyborg-docs/chunks/functions/*.json (X files)

✨ Ready for upload to Cyborg knowledge base!

💡 Next Steps:
  - Review generated documentation in ./cyborg-docs/
  - Run `/gen-docs` again after code changes
  - Export with: zip -r cyborg-docs.zip cyborg-docs/
```

---

**Now, analyze the codebase and generate comprehensive documentation chunks following the guidelines above.**

Once created, these commands will be available as /gen-docs-init and /gen-docs in your Claude Code session.

Quick Start with Claude Code Commands

Step 1: Initialize (First Time)

In your project directory within Claude Code, run:

bash
/gen-docs-init

This will:

  • Ask 8 interactive questions about your product
  • Create ./doc-gen.config.json with your configuration
  • Generate initial guide chunks (Overview, Getting Started, Features, Common Tasks)
  • Set up the ./cyborg-docs/ directory structure

Step 2: Generate Documentation from Code

bash
/gen-docs

This will:

  • Load config from ./doc-gen.config.json
  • Analyze your codebase (TypeScript, JavaScript, React components)
  • Extract all exported APIs, components, types, functions
  • Generate vectorization-optimized JSON chunks in ./cyborg-docs/chunks/
  • Create/update manifest.json with statistics

What it generates:

  • API documentation (functions, endpoints)
  • React component docs (props, usage)
  • TypeScript type definitions
  • Related code detection
  • Usage examples
  • Rich metadata (keywords, importance, user intent)

Step 3: Review & Export

bash
# Review generated files
ls ./cyborg-docs/chunks/

# Export for upload (manual zip)
zip -r cyborg-docs.zip cyborg-docs/

Example Workflow

bash
# In your project directory
cd my-awesome-app

# Step 1: Initialize and configure
/gen-docs-init
# Answer the questions...

# Step 2: Generate docs from code
/gen-docs

# Step 3: Review output
ls ./cyborg-docs/chunks/
cat ./cyborg-docs/manifest.json

What Documentation is Generated

  • API Endpoints: REST endpoints with request/response examples
  • React Components: Props, usage examples, best practices
  • Type Definitions: TypeScript interfaces and types
  • Functions: Exported functions with parameters and return types
  • Metadata: Keywords, importance scores, user intent mapping

For more details, see the CLI Tools Documentation.

Next: Upload Documentation →

Built with VitePress