---
name: kodadocs-faq-generator
description: "Analyze error patterns and GitHub Issues to generate FAQ and troubleshooting pages for your doc site."
---

# FAQ Generator

## Overview

This skill generates comprehensive FAQ and troubleshooting documentation by analyzing your codebase for error patterns, scanning GitHub Issues for common user questions, and clustering them into organized, searchable pages. The output integrates directly into your KodaDocs site as dedicated FAQ and troubleshooting sections.

Use this skill when:
- You want to add FAQ or troubleshooting pages to your documentation
- Users keep asking the same questions in GitHub Issues or support channels
- Your codebase has error codes or error messages that need documented solutions
- You want to proactively document known issues and their workarounds

## Prerequisites

Before running this skill, ensure the following:

1. **Project codebase:** The project directory must contain source code for analysis.
2. **GitHub CLI (optional but recommended):** `gh` must be authenticated for issue scanning (`gh auth status`).
3. **GitHub repository (optional):** A connected GitHub remote for issue data. Run `git remote -v` to check.
4. **KodaDocs manifest (optional):** If integrating with an existing doc site, a previous pipeline run should exist.

## Workflow

### Step 1: Analyze Error Patterns in Code

Use the KodaDocs codebase analysis tool to extract error patterns from the source code.

**Run the analysis:**
Call `mcp__kodadocs__analyze_codebase` with the project path:
```
project_path: "<project-root>"
```

**From the response, extract:**
- `error_patterns` — an array of error objects found via tree-sitter parsing
- Each error pattern includes: file path, line number, error message or code, and surrounding context

**Classify each error pattern:**

| Pattern Type | Detection Method | Example |
|-------------|-----------------|---------|
| Error codes | Matches pattern like `E001`, `ERR_*`, `ERROR_*` | `ERR_AUTH_FAILED` |
| HTTP status codes | Numeric codes 400-599 in response handlers | `res.status(404)` |
| Thrown errors | `throw new Error(...)`, `raise Exception(...)` | `throw new Error("Invalid token")` |
| Console errors | `console.error(...)`, `logger.error(...)` | `console.error("DB connection failed")` |
| Error boundaries | React error boundaries, try/catch blocks | `catch (AuthError)` |
| Validation errors | Form validation, schema validation messages | `"Email is required"` |
| Environment errors | Missing env vars, config validation | `"DATABASE_URL not set"` |

**For each error pattern, generate:**
1. A user-friendly error description (what the user sees)
2. The likely cause (why this happens)
3. The solution (how to fix it)
4. Prevention tips (how to avoid it in the future)

### Step 2: Scan GitHub Issues for Common Questions

If `gh` is available and authenticated, scan the project's GitHub Issues.

**Fetch recent issues:**
```bash
# Get open issues (most likely unanswered questions)
gh issue list --state open --limit 100 --json number,title,labels,body,comments,createdAt

# Get recently closed issues (answered questions)
gh issue list --state closed --limit 100 --json number,title,labels,body,comments,createdAt
```

**Filter for FAQ-worthy issues:**

Include issues that match any of these signals:
- Title contains a question mark (`?`)
- Title starts with "How", "Why", "Can", "Does", "Is", "What", "Where", "When"
- Labels include: `question`, `help wanted`, `good first issue`, `documentation`, `faq`, `support`
- Body contains phrases like: "how do I", "is it possible", "does this support", "I'm getting an error", "not working"

Exclude issues that match:
- Labels: `bug` (unless also labeled `question`), `feature request`, `enhancement`
- Issues with no comments and no resolution (unanswered, unhelpful)
- Duplicate issues (check for "duplicate" label or "duplicate of" in comments)

**Extract question-answer pairs:**
For each qualifying issue:
1. The **question** is the issue title (cleaned up for clarity)
2. The **answer** is derived from:
   - The first comment by a maintainer or contributor
   - The closing comment if the issue was resolved
   - If no clear answer exists, derive one from the issue body and any linked PRs
3. The **category** is inferred from labels or keywords (setup, usage, configuration, deployment, etc.)

### Step 3: Cluster and Deduplicate Questions

Group all collected questions (from error patterns and issues) into logical categories.

**Default category structure:**

1. **Getting Started** - Installation, setup, first-run issues
2. **Configuration** - Environment variables, config files, settings
3. **Usage** - How to use features, workflows, common tasks
4. **Authentication** - Login, API keys, permissions, tokens
5. **Deployment** - Build errors, hosting, CI/CD issues
6. **Troubleshooting** - Error messages, debugging, known issues
7. **Compatibility** - Browser support, OS support, version requirements
8. **Data & Storage** - Database, file uploads, caching
9. **API & Integrations** - Third-party services, webhooks, API usage

**Deduplication rules:**
- Merge questions with the same core topic (e.g., "How to set API key?" and "Where do I put my API key?" become one entry)
- When merging, keep the clearest question wording and combine the answers
- If two entries conflict, prefer the answer from the more recent source
- Flag merged entries so you can note "Related issues: #12, #34"

**Minimum threshold:** Each category must have at least 2 entries to be included. Categories with only 1 entry should be merged into the closest related category.

### Step 4: Enhance Answers with Code Context

For questions related to code behavior, enrich the answers with actual code references.

**For error-related questions:**
1. Reference the file and function where the error originates
2. Show the relevant code snippet (3-5 lines, centered on the error)
3. Explain what the code expects and what might cause it to fail
4. Provide a concrete fix with a code example

**For configuration questions:**
1. Show the relevant config file or environment variable
2. Provide a working example with the correct values
3. List all valid options if the config has enumerated values

**For "how to" questions:**
1. Provide a step-by-step answer
2. Include CLI commands or code snippets where applicable
3. Link to relevant documentation sections if they exist

### Step 5: Generate FAQ Page

Produce a structured FAQ page in markdown.

**FAQ page template:**

```markdown
# Frequently Asked Questions

<category-section repeat for each category>

## <Category Name>

### <Question 1>

<Answer paragraph>

<Optional code block>

<Optional "Related issues: #N, #M">

---

### <Question 2>

<Answer paragraph>

</category-section>
```

**Formatting rules:**
- Each question is an H3 heading (### )
- Answers are 1-3 paragraphs, concise and direct
- Code blocks use the appropriate language syntax highlighting
- Horizontal rules (---) separate questions within a category
- Related issue numbers link to GitHub when the repo URL is known
- Categories with more entries appear first (most-asked topics at the top)

**Tone guidelines:**
- Write answers as if explaining to a capable developer who is new to this project
- Be direct: answer the question in the first sentence, then provide details
- Avoid hedging ("you might want to", "it could be") -- be definitive
- Use "you" to address the reader, not "the user" or "one"

### Step 6: Generate Troubleshooting Page

Produce a separate troubleshooting page focused on errors and their solutions.

**Troubleshooting page template:**

```markdown
# Troubleshooting

Quick solutions for common errors and issues.

## Error Reference

| Error | Cause | Quick Fix |
|-------|-------|-----------|
| `ERR_AUTH_FAILED` | Invalid or expired API key | Regenerate your key in Settings |
| `404 Not Found` | Route does not exist | Check your route configuration |
| ... | ... | ... |

## Detailed Solutions

### `ERR_AUTH_FAILED` — Authentication Failed

**What you see:**
> Error: Authentication failed. Please check your credentials.

**Why this happens:**
Your API key is either invalid, expired, or not set in the environment.

**How to fix it:**

1. Check that your API key is set:
   ```bash
   echo $API_KEY
   ```
2. If empty, set it in your `.env` file:
   ```
   API_KEY=your-key-here
   ```
3. Restart your development server.

**Still not working?**
- Verify the key has not been revoked in your dashboard
- Check that you are using the correct environment (production vs. staging)

---

### <next error>
```

**Structure rules:**
- Start with a summary reference table (error -> cause -> quick fix)
- Follow with detailed sections for each error
- Each detailed section includes: what you see, why it happens, how to fix it, and "still not working?" fallback
- Order errors by frequency (most commonly encountered first)
- If error frequency is unknown, order alphabetically by error code

### Step 7: Save Output Files

Save the generated pages to the project.

**Default file locations:**
- FAQ: `docs/faq.md`
- Troubleshooting: `docs/troubleshooting.md`

If the user specifies different paths, use those instead.

### Step 8: Integrate with Doc Site (Optional)

If the user wants to add the pages to their KodaDocs documentation site:

1. **Load the existing manifest:**
   Call `mcp__kodadocs__load_manifest` to retrieve the current pipeline state.

2. **Create article objects:**
   ```json
   [
     {
       "title": "FAQ",
       "slug": "faq",
       "content": "<faq markdown content>",
       "order": 900
     },
     {
       "title": "Troubleshooting",
       "slug": "troubleshooting",
       "content": "<troubleshooting markdown content>",
       "order": 901
     }
   ]
   ```

3. **Reassemble the site:**
   Call `mcp__kodadocs__assemble_vitepress` with all existing articles plus the new FAQ and troubleshooting articles. Preserve the existing configuration from the manifest.

4. **Optionally redeploy:**
   Call `mcp__kodadocs__deploy_site` if the user requests it.

5. **Save updated manifest:**
   Call `mcp__kodadocs__save_manifest` to record the FAQ generation in the pipeline state.

## Decision Trees

### Issue Scanning Availability

```
Is `gh` CLI authenticated? (gh auth status)
  YES -> Does the repo have a GitHub remote?
           YES -> Scan issues for questions and answers
           NO  -> Skip issue scanning, use only error pattern analysis
  NO  -> Skip issue scanning entirely
         Inform the user: "GitHub Issues not available. FAQ will be based on code analysis only."
```

### Content Source Priority

```
For each FAQ entry, which source takes priority?
  1. Maintainer-authored answer from a closed GitHub Issue (highest trust)
  2. Error pattern from code analysis + generated solution
  3. Inferred answer from issue discussion threads
  4. Generated answer based on code context alone (lowest trust, mark as "auto-generated")
```

### Category Assignment

```
Does the question mention an error message or code?
  YES -> Assign to "Troubleshooting"
Does the question mention installation, setup, or getting started?
  YES -> Assign to "Getting Started"
Does the question mention config, env, settings, or options?
  YES -> Assign to "Configuration"
Does the question mention deploy, build, CI, or hosting?
  YES -> Assign to "Deployment"
Does the question mention auth, login, key, token, or permission?
  YES -> Assign to "Authentication"
Default -> Assign to "Usage"
```

### Thin Data Handling

```
Fewer than 5 total questions found?
  YES -> Generate a "starter FAQ" with common questions for the framework type
         Use mcp__kodadocs__detect_framework to identify the framework
         Add framework-specific starter questions:
           Next.js: "How do I deploy?", "How do I add environment variables?"
           Django: "How do I run migrations?", "How do I create a superuser?"
         Mark starter entries as "[Placeholder - customize for your project]"
  NO  -> Proceed with the collected questions
```

## Output Format

The skill produces:

1. **FAQ page** (`docs/faq.md`) - Categorized questions and answers
2. **Troubleshooting page** (`docs/troubleshooting.md`) - Error reference table and detailed solutions
3. **Doc site pages** (optional) - Integrated into the KodaDocs VitePress site
4. **Console summary:**

```
FAQ & Troubleshooting generated:
  - Error patterns found: 12
  - GitHub Issues scanned: 87
  - FAQ entries generated: 24
  - Troubleshooting entries: 8
  - Categories: 6
  Sources:
    - Code analysis: 8 entries
    - GitHub Issues: 16 entries
  Saved to:
    - docs/faq.md
    - docs/troubleshooting.md
```

## Error Handling

### No error patterns found
If `mcp__kodadocs__analyze_codebase` returns zero error patterns:
- Continue with GitHub Issues as the sole source
- If issues are also unavailable, generate a minimal starter FAQ
- Inform the user: "No error patterns detected in the codebase. FAQ is based on GitHub Issues only."

### GitHub Issues API rate limit
If `gh issue list` fails due to rate limiting:
- Log the warning and continue with code analysis data only
- Suggest: "GitHub API rate limit reached. Try again in an hour, or set GH_TOKEN for higher limits."

### No GitHub repository
If the project has no GitHub remote:
- Skip all issue scanning steps
- Generate FAQ purely from error pattern analysis
- This is a valid workflow -- not an error condition

### Empty or unhelpful issues
If issues are found but none qualify after filtering:
- Log: "Found N issues but none contained FAQ-worthy questions."
- Continue with code analysis data only

### Codebase analysis fails
If `mcp__kodadocs__analyze_codebase` returns an error:
- Fall back to manual error scanning using grep for common patterns:
  ```bash
  # Search for throw/raise statements
  grep -rn "throw new Error\|raise \w*Error\|console.error" --include="*.ts" --include="*.js" --include="*.py" <project-path>
  ```
- If manual scanning also fails, rely entirely on GitHub Issues

### Duplicate detection edge cases
If two questions appear identical but have different answers:
- Keep both entries
- Add a note: "See also: [other question]" to cross-reference them
- Let the user resolve the conflict manually

## Success Criteria

The run is successful when:
- [ ] Codebase was analyzed for error patterns (or fallback was used)
- [ ] GitHub Issues were scanned if available
- [ ] Questions were classified into logical categories
- [ ] Duplicates were identified and merged
- [ ] FAQ page contains at least 5 entries (or a starter FAQ was generated)
- [ ] Troubleshooting page contains an error reference table
- [ ] Each troubleshooting entry has: what you see, why it happens, how to fix it
- [ ] Answers are direct, developer-friendly, and include code examples where relevant
- [ ] Files were saved to the correct locations
- [ ] If doc site integration: pages were added and site reassembled
- [ ] Console summary was printed with statistics
