# CodeWiki — Auto-Generated Documentation from Code Analysis

## Overview

When a repository is uploaded, RepoPilot automatically scans the code, builds a knowledge graph, decomposes the codebase into a hierarchical module tree, then uses a multi-agent system (Claude Agent SDK subagents) to generate comprehensive wiki-style documentation. Documents are generated bottom-up: leaf modules first, then parent syntheses, then a root overview. The wiki is browsable in a dedicated Wiki tab alongside Chat and Code tabs.

## Architecture — Three Phases

### Phase 1: Repository Analysis & Hierarchical Module Decomposition

**Trigger:** Synchronous during `POST /api/repositories` after file extraction.

**Pipeline:**
```
Upload/Clone repo
  → RepoScanner.scan(sourcePath)        // existing tree-sitter AST parsing
  → RepoIndex.save(index.rpidx)         // cache knowledge graph to disk
  → buildModuleTree(graph)              // decompose graph into module tree
  → Save .codewiki/tree.json            // persist module tree
```

**No LLM calls** — pure static analysis using the existing scanner + graph traversal.

**`buildModuleTree(graph)` logic:**
1. Get all `PACKAGE` nodes from the knowledge graph
2. Group files by package path (split on `.` → hierarchy)
3. For each package, collect its classes (via `CONTAINS` edges)
4. If a package has >15 classes, split into subgroups by sub-package prefix or class naming patterns (`*Handler`, `*Service`, `*Schema`)
5. Build tree bottom-up, attach file lists and class lists

### Phase 2: Recursive Documentation Generation

**Depth-first traversal of the module tree, leaves first.**

For each leaf module, a `module-documenter` subagent receives:
1. **Module code** — all source files read in full
2. **Module tree position** — where it sits, siblings, parent
3. **Graph context** — classes, relationships, inheritance, CBS schemas
4. **Prompt template** — structured documentation instructions

Leaf module doc contains:
- Module purpose and responsibility
- Class-by-class documentation (what each class does, key methods)
- Internal patterns (inheritance hierarchies, message flows)
- Dependencies on other modules
- Key code snippets

### Phase 3: Hierarchical Assembly & Documentation Synthesis

**After all leaves are documented, synthesize parent docs bottom-up.**

For each parent module, a `module-synthesizer` subagent receives:
1. **Child module documentation** — the `.md` files generated for its children
2. **Module tree** — full tree structure
3. **Graph context** — cross-module relationships, package dependencies

Parent module doc contains:
- Package overview and purpose
- How child modules work together
- Cross-module patterns and data flows
- Key abstractions and extension points
- Dependency diagram (mermaid)

For the root overview, the synthesizer receives all top-level package docs + full module tree + graph-level stats (total classes, relationships, patterns). Root doc contains:
- Repository purpose and architecture
- Technology stack and frameworks
- Package responsibilities and interactions
- System-level data flow (mermaid diagram)
- Entry points and key classes

## Module Tree Data Model

```typescript
interface ModuleNode {
  id: string;                    // e.g., "koptBp.cbs"
  name: string;                  // e.g., "cbs"
  path: string;                  // e.g., "koptBp/cbs"
  level: "root" | "package" | "subpackage" | "class_group";
  files: string[];               // Java files in this module
  classes: string[];             // Class names (from graph nodes)
  children: ModuleNode[];        // Sub-modules
  parent?: string;               // Parent module id
  docPath?: string;              // Generated doc path
  status: "pending" | "generating" | "done";
}
```

Example tree for K-Opticom:
```
Root
├── koptBp/                     (package)
│   ├── cbs/                    (subpackage — CBS message handlers)
│   ├── ejb/                    (subpackage — EJB session beans)
│   └── util/                   (subpackage — utilities)
├── koptCommon/                 (package)
│   ├── cbs/
│   └── util/
└── koptModel/                  (package)
    ├── entity/
    └── dao/
```

## Multi-Agent System (Claude Agent SDK Subagents)

The wiki generation uses the Claude Agent SDK's subagent system. A main WikiAgent orchestrates the process, delegating to typed subagents.

### Agent Definitions

```typescript
agents: {
  "module-documenter": {
    description: "Reads source files for a code module and writes comprehensive markdown documentation.",
    prompt: "You are a code documentation expert. Read all files in the given module, analyze classes/methods/patterns, and write a detailed wiki page.",
    tools: ["Read", "Glob", "Grep", "Write"]
  },
  "module-synthesizer": {
    description: "Reads child module documentation and synthesizes a parent-level overview page.",
    prompt: "You are a documentation architect. Read the child docs provided and write a higher-level overview that explains how the sub-modules work together.",
    tools: ["Read", "Write"]
  }
}
```

### WikiAgent Flow

1. Main agent receives module tree + graph summary in system prompt
2. **Traverse leaves first** — for each leaf, delegate to `module-documenter` subagent
3. **Synthesize parents** — after leaf docs exist, delegate to `module-synthesizer`
4. **Generate root overview** — final synthesizer call writes `overview.md`

Each subagent gets a fresh context focused on its module. All subagents are sandboxed to the repository directory via `cwd`.

## Output Structure

```
/repos/{uuid}/
  ├── Source/...                  (original code)
  ├── index.rpidx                (knowledge graph)
  └── .codewiki/
      ├── tree.json              (module tree)
      ├── overview.md            (root synthesis)
      ├── koptBp.md              (parent synthesis)
      ├── koptBp/
      │   ├── cbs.md             (leaf doc)
      │   ├── ejb.md
      │   └── util.md
      ├── koptCommon.md
      ├── koptCommon/
      │   ├── cbs.md
      │   └── util.md
      ├── koptModel.md
      └── koptModel/
          ├── entity.md
          └── dao.md
```

## UI — Three-Tab Layout

Main content area has three tabs: **Chat**, **Code**, **Wiki**.

```
┌─────────────────────────────────────────────────┐
│  [ Chat ]  [ Code ]  [ Wiki ]                   │
├──────────────┬──────────────────────────────────┤
│ 📖 Overview  │                                  │
│ 📁 koptBp    │  # koptBp - Business Process     │
│   📄 cbs     │                                  │
│   📄 ejb     │  ## Overview                     │
│   📄 util    │  The koptBp package handles...   │
│ 📁 koptCommon│                                  │
│   📄 cbs     │  ## Sub-modules                  │
│   📄 util    │  - **cbs**: CBS message handlers  │
│ 📁 koptModel │  - **ejb**: Session beans         │
│   📄 entity  │  ...                             │
│   📄 dao     │                                  │
└──────────────┴──────────────────────────────────┘
```

- **Wiki tab:** Left panel = collapsible page tree from tree.json. Right panel = rendered markdown.
- **Code tab:** Existing file tree + code viewer components.
- **Chat tab:** Existing chat interface.

During upload, a loading indicator shows progress ("Scanning repository...", "Generating documentation...").

## API Routes

### Updated

```
POST /api/repositories              Add scan + wiki generation to creation pipeline
```

### New

```
GET /api/repositories/[id]/wiki           List wiki pages (reads tree.json)
GET /api/repositories/[id]/wiki/[...path] Get wiki page content (reads .md file)
```

Wiki pages are filesystem-only (`.codewiki/` directory) — no database storage.

## New Files

| File | Purpose |
|------|---------|
| `src/server/wiki-generator.ts` | Orchestrates Phase 1→2→3: scan, build tree, run WikiAgent |
| `src/lib/repopilot/module-tree.ts` | `buildModuleTree()` from knowledge graph |
| `src/components/TabBar.tsx` | Chat/Code/Wiki tab switcher |
| `src/components/WikiView.tsx` | Wiki tab content (tree nav + markdown) |
| `src/components/WikiTree.tsx` | Collapsible page tree from tree.json |
| `src/components/WikiPage.tsx` | Markdown renderer (reuses existing components) |
| `src/app/api/repositories/[id]/wiki/route.ts` | List wiki pages |
| `src/app/api/repositories/[id]/wiki/[...path]/route.ts` | Get wiki page content |

## Modified Files

| File | Change |
|------|--------|
| `src/app/api/repositories/route.ts` | Add scan + wiki generation after file extraction |
| `src/components/ChatApp.tsx` | Add tab state, render TabBar + active tab content |

## Data Flow

```
POST /api/repositories (upload/clone)
  → Extract files
  → Insert DB row
  → RepoScanner.scan() → index.rpidx
  → buildModuleTree() → .codewiki/tree.json
  → WikiAgent (Claude Agent SDK)
      → module-documenter subagents (leaves)
      → module-synthesizer subagents (parents)
      → module-synthesizer (root overview)
  → Return repository JSON

GET /api/repositories/[id]/wiki
  → Read .codewiki/tree.json → return page tree

GET /api/repositories/[id]/wiki/[...path]
  → Read .codewiki/{path}.md → return markdown content

UI: WikiView
  → Fetch tree.json → render WikiTree
  → On page click → fetch markdown → render WikiPage
```

## Configuration

Uses existing environment variables:
- `LLM_MODEL` — model for wiki generation LLM calls (same as chat agent)
- `ANTHROPIC_BASE_URL` — LiteLLM proxy URL
- `ANTHROPIC_API_KEY` — API key
- `REPOS_PATH` — managed repo directory

## Dependencies

No new dependencies. Uses existing:
- `@anthropic-ai/claude-agent-sdk` — subagent orchestration
- `tree-sitter` + `tree-sitter-java` — AST parsing (existing scanner)
- `@msgpack/msgpack` — RepoIndex serialization (existing)
