Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
get dependency path tool updated for cases where no direct path is found
RaghavChamadiyaf92f39c0f863
diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.mdnew file mode 100644index 000000000..d342bdb2d--- /dev/null+++ b/docs/QUICKSTART.md@@ -0,0 +1,96 @@+# Quickstart++Get the WikiCode backend and frontend running locally against an already-indexed repo.++## Prerequisites++- **Python 3.11+** managed by [uv](https://docs.astral.sh/uv/)+- **Node.js 18+** with npm+- A **Gemini API key** (or Anthropic/OpenAI — swap the env vars accordingly)+- A repo that has already been indexed with `wikicode init` (the `.wikicode/` directory exists)++## Test Repo++These instructions use the `interview-coach` repo as the test target:++```+Repo path: C:\Users\ragha\Desktop\interview-coach+Wiki DB: C:\Users\ragha\Desktop\interview-coach\.wikicode\wiki.db+Provider: gemini (gemini-3.1-flash-lite-preview)+Embedder: gemini+```++## 1. Install Dependencies++From the CodeWiki root:++```powershell+cd C:\Users\ragha\Desktop\CodeWiki++# Python packages (all workspace packages)+uv sync++# Node packages (web frontend)+npm install+```++## 2. Start the Backend (port 7337)++Open a PowerShell terminal:++```powershell+cd C:\Users\ragha\Desktop\CodeWiki++$env:WIKICODE_DB_URL = "sqlite+aiosqlite:///C:/Users/ragha/Desktop/interview-coach/.wikicode/wiki.db"+$env:GEMINI_API_KEY = "YOUR_GEMINI_API_KEY"+$env:WIKICODE_EMBEDDER = "gemini"++uv run uvicorn wikicode.server.app:create_app --factory --host 0.0.0.0 --port 7337 --reload+```++Verify: `http://localhost:7337/health` should return `{"status": "ok"}`.++## 3. Start the Frontend (port 3000)++Open a second PowerShell terminal:++```powershell+cd C:\Users\ragha\Desktop\CodeWiki++$env:WIKICODE_API_URL = "http://localhost:7337"++npm run dev --workspace packages/web+```++Open **http://localhost:3000** in your browser.++## 4. Test the Chat++1. Click your repo on the dashboard+2. You'll see the chat interface with suggestion chips+3. Try: *"Give me an overview of this codebase"*+4. Watch the streaming response with tool calls appearing in real time+5. Click **View** on any tool result to open the artifact panel++## Environment Variables Reference++| Variable | Required | Description |+|----------|----------|-------------|+| `WIKICODE_DB_URL` | Yes | SQLite/PostgreSQL connection string pointing to the indexed wiki DB |+| `GEMINI_API_KEY` | If using Gemini | Google Gemini API key |+| `ANTHROPIC_API_KEY` | If using Anthropic | Anthropic API key |+| `OPENAI_API_KEY` | If using OpenAI | OpenAI API key |+| `WIKICODE_EMBEDDER` | No (default: `mock`) | Embedder for RAG search: `gemini`, `openai`, or `mock` |+| `WIKICODE_API_URL` | Frontend only | Backend URL for Next.js proxy (default: `http://localhost:7337`) |+| `WIKICODE_API_KEY` | No | Optional API key to protect the backend; omit for local dev |++## Switching LLM Providers++The chat model selector in the UI lets you switch providers on the fly. To use a different provider, set its API key env var on the backend and restart. The chat will auto-detect configured providers.++## Troubleshooting++- **"embedder.mock_active" warning** — Set `$env:WIKICODE_EMBEDDER = "gemini"` (or `openai`) for real vector search+- **Empty repo list** — Check `WIKICODE_DB_URL` points to a DB with indexed repos+- **Chat returns 422** — The active provider doesn't have an API key set; check env vars+- **CORS errors** — Backend CORS is open (`*`) by default; ensure both servers are runningdiff --git a/packages/server/src/wikicode/server/chat_tools.py b/packages/server/src/wikicode/server/chat_tools.pyindex 77d103bcc..3fe94ada4 100644--- a/packages/server/src/wikicode/server/chat_tools.py+++ b/packages/server/src/wikicode/server/chat_tools.py@@ -111,7 +111,7 @@ _TOOL_SCHEMAS: list[dict[str, Any]] = [},{"name": "get_dependency_path",- "description": "Find the shortest dependency path between two files or modules in the codebase graph.",+ "description": "Find the shortest dependency path between two files or modules. When no direct path exists, returns visual context: nearest common ancestors, shared neighbors, community analysis, and bridge suggestions.","parameters": {"type": "object","properties": {diff --git a/packages/server/src/wikicode/server/mcp_server.py b/packages/server/src/wikicode/server/mcp_server.pyindex 4ffac2279..fff963dec 100644--- a/packages/server/src/wikicode/server/mcp_server.py+++ b/packages/server/src/wikicode/server/mcp_server.py@@ -1027,6 +1027,10 @@ async def get_dependency_path() -> dict:"""Find how two files/modules are connected in the dependency graph.+ When no direct path exists, returns visual context: nearest common+ ancestors, shared neighbors, community analysis, and bridge suggestions+ to help debug architectural silos.+Args:source: Source file or module path.target: Target file or module path.@@ -1035,12 +1039,19 @@ async def get_dependency_path(async with get_session(_session_factory) as session:repository = await _get_repo(session, repo)- result = await session.execute(+ edge_result = await session.execute(select(GraphEdge).where(GraphEdge.repository_id == repository.id,))- edges = result.scalars().all()+ edges = edge_result.scalars().all()++ node_result = await session.execute(+ select(GraphNode).where(+ GraphNode.repository_id == repository.id,+ )+ )+ nodes = node_result.scalars().all()try:import networkx as nx@@ -1063,7 +1074,12 @@ async def get_dependency_path(try:path = nx.shortest_path(G, source, target)except nx.NetworkXNoPath:- return {"path": [], "distance": -1, "explanation": "No path found"}+ return {+ "path": [],+ "distance": -1,+ "explanation": "No direct dependency path found",+ "visual_context": _build_visual_context(G, source, target, nodes, nx),+ }# Build path with relationshipspath_with_info = []@@ -1081,6 +1097,141 @@ async def get_dependency_path(}+def _build_visual_context(+ G: Any, source: str, target: str, nodes: list, nx: Any,+) -> dict:+ """Build diagnostic context when no directed path exists."""+ node_meta = {n.node_id: n for n in nodes}+ context: dict[str, Any] = {}++ # --- Reverse path check ---+ try:+ rev_path = nx.shortest_path(G, target, source)+ context["reverse_path"] = {+ "exists": True,+ "path": rev_path,+ "distance": len(rev_path) - 1,+ "note": f"A path exists in the reverse direction ({target} -> {source}). "+ "The dependency flows the other way.",+ }+ except nx.NetworkXNoPath:+ context["reverse_path"] = {"exists": False}++ # --- Nearest common ancestors (via undirected graph) ---+ U = G.to_undirected()+ source_reachable = set(nx.single_source_shortest_path_length(U, source))+ target_reachable = set(nx.single_source_shortest_path_length(U, target))+ common = source_reachable & target_reachable+ common.discard(source)+ common.discard(target)++ if common:+ source_dist = nx.single_source_shortest_path_length(U, source)+ target_dist = nx.single_source_shortest_path_length(U, target)+ scored = [+ (node, source_dist[node] + target_dist[node])+ for node in common+ ]+ scored.sort(key=lambda x: x[1])+ context["nearest_common_ancestors"] = [+ {"node": node, "distance_from_source": source_dist[node],+ "distance_from_target": target_dist[node]}+ for node, _ in scored[:5]+ ]+ else:+ context["nearest_common_ancestors"] = []++ # --- Shared neighbors (direct) ---+ source_neighbors = set(G.predecessors(source)) | set(G.successors(source))+ target_neighbors = set(G.predecessors(target)) | set(G.successors(target))+ shared = source_neighbors & target_neighbors+ if shared:+ context["shared_neighbors"] = sorted(shared)+ else:+ context["shared_neighbors"] = []++ # --- Community analysis ---+ src_meta = node_meta.get(source)+ tgt_meta = node_meta.get(target)+ src_community = src_meta.community_id if src_meta else None+ tgt_community = tgt_meta.community_id if tgt_meta else None++ context["community"] = {+ "source_community": src_community,+ "target_community": tgt_community,+ "same_community": src_community is not None and src_community == tgt_community,+ }++ # --- Bridge suggestions: high-centrality nodes between communities ---+ if src_community is not None and tgt_community is not None and src_community != tgt_community:+ # Find nodes that have edges crossing these two communities+ bridge_nodes = []+ nodes_by_community: dict[int, set[str]] = {}+ for n in nodes:+ nodes_by_community.setdefault(n.community_id, set()).add(n.node_id)++ src_community_nodes = nodes_by_community.get(src_community, set())+ tgt_community_nodes = nodes_by_community.get(tgt_community, set())++ for node_id in G.nodes():+ neighbors = set(G.predecessors(node_id)) | set(G.successors(node_id))+ touches_src = bool(neighbors & src_community_nodes)+ touches_tgt = bool(neighbors & tgt_community_nodes)+ if touches_src and touches_tgt:+ meta = node_meta.get(node_id)+ bridge_nodes.append({+ "node": node_id,+ "pagerank": meta.pagerank if meta else 0.0,+ })+ bridge_nodes.sort(key=lambda x: x["pagerank"], reverse=True)+ context["bridge_suggestions"] = bridge_nodes[:5]+ else:+ context["bridge_suggestions"] = []++ # --- Connectivity summary ---+ # Check if they're in completely disconnected components+ components = list(nx.weakly_connected_components(G))+ src_comp = next((c for c in components if source in c), set())+ tgt_comp = next((c for c in components if target in c), set())+ actually_disconnected = src_comp != tgt_comp++ if actually_disconnected:+ context["disconnected"] = True+ context["source_component_size"] = len(src_comp)+ context["target_component_size"] = len(tgt_comp)+ context["suggestion"] = (+ "These nodes are in completely separate dependency clusters with "+ "no shared connections. Look for shared configuration files, API "+ "contracts, or event buses that should bridge them."+ )+ else:+ context["disconnected"] = False+ if context["nearest_common_ancestors"]:+ top = context["nearest_common_ancestors"][0]["node"]+ context["suggestion"] = (+ f"No direct path, but both nodes connect through '{top}'. "+ "This shared dependency may be the architectural bridge point."+ )+ elif context["shared_neighbors"]:+ context["suggestion"] = (+ f"No direct path, but they share neighbor(s): "+ f"{', '.join(context['shared_neighbors'])}. "+ "These shared files may serve as the missing link."+ )+ elif context["reverse_path"].get("exists"):+ context["suggestion"] = (+ "No direct path in this direction, but a reverse path exists. "+ "The dependency flows the other way."+ )+ else:+ context["suggestion"] = (+ "These nodes are in the same cluster but have no direct "+ "or reverse dependency. Check for indirect connections."+ )++ return context++# ---------------------------------------------------------------------------# Tool 7: get_dead_code (unchanged)# ---------------------------------------------------------------------------diff --git a/packages/server/src/wikicode/server/routers/chat.py b/packages/server/src/wikicode/server/routers/chat.pyindex 68c7e4a77..770cabd3a 100644--- a/packages/server/src/wikicode/server/routers/chat.py+++ b/packages/server/src/wikicode/server/routers/chat.py@@ -462,7 +462,15 @@ def _build_tool_summary(tool_name: str, result: dict[str, Any]) -> str:if tool_name == "get_dependency_path":dist = result.get("distance", -1)- return f"Path found (distance: {dist})" if dist >= 0 else "No path found"+ if dist >= 0:+ return f"Path found (distance: {dist})"+ ctx = result.get("visual_context", {})+ ancestors = ctx.get("nearest_common_ancestors", [])+ if ancestors:+ return f"No direct path — nearest bridge: {ancestors[0]['node']}"+ if ctx.get("disconnected"):+ return "No path — nodes are in separate dependency clusters"+ return "No direct path found"if tool_name == "get_dead_code":summary = result.get("summary", {})diff --git a/packages/server/src/wikicode/server/routers/graph.py b/packages/server/src/wikicode/server/routers/graph.pyindex b75faf0de..4696dd10e 100644--- a/packages/server/src/wikicode/server/routers/graph.py+++ b/packages/server/src/wikicode/server/routers/graph.py@@ -620,7 +620,11 @@ async def dependency_path(target: str = Query(..., alias="to", description="Target node ID"),session: AsyncSession = Depends(get_db_session),) -> dict:- """Find the shortest dependency path between two nodes."""+ """Find the shortest dependency path between two nodes.++ When no direct path exists, returns visual context with nearest common+ ancestors, shared neighbors, and bridge suggestions.+ """repo = await crud.get_repository(session, repo_id)if repo is None:raise HTTPException(status_code=404, detail="Repository not found")@@ -630,6 +634,11 @@ async def dependency_path()edges = edge_result.scalars().all()+ node_result = await session.execute(+ select(GraphNode).where(GraphNode.repository_id == repo_id)+ )+ nodes = node_result.scalars().all()+try:import networkx as nxexcept ImportError:@@ -647,7 +656,13 @@ async def dependency_path(try:path = nx.shortest_path(G, source, target)except nx.NetworkXNoPath:- return {"path": [], "distance": -1, "explanation": "No path found"}+ from wikicode.server.mcp_server import _build_visual_context+ return {+ "path": [],+ "distance": -1,+ "explanation": "No direct dependency path found",+ "visual_context": _build_visual_context(G, source, target, nodes, nx),+ }return {"path": path,diff --git a/packages/server/src/wikicode/server/scheduler.py b/packages/server/src/wikicode/server/scheduler.pyindex c54e5fa65..5f5d1ae87 100644--- a/packages/server/src/wikicode/server/scheduler.py+++ b/packages/server/src/wikicode/server/scheduler.py@@ -84,14 +84,17 @@ def setup_scheduler(# NOTE: when a full sync is implemented here, pass# extra_exclude_patterns=repo.settings.get("exclude_patterns", [])# to FileTraverser so user-configured exclusions are respected.+ import json as _json+ try:+ _settings = _json.loads(repo.settings_json) if repo.settings_json else {}+ except Exception:+ _settings = {}logger.debug("polling_check",extra={"repo_id": repo.id,"head_commit": repo.head_commit,- "exclude_patterns": repo.settings.get("exclude_patterns", [])- if repo.settings- else [],+ "exclude_patterns": _settings.get("exclude_patterns", []),},)except Exception:diff --git a/packages/web/README.md b/packages/web/README.mdindex fdde857a7..f712353cf 100644--- a/packages/web/README.md+++ b/packages/web/README.md@@ -1,132 +1,153 @@# WikiCode Web UI-Next.js 15 frontend for the WikiCode codebase documentation engine. Displays AI-generated wiki pages, dependency graphs, symbol indexes, git analytics, and dead code analysis for any indexed codebase.+Next.js 15 frontend for the WikiCode codebase documentation engine. Provides an interactive interface for exploring AI-generated wiki pages, dependency graphs, code analytics, and architectural insights for any indexed repository.-**Stack:** Next.js 15 (App Router) · Tailwind CSS v4 · Radix UI · SWR · D3.js · Shiki · Framer Motion+## Tech Stack----+| Layer | Technology |+|-------|------------|+| Framework | Next.js 15 (App Router), React 19, TypeScript 5.7 |+| Styling | Tailwind CSS v4 (CSS-first, no config file), custom design tokens in `globals.css` |+| Components | Radix UI primitives, class-variance-authority for variants |+| Data Fetching | SWR (stale-while-revalidate) with 30s polling, Server-Sent Events for live job progress |+| Visualization | D3.js (force-directed graphs), Recharts (bar/donut charts), Mermaid (diagrams) |+| Code Rendering | Shiki (syntax highlighting), next-mdx-remote (wiki content) |+| Search | cmdk command palette (Cmd+K), Fuse.js client-side fuzzy search |+| URL State | nuqs (type-safe URL search params for bookmarkable views) |+| Animation | Framer Motion |+| Icons | Lucide React |+| Fonts | Geist Sans + Geist Mono |-## File Map+## Pages & Features-### Config & Root+### Dashboard (`/`)-| File | Purpose |-|------|---------|-| `package.json` | Dependencies: Next.js 15, React 19, Tailwind v4, all Radix UI packages, SWR, D3, Shiki, Framer Motion, cmdk |-| `tsconfig.json` | Strict TypeScript, `@/*` path alias → `./src/*` |-| `next.config.ts` | Standalone output, `/api/*` proxy rewrite to `WIKICODE_API_URL`, `optimizePackageImports` |-| `postcss.config.mjs` | `@tailwindcss/postcss` plugin (Tailwind v4 CSS-first — no `tailwind.config.ts`) |-| `.gitignore` | Standard Next.js ignores |+The home page. Shows aggregate stats across all registered repositories (total files, symbols, entry points, dead code findings), a list of repos with quick-action buttons, and recent indexing jobs with their status.-### Styles+### Repository Overview (`/repos/[id]`)-| File | Purpose |-|------|---------|-| `src/styles/globals.css` | Full design system — `@import "tailwindcss"` + `@theme {}` block with all CSS variables: surfaces (`--bg-base`, `--bg-surface`, `--bg-elevated`), borders, text, accent blue (`#5B9CF6`), confidence colors (fresh/stale/outdated), language colors, edge colors, typography scale, spacing, radii, z-index, animation easing. Also: prose overrides for wiki MDX content. |+Landing page for a single repo. Displays git stats (HEAD commit, branch, contributor count), documentation coverage at a glance, and quick links to all sub-pages. Includes an operations panel for triggering sync and full-resync jobs.++### Wiki Pages (`/repos/[id]/wiki/[...slug]`)++The core documentation viewer. Renders AI-generated wiki pages as MDX with:+- Shiki syntax-highlighted code blocks+- Embedded Mermaid diagrams (flowcharts, sequence diagrams, etc.)+- Auto-generated sticky table of contents from headings+- Confidence badge showing freshness (fresh/stale/outdated) with last-updated tooltip+- Git history panel showing the file's change timeline+- Regenerate button to force a fresh AI pass on stale pages++### Dependency Graph (`/repos/[id]/graph`)++Interactive D3 force-directed graph rendered on HTML Canvas. Supports six view modes:+- **Module view** — hierarchical module organization+- **Ego graph** — neighborhood of a selected node with context sidebar+- **Architecture view** — entry point reachability analysis+- **Dead code view** — highlights unreachable files+- **Hot files view** — commit activity heatmap overlay+- **Full graph** — complete dependency graph++Features pan/zoom, a minimap for orientation, a filter panel (by language, node type, edge type), node sizing controls, and a path finder to trace dependency chains between any two files.++### Search (`/repos/[id]/search`)++Full-text and semantic search across all wiki pages. Includes a type toggle (FTS / semantic / hybrid), debounced input, and result cards with highlighted snippets. Also powers the global command palette (Cmd+K) accessible from anywhere.++### Symbol Index (`/repos/[id]/symbols`)++Sortable, filterable table of all extracted symbols (functions, classes, constants, etc.). Filter by kind and language. Click any row to open a detail drawer with the symbol's signature, location, and relationships.++### Documentation Coverage (`/repos/[id]/coverage`)++Donut chart of overall documentation freshness plus a per-file table showing each page's confidence score, status (fresh/stale/outdated), and a per-row regenerate button for targeted updates.++### Code Ownership (`/repos/[id]/ownership`)++Contributor attribution view with granularity toggle (file/directory). Shows ownership percentages, knowledge silo badges (files owned by a single contributor), and a contributor activity chart.++### Hotspots (`/repos/[id]/hotspots`)++Ranked table of high-churn files with churn bar charts and an owner leaderboard. Helps identify files that change frequently and may need architectural attention.++### Dead Code (`/repos/[id]/dead-code`)++Tabbed view of dead code findings (unreachable files, unused exports). Supports row-level actions (ignore, mark as false positive), bulk selection, and a trigger to run fresh analysis. Summary bar shows counts by category.++### Architectural Decisions (`/repos/[id]/decisions`)++Lists extracted architectural decision records with health metrics. Each decision has a detail page (`/repos/[id]/decisions/[decisionId]`) showing rationale, status, and related code.++### Settings (`/settings` and `/repos/[id]/settings`)++Global settings page with sections for API connection, LLM provider/model selection, webhook configuration, and MCP integration. Per-repo settings available under each repository.++## Architecture++### Data Flow++```+Server Components (RSC) Client Components+───────────────────────── ──────────────────────+Fetch data via apiGet() ──> SWR hooks for polling/revalidation+Render static content useSSE() for live job progress+Pass props to client nuqs for URL state persistence+ useState for transient UI+```++Most pages are **React Server Components** that fetch data server-side. Client components are used only where interactivity is needed (D3 canvas, command palette, SSE streams, form state). The `"use client"` boundary is kept as narrow as possible.++### API Proxy++`next.config.ts` rewrites `/api/*` to `WIKICODE_API_URL/api/*`, so the frontend never hardcodes the backend URL and CORS is handled at the proxy layer.### API Client (`src/lib/api/`)-| File | Purpose |-|------|---------|-| `types.ts` | All TypeScript interfaces mirroring backend schemas: `RepoResponse`, `PageResponse`, `PageVersionResponse`, `JobResponse`, `JobProgressEvent`, `SearchResultResponse`, `SymbolResponse`, `GraphExportResponse`, `GitMetadataResponse`, `HotspotResponse`, `OwnershipEntry`, `DeadCodeFindingResponse`, `HealthResponse`, `WebhookResponse`, `ApiError` |-| `client.ts` | Base fetch wrapper — `apiGet`, `apiPost`, `apiPatch`. Reads API key from `localStorage` (browser) or `WIKICODE_API_KEY` env var (server). Throws `ApiClientError` with status code on failures. |-| `repos.ts` | `listRepos`, `getRepo`, `createRepo`, `updateRepo`, `syncRepo`, `fullResyncRepo` |-| `pages.ts` | `listPages`, `getPageById` (uses `/api/pages/lookup?page_id=`), `getPageVersions`, `regeneratePage` |-| `search.ts` | `search` — supports `fts`, `semantic`, `hybrid` search types |-| `jobs.ts` | `listJobs`, `getJob`, `getJobStreamUrl` |-| `symbols.ts` | `listSymbols`, `lookupSymbolByName`, `getSymbolById` |-| `graph.ts` | `getGraph`, `getGraphPath` |-| `git.ts` | `getGitMetadata`, `getHotspots`, `getOwnership`, `getCoChanges`, `getGitSummary` |-| `dead-code.ts` | `listDeadCode`, `analyzeDeadCode`, `getDeadCodeSummary`, `patchDeadCodeFinding` |-| `health.ts` | `getHealth` |--### Hooks (`src/lib/hooks/`)--| File | Purpose |-|------|---------|-| `use-repo.ts` | `useRepos`, `useRepo` — SWR hooks with 30s background refresh |-| `use-page.ts` | `usePage`, `usePageVersions` — SWR hooks for wiki page data |-| `use-search.ts` | `useSearch` — debounced search (300ms), min 2 chars, SWR |-| `use-debounce.ts` | Generic debounce hook |-| `use-sse.ts` | SSE hook for job progress — named event handlers (progress/done/error), auto-reconnect with exponential backoff, max retries |-| `use-graph.ts` | `useGraph` — SWR with no revalidate on focus/reconnect (graph data is stable) |+Organized by domain — `repos.ts`, `pages.ts`, `graph.ts`, `search.ts`, `symbols.ts`, `jobs.ts`, `git.ts`, `dead-code.ts`, `decisions.ts`, `health.ts`. Each module exports typed async functions wrapping `apiGet`/`apiPost`/`apiPatch` from `client.ts`. Auth is handled via Bearer token from `localStorage` (browser) or `WIKICODE_API_KEY` env var (server).-### Utilities (`src/lib/utils/`)+### Custom Hooks (`src/lib/hooks/`)-| File | Purpose |+| Hook | Purpose ||------|---------|-| `cn.ts` | `cn()` — `clsx` + `tailwind-merge` combinator |-| `format.ts` | `formatNumber`, `formatTokens`, `formatCost`, `formatRelativeTime`, `formatDate`, `formatDateTime`, `formatLOC`, `truncatePath`, `formatConfidence`, `formatProgress` |-| `confidence.ts` | `FreshnessStatus` type, `scoreToStatus`, `statusColor`, `statusTextClass`, `statusBadgeClasses`, `statusLabel`, `LANGUAGE_COLORS`, `languageColor`, `EDGE_COLORS`, `edgeColor` |--### UI Primitives (`src/components/ui/`)--All built on Radix UI with WikiCode design tokens:--| File | Component |-|------|-----------|-| `button.tsx` | CVA variants: default/destructive/outline/secondary/ghost/link × sm/md/lg/icon sizes |-| `badge.tsx` | CVA variants: default/fresh/stale/outdated/accent/outline |-| `card.tsx` | `Card`, `CardHeader`, `CardTitle`, `CardDescription`, `CardContent`, `CardFooter` |-| `separator.tsx` | Radix Separator |-| `input.tsx` | Styled text input |-| `skeleton.tsx` | `animate-pulse` loading skeleton |-| `tabs.tsx` | Radix Tabs |-| `tooltip.tsx` | Radix Tooltip with portal |-| `dialog.tsx` | Radix Dialog with overlay and close button |-| `scroll-area.tsx` | Radix ScrollArea with styled scrollbar |-| `select.tsx` | Full Radix Select with all sub-components |--### Shared Components (`src/components/shared/`)--| File | Component |-|------|-----------|-| `stat-card.tsx` | Dashboard stat card — label, value, description, optional icon |-| `empty-state.tsx` | Empty state — icon, title, description, optional action button |--### Wiki Components (`src/components/wiki/`)--| File | Component |-|------|-----------|-| `confidence-badge.tsx` | Freshness badge — fresh/stale/outdated states, animated pulse on stale, tooltip with date |--### Layout (`src/components/layout/`)--| File | Component |-|------|-----------|-| `sidebar.tsx` | Global sidebar — WikiCode logo, nav links (Dashboard, Settings), collapsible per-repo tree with all wiki pages, active state highlighting |--### Pages (`src/app/`)--| Route | File | Status |-|-------|------|--------|-| `/` | `page.tsx` | **Built** — stat cards, repo list, recent jobs |-| `layout.tsx` | Root layout | **Built** — Geist fonts, TooltipProvider, sidebar |-| `/repos/[id]` | `repos/[id]/page.tsx` | **Built** — git stats, head commit, overview content |-| `/repos/[id]/layout.tsx` | Repo layout | **Built** |-| `/repos/[id]/wiki/[...slug]` | `wiki/[...slug]/page.tsx` | **Built** — MDX pipeline with Shiki highlighting, Mermaid diagrams, sticky ToC, regenerate button |-| `/repos/[id]/search` | `search/page.tsx` | **Built** — debounce, type toggle, cmdk palette, result cards |-| `/repos/[id]/graph` | `graph/page.tsx` | **Built** — D3 canvas, zoom/pan, tooltips, filter panel, minimap |-| `/repos/[id]/symbols` | `symbols/page.tsx` | **Built** — sortable table, kind/language filters, detail drawer |-| `/repos/[id]/coverage` | `coverage/page.tsx` | **Built** — donut chart, freshness table, per-file regenerate |-| `/repos/[id]/ownership` | `ownership/page.tsx` | **Built** — granularity toggle, silo badges, contributor chart |-| `/repos/[id]/hotspots` | `hotspots/page.tsx` | **Built** — ranked table, churn bars, owner leaderboard |-| `/repos/[id]/dead-code` | `dead-code/page.tsx` | **Built** — tabs, row actions, bulk select, analyze trigger |-| `/settings` | `settings/page.tsx` | **Built** — connection, provider, webhook, MCP sections |-----+| `useRepo`, `useRepos` | SWR wrappers for repository data with 30s refresh |+| `usePage`, `usePageVersions` | Page content and version history |+| `useSearch` | Debounced search (300ms, min 2 chars) |+| `useGraph` (+ variants) | Graph data with stable caching (no revalidate on focus) |+| `useSSE` | Generic SSE hook with reconnection, exponential backoff, named events |+| `useJob` | Combines SWR polling + SSE streaming for real-time job monitoring |+| `useDebounce` | Generic value debounce |++### Component Organization (`src/components/`)++```+components/+ ui/ Radix-based primitives (button, card, dialog, tabs, tooltip, etc.)+ layout/ Sidebar, mobile nav+ wiki/ Wiki renderer, code blocks, Mermaid, ToC, confidence badge+ graph/ D3 canvas, filter panel, minimap, tooltip, ego sidebar, path finder+ search/ Command palette, search bar, result cards+ jobs/ Generation progress (SSE), job logs+ repos/ Add repo dialog, operations panel, run config form+ coverage/ Coverage donut chart, freshness table+ dead-code/ Findings table, row actions, summary bar+ decisions/ Decisions table, detail view, health widget+ git/ Churn bars, contributor charts, hotspot/ownership tables+ shared/ Stat cards, empty states+```++### Design System++Dark-mode only. All visual tokens are CSS custom properties in `src/styles/globals.css` — surfaces, borders, text colors, accent blue (`#5B9CF6`), confidence colors (green/yellow/red), language colors for graph nodes, edge type colors, typography scale, spacing grid, radii, and z-index layers. Changing the design means editing one file.## Development```powershell-# From repo root+# From repo root — requires the WikiCode API server on port 7337$env:WIKICODE_API_URL = "http://localhost:7337"npm run dev --workspace packages/web# Open http://localhost:3000```-Requires the WikiCode API server running on port 7337. See `TESTING_GUIDE.md` in the repo root.-```powershell# Type checknpm run type-check --workspace packages/web@@ -134,15 +155,3 @@ npm run type-check --workspace packages/web# Lintnpm run lint --workspace packages/web```-------## Architecture Notes--**Server vs Client components:** Default to RSC. Add `"use client"` only for interactivity (D3, command palette, SSE hooks, form state). Data fetching in RSC via direct `apiGet()` calls; client-side revalidation via SWR hooks.--**API proxy:** `next.config.ts` rewrites `/api/*` → `WIKICODE_API_URL/api/*` so the frontend never hard-codes the backend URL and CORS is handled at the proxy layer.--**Design tokens:** Everything uses CSS variables defined in `globals.css`. Changing the design means changing one file. No Tailwind config needed (v4 CSS-first).--**Embedder for search:** The backend uses `MockEmbedder` by default. Set `WIKICODE_EMBEDDER=gemini` when starting the server to activate real semantic search via `gemini-embedding-001`.diff --git a/tests/unit/server/test_graph.py b/tests/unit/server/test_graph.pyindex 0dfcc3066..9f5251a11 100644--- a/tests/unit/server/test_graph.py+++ b/tests/unit/server/test_graph.py@@ -109,3 +109,10 @@ async def test_dependency_path_no_path(client: AsyncClient, app) -> None:assert resp.status_code == 200data = resp.json()assert data["distance"] == -1 # No reverse path++ # Visual context should be returned+ ctx = data["visual_context"]+ assert ctx is not None+ assert ctx["reverse_path"]["exists"] is True # main -> utils exists+ assert ctx["disconnected"] is False+ assert "suggestion" in ctxdiff --git a/tests/unit/server/test_mcp.py b/tests/unit/server/test_mcp.pyindex 39b866558..fda3b1c46 100644--- a/tests/unit/server/test_mcp.py+++ b/tests/unit/server/test_mcp.py@@ -856,6 +856,25 @@ async def test_get_dependency_path_no_path(setup_mcp):assert result["distance"] == -1assert result["path"] == []+ # Visual context should be present+ ctx = result["visual_context"]+ assert ctx is not None++ # Reverse path exists (middleware -> service -> models)+ assert ctx["reverse_path"]["exists"] is True++ # Nearest common ancestor should be service.py (connects both via undirected)+ ancestors = ctx["nearest_common_ancestors"]+ assert len(ancestors) >= 1+ assert ancestors[0]["node"] == "src/auth/service.py"++ # Community analysis — models is community 2, middleware is community 1+ assert ctx["community"]["same_community"] is False++ # Not disconnected — they are reachable in undirected graph+ assert ctx["disconnected"] is False+ assert "suggestion" in ctx+@pytest.mark.asyncioasync def test_get_dependency_path_node_not_found(setup_mcp):