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
added docs viewer to frontend
RaghavChamadiyaed0bfe073541
diff --git a/packages/server/src/repowise/server/routers/pages.py b/packages/server/src/repowise/server/routers/pages.pyindex 45f62364c..f84f59e1d 100644--- a/packages/server/src/repowise/server/routers/pages.py+++ b/packages/server/src/repowise/server/routers/pages.py@@ -29,7 +29,7 @@ async def list_pages(page_type: str | None = Query(None, description="Filter by page type"),sort_by: str = Query("updated_at", description="Sort field: updated_at, confidence, created_at"),order: str = Query("desc", description="Sort order: asc or desc"),- limit: int = Query(100, ge=1, le=500),+ limit: int = Query(100, ge=1, le=5000),offset: int = Query(0, ge=0),session: AsyncSession = Depends(get_db_session),) -> list[PageResponse]:diff --git a/packages/web/src/app/repos/[id]/docs/page.tsx b/packages/web/src/app/repos/[id]/docs/page.tsxnew file mode 100644index 000000000..26f2ca2a8--- /dev/null+++ b/packages/web/src/app/repos/[id]/docs/page.tsx@@ -0,0 +1,31 @@+"use client";++import { use } from "react";+import { DocsExplorer } from "@/components/docs/docs-explorer";++export default function DocsPage({+ params,+}: {+ params: Promise<{ id: string }>;+}) {+ const { id: repoId } = use(params);++ return (+ <div className="flex flex-col h-screen">+ {/* Header */}+ <div className="shrink-0 px-4 sm:px-6 py-3 border-b border-[var(--color-border-default)]">+ <h1 className="text-lg font-semibold text-[var(--color-text-primary)]">+ Documentation+ </h1>+ <p className="text-xs text-[var(--color-text-secondary)] mt-0.5">+ Browse AI-generated documentation for every file, module, and symbol.+ </p>+ </div>++ {/* Explorer */}+ <div className="flex-1 min-h-0">+ <DocsExplorer repoId={repoId} />+ </div>+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/graph/page.tsx b/packages/web/src/app/repos/[id]/graph/page.tsxindex 2c12ace86..bd9c62533 100644--- a/packages/web/src/app/repos/[id]/graph/page.tsx+++ b/packages/web/src/app/repos/[id]/graph/page.tsx@@ -1,10 +1,11 @@"use client";-import { use, useCallback } from "react";+import { use, useCallback, useState } from "react";import { useQueryState, parseAsString, parseAsInteger } from "nuqs";import { GraphCanvas, type ViewMode } from "@/components/graph/graph-canvas";import { GraphViewSwitcher } from "@/components/graph/graph-view-switcher";import { GraphEgoSidebar } from "@/components/graph/graph-ego-sidebar";+import { GraphDocPanel } from "@/components/graph/graph-doc-panel";import { useEgoGraph } from "@/lib/hooks/use-graph";import { searchNodes } from "@/lib/api/graph";@@ -19,6 +20,7 @@ export default function GraphPage({const [node, setNode] = useQueryState("node");const [hops, setHops] = useQueryState("hops", parseAsInteger.withDefault(2));const [days, setDays] = useQueryState("days", parseAsInteger.withDefault(30));+ const [docNodeId, setDocNodeId] = useState<string | null>(null);const viewMode = view as ViewMode;@@ -62,6 +64,10 @@ export default function GraphPage({[viewMode, repoId, setView, setNode],);+ const handleNodeViewDocs = useCallback((nodeId: string) => {+ setDocNodeId((prev) => (prev === nodeId ? null : nodeId));+ }, []);+return (<div className="flex flex-col h-screen">{/* Header */}@@ -101,17 +107,27 @@ export default function GraphPage({hops={hops}days={days}onNodeClick={(nodeId) => void handleNodeClick(nodeId)}+ onNodeViewDocs={handleNodeViewDocs}onViewChange={(v) => void setView(v)}/>{/* Ego sidebar */}- {viewMode === "ego" && egoGraph && (+ {viewMode === "ego" && egoGraph && !docNodeId && (<GraphEgoSidebargraph={egoGraph}onClose={() => void setView("module")}onNavigateToNode={(nodeId) => void setNode(nodeId)}/>)}++ {/* Doc panel */}+ {docNodeId && (+ <GraphDocPanel+ repoId={repoId}+ nodeId={docNodeId}+ onClose={() => setDocNodeId(null)}+ />+ )}</div></div></div>diff --git a/packages/web/src/components/chat/chat-interface.tsx b/packages/web/src/components/chat/chat-interface.tsxindex 7e68d94c3..c29d0ac11 100644--- a/packages/web/src/components/chat/chat-interface.tsx+++ b/packages/web/src/components/chat/chat-interface.tsx@@ -180,6 +180,7 @@ export function ChatInterface({ repoId, repoName }: ChatInterfaceProps) {<ChatMessagekey={m.id}message={m}+ repoId={repoId}onViewArtifact={handleViewArtifact}/>))}diff --git a/packages/web/src/components/chat/chat-message.tsx b/packages/web/src/components/chat/chat-message.tsxindex 3a8859474..63c89648f 100644--- a/packages/web/src/components/chat/chat-message.tsx+++ b/packages/web/src/components/chat/chat-message.tsx@@ -4,14 +4,16 @@ import { Bot, User } from "lucide-react";import { cn } from "@/lib/utils/cn";import { ToolCallBlock } from "./tool-call-block";import { ChatMarkdown } from "./chat-markdown";+import { SourceCitations } from "./source-citations";import type { ChatMessage as ChatMessageType } from "@/lib/hooks/use-chat";interface ChatMessageProps {message: ChatMessageType;+ repoId: string;onViewArtifact?: (artifact: { type: string; data: Record<string, unknown> }) => void;}-export function ChatMessage({ message, onViewArtifact }: ChatMessageProps) {+export function ChatMessage({ message, repoId, onViewArtifact }: ChatMessageProps) {const isUser = message.role === "user";return (@@ -73,6 +75,11 @@ export function ChatMessage({ message, onViewArtifact }: ChatMessageProps) {</div>)}+ {/* Source citations */}+ {!message.isStreaming && message.toolCalls.length > 0 && (+ <SourceCitations toolCalls={message.toolCalls} repoId={repoId} />+ )}+{/* Streaming cursor */}{message.isStreaming &&!message.text &&diff --git a/packages/web/src/components/chat/source-citations.tsx b/packages/web/src/components/chat/source-citations.tsxnew file mode 100644index 000000000..0ebf65c21--- /dev/null+++ b/packages/web/src/components/chat/source-citations.tsx@@ -0,0 +1,210 @@+"use client";++import { useMemo } from "react";+import Link from "next/link";+import {+ FileText,+ FolderOpen,+ Globe,+ Sparkles,+ LayoutGrid,+ ArrowUpRight,+} from "lucide-react";+import { cn } from "@/lib/utils/cn";+import type { ChatToolCall } from "@/lib/hooks/use-chat";++// ---------------------------------------------------------------------------+// Types+// ---------------------------------------------------------------------------++export interface SourceReference {+ id: string;+ pageId: string;+ title: string;+ pageType: string;+ targetPath: string;+ score?: number;+ toolName: string;+}++// ---------------------------------------------------------------------------+// Extract sources from tool call results+// ---------------------------------------------------------------------------++export function extractSources(+ toolCalls: ChatToolCall[],+ repoId: string,+): SourceReference[] {+ const seen = new Set<string>();+ const sources: SourceReference[] = [];++ for (const tc of toolCalls) {+ if (tc.status !== "done" || !tc.result) continue;++ const result = tc.result as Record<string, unknown>;++ // search_codebase → results array+ if (tc.name === "search_codebase") {+ const results = (result.results as Array<Record<string, unknown>>) ?? [];+ for (const r of results) {+ const pageId = r.page_id as string;+ if (!pageId || seen.has(pageId)) continue;+ seen.add(pageId);+ sources.push({+ id: `${tc.id}:${pageId}`,+ pageId,+ title: (r.title as string) ?? pageId,+ pageType: (r.page_type as string) ?? "file_page",+ targetPath: (r.target_path as string) ?? "",+ score: r.relevance_score as number ?? r.score as number,+ toolName: tc.name,+ });+ }+ }++ // get_context → targets dict with docs+ if (tc.name === "get_context") {+ const targets = result.targets as Record<string, Record<string, unknown>> | undefined;+ if (targets) {+ for (const [target, info] of Object.entries(targets)) {+ const docs = info.docs as Record<string, unknown> | undefined;+ if (!docs) continue;+ const pageId = (docs.page_id as string) ?? `file_page:${target}`;+ if (seen.has(pageId)) continue;+ seen.add(pageId);+ sources.push({+ id: `${tc.id}:${pageId}`,+ pageId,+ title: (docs.title as string) ?? target.split("/").pop() ?? target,+ pageType: (docs.page_type as string) ?? "file_page",+ targetPath: target,+ toolName: tc.name,+ });+ }+ }+ }++ // get_overview → single overview page+ if (tc.name === "get_overview") {+ const title = result.title as string;+ if (title) {+ const pageId = "repo_overview:";+ if (!seen.has(pageId)) {+ seen.add(pageId);+ sources.push({+ id: `${tc.id}:overview`,+ pageId,+ title: title ?? "Repository Overview",+ pageType: "repo_overview",+ targetPath: "",+ toolName: tc.name,+ });+ }+ }+ }++ // get_why → decisions with page references+ if (tc.name === "get_why") {+ const decisions = (result.decisions as Array<Record<string, unknown>>)+ ?? (result.matching_decisions as Array<Record<string, unknown>>)+ ?? [];+ for (const d of decisions) {+ const affectedFiles = (d.affected_files as string[]) ?? [];+ for (const filePath of affectedFiles.slice(0, 3)) {+ const pageId = `file_page:${filePath}`;+ if (seen.has(pageId)) continue;+ seen.add(pageId);+ sources.push({+ id: `${tc.id}:${pageId}`,+ pageId,+ title: filePath.split("/").pop() ?? filePath,+ pageType: "file_page",+ targetPath: filePath,+ toolName: tc.name,+ });+ }+ }+ }++ // get_architecture_diagram — link to the diagram page+ if (tc.name === "get_architecture_diagram") {+ const pageId = "architecture_diagram:";+ if (!seen.has(pageId)) {+ seen.add(pageId);+ sources.push({+ id: `${tc.id}:arch-diagram`,+ pageId,+ title: "Architecture Diagram",+ pageType: "architecture_diagram",+ targetPath: "",+ toolName: tc.name,+ });+ }+ }+ }++ return sources;+}++// ---------------------------------------------------------------------------+// Icon helper+// ---------------------------------------------------------------------------++const TYPE_ICON: Record<string, React.ComponentType<{ className?: string }>> = {+ repo_overview: Globe,+ architecture_diagram: LayoutGrid,+ module_page: FolderOpen,+ symbol_spotlight: Sparkles,+};++function SourceIcon({ pageType, className }: { pageType: string; className?: string }) {+ const Icon = TYPE_ICON[pageType] ?? FileText;+ return <Icon className={className} />;+}++// ---------------------------------------------------------------------------+// Component+// ---------------------------------------------------------------------------++interface SourceCitationsProps {+ toolCalls: ChatToolCall[];+ repoId: string;+}++export function SourceCitations({ toolCalls, repoId }: SourceCitationsProps) {+ const sources = useMemo(+ () => extractSources(toolCalls, repoId),+ [toolCalls, repoId],+ );++ if (sources.length === 0) return null;++ return (+ <div className="mt-2 pt-2 border-t border-[var(--color-border-default)]/50">+ <p className="text-[10px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-medium mb-1.5">+ Sources+ </p>+ <div className="flex flex-wrap gap-1.5">+ {sources.map((source, idx) => (+ <Link+ key={source.id}+ href={`/repos/${repoId}/wiki/${encodeURIComponent(source.pageId)}`}+ className="group inline-flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-[10px] text-[var(--color-text-secondary)] hover:border-[var(--color-accent-primary)] hover:text-[var(--color-accent-primary)] hover:bg-[var(--color-accent-muted)] transition-all"+ >+ <span className="flex items-center justify-center h-3.5 w-3.5 rounded-sm bg-[var(--color-bg-overlay)] text-[9px] font-bold text-[var(--color-text-tertiary)] group-hover:bg-[var(--color-accent-primary)] group-hover:text-white shrink-0 transition-colors">+ {idx + 1}+ </span>+ <SourceIcon pageType={source.pageType} className="h-3 w-3 shrink-0 opacity-60" />+ <span className="truncate max-w-[160px] font-medium">{source.title}</span>+ {source.score != null && (+ <span className="text-[9px] text-[var(--color-text-tertiary)] tabular-nums">+ {(source.score * 100).toFixed(0)}%+ </span>+ )}+ <ArrowUpRight className="h-2.5 w-2.5 opacity-0 group-hover:opacity-100 transition-opacity shrink-0" />+ </Link>+ ))}+ </div>+ </div>+ );+}diff --git a/packages/web/src/components/docs/docs-explorer.tsx b/packages/web/src/components/docs/docs-explorer.tsxnew file mode 100644index 000000000..5e811eb55--- /dev/null+++ b/packages/web/src/components/docs/docs-explorer.tsx@@ -0,0 +1,99 @@+"use client";++import { useState, useCallback } from "react";+import { BookOpen, PanelLeftClose, PanelLeft } from "lucide-react";+import { cn } from "@/lib/utils/cn";+import { usePages } from "@/lib/hooks/use-pages";+import { DocsTree } from "./docs-tree";+import { DocsViewer } from "./docs-viewer";+import { Skeleton } from "@/components/ui/skeleton";+import type { PageResponse } from "@/lib/api/types";++interface DocsExplorerProps {+ repoId: string;+}++export function DocsExplorer({ repoId }: DocsExplorerProps) {+ const { pages, isLoading } = usePages(repoId);+ const [selectedPage, setSelectedPage] = useState<PageResponse | null>(null);+ const [treePanelOpen, setTreePanelOpen] = useState(true);++ const handleSelectPage = useCallback((page: PageResponse) => {+ setSelectedPage(page);+ }, []);++ if (isLoading) {+ return (+ <div className="flex h-full">+ <div className="w-[300px] border-r border-[var(--color-border-default)] p-3 space-y-2">+ <Skeleton className="h-8 w-full rounded-md" />+ <Skeleton className="h-4 w-3/4 rounded" />+ <Skeleton className="h-4 w-1/2 rounded" />+ <Skeleton className="h-4 w-5/6 rounded" />+ <Skeleton className="h-4 w-2/3 rounded" />+ <Skeleton className="h-4 w-3/4 rounded" />+ <Skeleton className="h-4 w-1/2 rounded" />+ </div>+ <div className="flex-1 flex items-center justify-center">+ <Skeleton className="h-8 w-48 rounded" />+ </div>+ </div>+ );+ }++ if (pages.length === 0) {+ return (+ <div className="flex flex-col items-center justify-center h-full gap-4 text-center px-8">+ <div className="rounded-full bg-[var(--color-bg-elevated)] border border-[var(--color-border-default)] p-4">+ <BookOpen className="h-8 w-8 text-[var(--color-text-tertiary)]" />+ </div>+ <div className="space-y-1">+ <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">+ No documentation yet+ </h3>+ <p className="text-xs text-[var(--color-text-secondary)] max-w-sm">+ Run a generation job to create AI-powered documentation for this codebase.+ </p>+ </div>+ </div>+ );+ }++ return (+ <div className="flex h-full">+ {/* Tree sidebar */}+ <div+ className={cn(+ "border-r border-[var(--color-border-default)] bg-[var(--color-bg-surface)] transition-all duration-200 shrink-0 relative",+ treePanelOpen ? "w-[300px]" : "w-0 overflow-hidden border-r-0",+ )}+ >+ <DocsTree+ pages={pages}+ selectedPageId={selectedPage?.id ?? null}+ onSelectPage={handleSelectPage}+ />+ </div>++ {/* Toggle button */}+ <button+ onClick={() => setTreePanelOpen((o) => !o)}+ className="absolute left-[300px] top-3 z-20 rounded-r-md border border-l-0 border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-1 text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)] transition-colors"+ style={{+ left: treePanelOpen ? "300px" : "0px",+ }}+ >+ {treePanelOpen ? (+ <PanelLeftClose className="h-3.5 w-3.5" />+ ) : (+ <PanelLeft className="h-3.5 w-3.5" />+ )}+ </button>++ {/* Viewer */}+ <div className="flex-1 min-w-0">+ <DocsViewer page={selectedPage} repoId={repoId} />+ </div>+ </div>+ );+}diff --git a/packages/web/src/components/docs/docs-tree.tsx b/packages/web/src/components/docs/docs-tree.tsxnew file mode 100644index 000000000..e643530be--- /dev/null+++ b/packages/web/src/components/docs/docs-tree.tsx@@ -0,0 +1,477 @@+"use client";++import { useState, useMemo } from "react";+import {+ ChevronDown,+ ChevronRight,+ FileText,+ FolderOpen,+ Folder,+ Globe,+ LayoutGrid,+ Sparkles,+ Search,+ Filter,+} from "lucide-react";+import { cn } from "@/lib/utils/cn";+import { statusBadgeClasses } from "@/lib/utils/confidence";+import type { PageResponse } from "@/lib/api/types";+import type { FreshnessStatus } from "@/lib/utils/confidence";++// ---------------------------------------------------------------------------+// Types+// ---------------------------------------------------------------------------++interface TreeNode {+ name: string;+ path: string;+ isDir: boolean;+ page?: PageResponse;+ children: TreeNode[];+}++interface DocsTreeProps {+ pages: PageResponse[];+ selectedPageId: string | null;+ onSelectPage: (page: PageResponse) => void;+ className?: string;+}++// ---------------------------------------------------------------------------+// Page type icons+// ---------------------------------------------------------------------------++const PAGE_TYPE_ICON: Record<string, React.ComponentType<{ className?: string }>> = {+ repo_overview: Globe,+ architecture_diagram: LayoutGrid,+ module_page: FolderOpen,+ symbol_spotlight: Sparkles,+};++function PageIcon({ pageType, className }: { pageType: string; className?: string }) {+ const Icon = PAGE_TYPE_ICON[pageType] ?? FileText;+ return <Icon className={className} />;+}++// ---------------------------------------------------------------------------+// Build tree from flat page list+// ---------------------------------------------------------------------------++function buildTree(pages: PageResponse[]): TreeNode[] {+ const root: TreeNode[] = [];++ // Separate special pages (overview, architecture) from path-based pages+ const specialPages: PageResponse[] = [];+ const pathPages: PageResponse[] = [];++ for (const page of pages) {+ if (page.page_type === "repo_overview" || page.page_type === "architecture_diagram") {+ specialPages.push(page);+ } else {+ pathPages.push(page);+ }+ }++ // Add special pages at top level+ for (const page of specialPages) {+ root.push({+ name: page.title,+ path: page.id,+ isDir: false,+ page,+ children: [],+ });+ }++ // Build directory tree from path-based pages+ const dirMap = new Map<string, TreeNode>();++ function ensureDir(dirPath: string): TreeNode {+ if (dirMap.has(dirPath)) return dirMap.get(dirPath)!;++ const parts = dirPath.split("/");+ const name = parts[parts.length - 1];+ const node: TreeNode = {+ name,+ path: dirPath,+ isDir: true,+ children: [],+ };+ dirMap.set(dirPath, node);++ if (parts.length > 1) {+ const parentPath = parts.slice(0, -1).join("/");+ const parent = ensureDir(parentPath);+ // Only add if not already a child+ if (!parent.children.some((c) => c.path === dirPath)) {+ parent.children.push(node);+ }+ }++ return node;+ }++ // Check if any path page is a module_page that matches a directory+ const modulePaths = new Set(+ pathPages.filter((p) => p.page_type === "module_page").map((p) => p.target_path),+ );++ for (const page of pathPages) {+ const targetPath = page.target_path;+ if (!targetPath) continue;++ if (page.page_type === "module_page") {+ // Module pages become directories with their page attached+ const dirNode = ensureDir(targetPath);+ dirNode.page = page;+ } else {+ // File pages go into their parent directory+ const parts = targetPath.split("/");+ const fileName = parts[parts.length - 1];++ const fileNode: TreeNode = {+ name: fileName,+ path: page.id,+ isDir: false,+ page,+ children: [],+ };++ if (parts.length > 1) {+ const parentPath = parts.slice(0, -1).join("/");+ const parent = ensureDir(parentPath);+ parent.children.push(fileNode);+ } else {+ root.push(fileNode);+ }+ }+ }++ // Add top-level directories to root+ for (const [dirPath, node] of dirMap) {+ if (!dirPath.includes("/")) {+ root.push(node);+ }+ }++ // Sort children: directories first, then files, both alphabetically+ function sortChildren(nodes: TreeNode[]) {+ nodes.sort((a, b) => {+ if (a.isDir && !b.isDir) return -1;+ if (!a.isDir && b.isDir) return 1;+ return a.name.localeCompare(b.name);+ });+ for (const node of nodes) {+ if (node.children.length > 0) sortChildren(node.children);+ }+ }++ sortChildren(root);+ return root;+}++// ---------------------------------------------------------------------------+// Filter helpers+// ---------------------------------------------------------------------------++type TypeFilter = "all" | "file_page" | "module_page" | "symbol_spotlight" | "repo_overview";+type FreshnessFilter = "all" | "fresh" | "stale" | "outdated";++function matchesFilters(+ page: PageResponse | undefined,+ search: string,+ typeFilter: TypeFilter,+ freshnessFilter: FreshnessFilter,+): boolean {+ if (!page) return true; // directories always pass (will be pruned if empty)+ if (typeFilter !== "all" && page.page_type !== typeFilter) return false;+ if (freshnessFilter !== "all" && page.freshness_status !== freshnessFilter) return false;+ if (search) {+ const q = search.toLowerCase();+ return (+ page.title.toLowerCase().includes(q) ||+ page.target_path.toLowerCase().includes(q)+ );+ }+ return true;+}++function filterTree(+ nodes: TreeNode[],+ search: string,+ typeFilter: TypeFilter,+ freshnessFilter: FreshnessFilter,+): TreeNode[] {+ const result: TreeNode[] = [];+ for (const node of nodes) {+ if (node.isDir) {+ const filteredChildren = filterTree(node.children, search, typeFilter, freshnessFilter);+ const dirPageMatches = node.page+ ? matchesFilters(node.page, search, typeFilter, freshnessFilter)+ : false;+ if (filteredChildren.length > 0 || dirPageMatches) {+ result.push({ ...node, children: filteredChildren });+ }+ } else {+ if (matchesFilters(node.page, search, typeFilter, freshnessFilter)) {+ result.push(node);+ }+ }+ }+ return result;+}++// ---------------------------------------------------------------------------+// Tree node component+// ---------------------------------------------------------------------------++function TreeItem({+ node,+ depth,+ selectedPageId,+ expandedDirs,+ toggleDir,+ onSelectPage,+}: {+ node: TreeNode;+ depth: number;+ selectedPageId: string | null;+ expandedDirs: Set<string>;+ toggleDir: (path: string) => void;+ onSelectPage: (page: PageResponse) => void;+}) {+ const isExpanded = expandedDirs.has(node.path);+ const isSelected = node.page && node.page.id === selectedPageId;+ const hasChildren = node.children.length > 0;++ if (node.isDir) {+ return (+ <div>+ <button+ onClick={() => {+ toggleDir(node.path);+ if (node.page) onSelectPage(node.page);+ }}+ className={cn(+ "flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-xs transition-colors hover:bg-[var(--color-bg-elevated)]",+ isSelected+ ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"+ : "text-[var(--color-text-secondary)]",+ )}+ style={{ paddingLeft: `${depth * 16 + 8}px` }}+ >+ {hasChildren ? (+ isExpanded ? (+ <ChevronDown className="h-3 w-3 shrink-0 opacity-50" />+ ) : (+ <ChevronRight className="h-3 w-3 shrink-0 opacity-50" />+ )+ ) : (+ <span className="w-3 shrink-0" />+ )}+ {isExpanded ? (+ <FolderOpen className="h-3.5 w-3.5 shrink-0 text-[var(--color-accent-primary)] opacity-70" />+ ) : (+ <Folder className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)]" />+ )}+ <span className="truncate font-medium">{node.name}</span>+ {node.page && (+ <FreshnessDot status={node.page.freshness_status as FreshnessStatus} />+ )}+ </button>++ {isExpanded && hasChildren && (+ <div>+ {node.children.map((child) => (+ <TreeItem+ key={child.path}+ node={child}+ depth={depth + 1}+ selectedPageId={selectedPageId}+ expandedDirs={expandedDirs}+ toggleDir={toggleDir}+ onSelectPage={onSelectPage}+ />+ ))}+ </div>+ )}+ </div>+ );+ }++ // File/leaf node+ return (+ <button+ onClick={() => node.page && onSelectPage(node.page)}+ className={cn(+ "flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-xs transition-colors hover:bg-[var(--color-bg-elevated)]",+ isSelected+ ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"+ : "text-[var(--color-text-secondary)]",+ )}+ style={{ paddingLeft: `${depth * 16 + 8 + 16}px` }}+ >+ <PageIcon+ pageType={node.page?.page_type ?? "file_page"}+ className={cn(+ "h-3.5 w-3.5 shrink-0",+ isSelected ? "text-[var(--color-accent-primary)]" : "text-[var(--color-text-tertiary)]",+ )}+ />+ <span className="truncate">{node.name}</span>+ {node.page && (+ <FreshnessDot status={node.page.freshness_status as FreshnessStatus} />+ )}+ </button>+ );+}++function FreshnessDot({ status }: { status: FreshnessStatus }) {+ const color =+ status === "fresh"+ ? "bg-green-500"+ : status === "stale"+ ? "bg-yellow-500"+ : "bg-red-500";+ return <span className={cn("ml-auto h-1.5 w-1.5 rounded-full shrink-0", color)} />;+}++// ---------------------------------------------------------------------------+// Main DocsTree component+// ---------------------------------------------------------------------------++export function DocsTree({ pages, selectedPageId, onSelectPage, className }: DocsTreeProps) {+ const [search, setSearch] = useState("");+ const [typeFilter, setTypeFilter] = useState<TypeFilter>("all");+ const [freshnessFilter, setFreshnessFilter] = useState<FreshnessFilter>("all");+ const [expandedDirs, setExpandedDirs] = useState<Set<string>>(() => {+ // Auto-expand first two levels+ const dirs = new Set<string>();+ for (const page of pages) {+ const parts = page.target_path.split("/");+ if (parts.length > 1) dirs.add(parts[0]);+ }+ return dirs;+ });+ const [showFilters, setShowFilters] = useState(false);++ const tree = useMemo(() => buildTree(pages), [pages]);+ const filteredTree = useMemo(+ () => filterTree(tree, search, typeFilter, freshnessFilter),+ [tree, search, typeFilter, freshnessFilter],+ );++ const toggleDir = (path: string) => {+ setExpandedDirs((prev) => {+ const next = new Set(prev);+ if (next.has(path)) next.delete(path);+ else next.add(path);+ return next;+ });+ };++ // Stats+ const totalPages = pages.length;+ const freshCount = pages.filter((p) => p.freshness_status === "fresh").length;++ return (+ <div className={cn("flex flex-col h-full", className)}>+ {/* Search + filter bar */}+ <div className="p-3 space-y-2 border-b border-[var(--color-border-default)]">+ <div className="flex items-center gap-2">+ <div className="flex-1 flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1.5">+ <Search className="h-3.5 w-3.5 text-[var(--color-text-tertiary)] shrink-0" />+ <input+ type="text"+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Search docs..."+ className="flex-1 bg-transparent text-xs text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] outline-none"+ />+ </div>+ <button+ onClick={() => setShowFilters((s) => !s)}+ className={cn(+ "rounded-md p-1.5 transition-colors",+ showFilters+ ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"+ : "text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-secondary)]",+ )}+ >+ <Filter className="h-3.5 w-3.5" />+ </button>+ </div>++ {showFilters && (+ <div className="space-y-1.5">+ <div className="flex items-center gap-1 flex-wrap">+ <span className="text-[10px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-medium w-10">Type</span>+ {(["all", "file_page", "module_page", "symbol_spotlight", "repo_overview"] as TypeFilter[]).map((t) => (+ <button+ key={t}+ onClick={() => setTypeFilter(t)}+ className={cn(+ "rounded-full px-2 py-0.5 text-[10px] border transition-colors",+ typeFilter === t+ ? "border-[var(--color-accent-primary)] bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"+ : "border-[var(--color-border-default)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]",+ )}+ >+ {t === "all" ? "All" : t.replace(/_/g, " ").replace("page", "").trim() || "file"}+ </button>+ ))}+ </div>+ <div className="flex items-center gap-1 flex-wrap">+ <span className="text-[10px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-medium w-10">Status</span>+ {(["all", "fresh", "stale", "outdated"] as FreshnessFilter[]).map((f) => (+ <button+ key={f}+ onClick={() => setFreshnessFilter(f)}+ className={cn(+ "rounded-full px-2 py-0.5 text-[10px] border transition-colors",+ freshnessFilter === f+ ? f === "all"+ ? "border-[var(--color-accent-primary)] bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"+ : statusBadgeClasses(f as FreshnessStatus)+ : "border-[var(--color-border-default)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]",+ )}+ >+ {f === "all" ? "All" : f.charAt(0).toUpperCase() + f.slice(1)}+ </button>+ ))}+ </div>+ </div>+ )}++ {/* Stats line */}+ <div className="flex items-center justify-between text-[10px] text-[var(--color-text-tertiary)]">+ <span>{totalPages} pages</span>+ <span>{freshCount} fresh · {totalPages - freshCount} need attention</span>+ </div>+ </div>++ {/* Tree */}+ <div className="flex-1 overflow-y-auto p-1.5">+ {filteredTree.length === 0 ? (+ <div className="flex flex-col items-center justify-center h-32 text-xs text-[var(--color-text-tertiary)]">+ <p>No matching pages</p>+ </div>+ ) : (+ <div className="space-y-0.5">+ {filteredTree.map((node) => (+ <TreeItem+ key={node.path}+ node={node}+ depth={0}+ selectedPageId={selectedPageId}+ expandedDirs={expandedDirs}+ toggleDir={toggleDir}+ onSelectPage={onSelectPage}+ />+ ))}+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/packages/web/src/components/docs/docs-viewer.tsx b/packages/web/src/components/docs/docs-viewer.tsxnew file mode 100644index 000000000..18b625fa3--- /dev/null+++ b/packages/web/src/components/docs/docs-viewer.tsx@@ -0,0 +1,125 @@+"use client";++import { useEffect, useRef } from "react";+import Link from "next/link";+import {+ FileText,+ Clock,+ Cpu,+ Hash,+ ExternalLink,+ ArrowRight,+ RefreshCw,+ Loader2,+} from "lucide-react";+import { cn } from "@/lib/utils/cn";+import { ChatMarkdown } from "@/components/chat/chat-markdown";+import { ConfidenceBadge } from "@/components/wiki/confidence-badge";+import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";+import { formatRelativeTime, formatTokens } from "@/lib/utils/format";+import type { PageResponse } from "@/lib/api/types";++interface DocsViewerProps {+ page: PageResponse | null;+ repoId: string;+ isLoading?: boolean;+}++export function DocsViewer({ page, repoId, isLoading }: DocsViewerProps) {+ const scrollRef = useRef<HTMLDivElement>(null);++ // Scroll to top when page changes+ useEffect(() => {+ scrollRef.current?.scrollTo(0, 0);+ }, [page?.id]);++ if (isLoading) {+ return (+ <div className="flex items-center justify-center h-full">+ <Loader2 className="h-5 w-5 animate-spin text-[var(--color-accent-primary)]" />+ </div>+ );+ }++ if (!page) {+ return (+ <div className="flex flex-col items-center justify-center h-full gap-4 text-center px-8">+ <div className="rounded-full bg-[var(--color-bg-elevated)] border border-[var(--color-border-default)] p-4">+ <FileText className="h-8 w-8 text-[var(--color-text-tertiary)]" />+ </div>+ <div className="space-y-1">+ <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">+ Select a page+ </h3>+ <p className="text-xs text-[var(--color-text-secondary)] max-w-sm">+ Choose a file or module from the tree to view its AI-generated documentation.+ </p>+ </div>+ </div>+ );+ }++ return (+ <div className="flex flex-col h-full">+ {/* Sticky header */}+ <div className="sticky top-0 z-10 flex items-center gap-2 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)]/95 backdrop-blur px-4 sm:px-6 py-2.5 flex-wrap sm:flex-nowrap shrink-0">+ {/* Path breadcrumb */}+ <div className="flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)] min-w-0 flex-1">+ <span className="font-mono truncate text-[var(--color-text-secondary)]">+ {page.target_path || page.page_type}+ </span>+ </div>++ {/* Confidence */}+ <ConfidenceBadge+ score={page.confidence}+ status={page.freshness_status}+ showScore+ />++ {/* Provider */}+ <Badge variant="outline" className="font-mono text-[10px] hidden sm:flex shrink-0">+ <Cpu className="h-2.5 w-2.5 mr-1" />+ <span className="truncate max-w-[100px]">{page.model_name}</span>+ </Badge>++ {/* Open full page link */}+ <Link+ href={`/repos/${repoId}/wiki/${encodeURIComponent(page.id)}`}+ className="text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-primary)] transition-colors shrink-0"+ title="Open full page"+ >+ <ExternalLink className="h-3.5 w-3.5" />+ </Link>+ </div>++ {/* Content */}+ <div ref={scrollRef} className="flex-1 overflow-y-auto">+ <div className="px-4 sm:px-6 py-6 max-w-[768px] mx-auto">+ {/* Title */}+ <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 break-words">+ {page.title}+ </h1>++ {/* Meta row */}+ <div className="flex items-center gap-3 text-[10px] text-[var(--color-text-tertiary)] mb-6">+ <span className="flex items-center gap-1">+ <Clock className="h-3 w-3" />+ {formatRelativeTime(page.updated_at)}+ </span>+ <span>v{page.version}</span>+ <span className="font-mono">+ {formatTokens(page.input_tokens)} in · {formatTokens(page.output_tokens)} out+ </span>+ </div>++ {/* Markdown content */}+ <article className="prose-chat">+ <ChatMarkdown content={page.content} />+ </article>+ </div>+ </div>+ </div>+ );+}diff --git a/packages/web/src/components/graph/graph-canvas.tsx b/packages/web/src/components/graph/graph-canvas.tsxindex 1ab7cff3e..0891f4fc8 100644--- a/packages/web/src/components/graph/graph-canvas.tsx+++ b/packages/web/src/components/graph/graph-canvas.tsx@@ -117,6 +117,7 @@ export interface GraphCanvasProps {hops?: number;days?: number;onNodeClick?: (nodeId: string) => void;+ onNodeViewDocs?: (nodeId: string) => void;onViewChange?: (view: ViewMode) => void;}@@ -127,6 +128,7 @@ export function GraphCanvas({hops = 2,days = 30,onNodeClick,+ onNodeViewDocs,onViewChange,}: GraphCanvasProps) {const router = useRouter();@@ -616,11 +618,12 @@ export function GraphCanvas({if (viewMode === "module") {onNodeClick?.(closest.node_id);} else {- router.push(`/repos/${repoId}/wiki/${encodeURIComponent(closest.node_id)}`);+ // Open doc panel for the clicked node+ onNodeViewDocs?.(closest.node_id);}}},- [filters, router, repoId, viewMode, onNodeClick],+ [filters, viewMode, onNodeClick, onNodeViewDocs],);const isLoading =diff --git a/packages/web/src/components/graph/graph-doc-panel.tsx b/packages/web/src/components/graph/graph-doc-panel.tsxnew file mode 100644index 000000000..456c7fbbb--- /dev/null+++ b/packages/web/src/components/graph/graph-doc-panel.tsx@@ -0,0 +1,123 @@+"use client";++import { useEffect, useRef } from "react";+import Link from "next/link";+import {+ X,+ FileText,+ ExternalLink,+ Clock,+ Cpu,+ Loader2,+ AlertCircle,+} from "lucide-react";+import { cn } from "@/lib/utils/cn";+import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";+import { ChatMarkdown } from "@/components/chat/chat-markdown";+import { ConfidenceBadge } from "@/components/wiki/confidence-badge";+import { usePage } from "@/lib/hooks/use-page";+import { formatRelativeTime } from "@/lib/utils/format";++interface GraphDocPanelProps {+ repoId: string;+ nodeId: string;+ onClose: () => void;+}++export function GraphDocPanel({ repoId, nodeId, onClose }: GraphDocPanelProps) {+ const pageId = `file_page:${nodeId}`;+ const { page, isLoading, error } = usePage(pageId);+ const scrollRef = useRef<HTMLDivElement>(null);++ useEffect(() => {+ scrollRef.current?.scrollTo(0, 0);+ }, [nodeId]);++ return (+ <div className="absolute top-0 right-0 z-20 h-full w-[400px] flex flex-col bg-[var(--color-bg-surface)] border-l border-[var(--color-border-default)] shadow-2xl shadow-black/30">+ {/* Header */}+ <div className="flex items-center gap-2 px-4 py-3 border-b border-[var(--color-border-default)] shrink-0">+ <FileText className="h-4 w-4 text-[var(--color-accent-primary)] shrink-0" />+ <div className="flex-1 min-w-0">+ <p className="text-xs font-medium text-[var(--color-text-primary)] truncate">+ {page?.title ?? nodeId.split("/").pop()}+ </p>+ <p className="text-[10px] text-[var(--color-text-tertiary)] font-mono truncate">+ {nodeId}+ </p>+ </div>+ <div className="flex items-center gap-1.5 shrink-0">+ {page && (+ <Link+ href={`/repos/${repoId}/wiki/${encodeURIComponent(page.id)}`}+ className="text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-primary)] transition-colors p-1"+ title="Open full page"+ >+ <ExternalLink className="h-3.5 w-3.5" />+ </Link>+ )}+ <Button+ size="sm"+ variant="ghost"+ onClick={onClose}+ className="h-6 w-6 p-0"+ >+ <X className="h-3.5 w-3.5" />+ </Button>+ </div>+ </div>++ {/* Meta bar */}+ {page && (+ <div className="flex items-center gap-2 px-4 py-2 border-b border-[var(--color-border-default)] shrink-0 flex-wrap">+ <ConfidenceBadge+ score={page.confidence}+ status={page.freshness_status}+ showScore+ />+ <Badge variant="outline" className="font-mono text-[10px]">+ <Cpu className="h-2.5 w-2.5 mr-0.5" />+ {page.model_name}+ </Badge>+ <span className="text-[10px] text-[var(--color-text-tertiary)] flex items-center gap-1 ml-auto">+ <Clock className="h-2.5 w-2.5" />+ {formatRelativeTime(page.updated_at)}+ </span>+ </div>+ )}++ {/* Content */}+ <div ref={scrollRef} className="flex-1 overflow-y-auto">+ {isLoading && (+ <div className="flex items-center justify-center h-32">+ <Loader2 className="h-5 w-5 animate-spin text-[var(--color-accent-primary)]" />+ </div>+ )}++ {error && !isLoading && (+ <div className="flex flex-col items-center justify-center h-32 gap-2 px-6 text-center">+ <AlertCircle className="h-5 w-5 text-[var(--color-text-tertiary)]" />+ <p className="text-xs text-[var(--color-text-tertiary)]">+ No documentation found for this file.+ </p>+ <Link+ href={`/repos/${repoId}/docs`}+ className="text-xs text-[var(--color-accent-primary)] hover:underline"+ >+ Browse all docs+ </Link>+ </div>+ )}++ {page && !isLoading && (+ <div className="px-4 py-4">+ <article className="prose-chat text-xs">+ <ChatMarkdown content={page.content} />+ </article>+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/packages/web/src/components/graph/graph-tooltip.tsx b/packages/web/src/components/graph/graph-tooltip.tsxindex 0778fe7d0..d1dd77a7f 100644--- a/packages/web/src/components/graph/graph-tooltip.tsx+++ b/packages/web/src/components/graph/graph-tooltip.tsx@@ -1,3 +1,4 @@+import { FileText } from "lucide-react";import { formatNumber } from "@/lib/utils/format";import type { GraphNodeResponse } from "@/lib/api/types";@@ -10,8 +11,8 @@ interface GraphTooltipProps {}export function GraphTooltip({ node, x, y, canvasWidth, canvasHeight }: GraphTooltipProps) {- const tooltipW = 200;- const tooltipH = 130;+ const tooltipW = 220;+ const tooltipH = 150;const left = x + 16 + tooltipW > canvasWidth ? x - tooltipW - 8 : x + 16;const top = y + tooltipH > canvasHeight ? y - tooltipH : y;@@ -52,6 +53,11 @@ export function GraphTooltip({ node, x, y, canvasWidth, canvasHeight }: GraphToo</span>)}</div>+ {/* Hint for clicking */}+ <div className="mt-2 pt-2 border-t border-[var(--color-border-default)]/50 flex items-center gap-1.5 text-[10px] text-[var(--color-text-tertiary)]">+ <FileText className="h-3 w-3" />+ <span>Click to view docs</span>+ </div></div>);}diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex 4936fa497..c9460f637 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -42,6 +42,7 @@ const GLOBAL_NAV: NavItem[] = [function repoNavItems(repoId: string): NavItem[] {return [{ label: "Chat", href: `/repos/${repoId}`, icon: MessageSquare },+ { label: "Docs", href: `/repos/${repoId}/docs`, icon: BookOpen },{ label: "Search", href: `/repos/${repoId}/search`, icon: Search },{ label: "Graph", href: `/repos/${repoId}/graph`, icon: GitBranch },{ label: "Symbols", href: `/repos/${repoId}/symbols`, icon: Code2 },