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
Add missing web source files and fix gitignore lib/ rule
RaghavChamadiyaf56d7f357f1b
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.ymlindex d1826b23f..217bbf1c9 100644--- a/.github/workflows/publish.yml+++ b/.github/workflows/publish.yml@@ -131,3 +131,5 @@ jobs:- name: Publish to PyPIuses: pypa/gh-action-pypi-publish@release/v1+ with:+ skip-existing: truediff --git a/.gitignore b/.gitignoreindex 0f47b4daa..3a93f322b 100644--- a/.gitignore+++ b/.gitignore@@ -10,8 +10,9 @@ dist/downloads/eggs/.eggs/-lib/-lib64/+# Python build dirs (only at root, not packages/web/src/lib/)+/lib/+/lib64/parts/sdist/var/diff --git a/packages/web/src/lib/api/dead-code.ts b/packages/web/src/lib/api/dead-code.tsnew file mode 100644index 000000000..4990e927d--- /dev/null+++ b/packages/web/src/lib/api/dead-code.ts@@ -0,0 +1,34 @@+import { apiGet, apiPost, apiPatch } from "./client";+import type {+ DeadCodeFindingResponse,+ DeadCodePatchRequest,+ DeadCodeSummaryResponse,+} from "./types";++export async function listDeadCode(+ repoId: string,+ opts?: {+ kind?: string;+ min_confidence?: number;+ status?: string;+ safe_only?: boolean;+ limit?: number;+ },+): Promise<DeadCodeFindingResponse[]> {+ return apiGet<DeadCodeFindingResponse[]>(`/api/repos/${repoId}/dead-code`, opts);+}++export async function analyzeDeadCode(repoId: string): Promise<{ job_id: string }> {+ return apiPost<{ job_id: string }>(`/api/repos/${repoId}/dead-code/analyze`);+}++export async function getDeadCodeSummary(repoId: string): Promise<DeadCodeSummaryResponse> {+ return apiGet<DeadCodeSummaryResponse>(`/api/repos/${repoId}/dead-code/summary`);+}++export async function patchDeadCodeFinding(+ findingId: string,+ data: DeadCodePatchRequest,+): Promise<DeadCodeFindingResponse> {+ return apiPatch<DeadCodeFindingResponse>(`/api/dead-code/${findingId}`, data);+}diff --git a/packages/web/src/lib/api/decisions.ts b/packages/web/src/lib/api/decisions.tsnew file mode 100644index 000000000..7a6c2d392--- /dev/null+++ b/packages/web/src/lib/api/decisions.ts@@ -0,0 +1,56 @@+import { apiGet, apiPost, apiPatch } from "./client";+import type {+ DecisionCreate,+ DecisionHealthResponse,+ DecisionRecordResponse,+ DecisionStatusUpdate,+} from "./types";++export async function listDecisions(+ repoId: string,+ opts?: {+ status?: string;+ source?: string;+ tag?: string;+ module?: string;+ include_proposed?: boolean;+ limit?: number;+ },+): Promise<DecisionRecordResponse[]> {+ return apiGet<DecisionRecordResponse[]>(`/api/repos/${repoId}/decisions`, opts);+}++export async function getDecision(+ repoId: string,+ decisionId: string,+): Promise<DecisionRecordResponse> {+ return apiGet<DecisionRecordResponse>(+ `/api/repos/${repoId}/decisions/${decisionId}`,+ );+}++export async function createDecision(+ repoId: string,+ data: DecisionCreate,+): Promise<DecisionRecordResponse> {+ return apiPost<DecisionRecordResponse>(`/api/repos/${repoId}/decisions`, data);+}++export async function patchDecision(+ repoId: string,+ decisionId: string,+ data: DecisionStatusUpdate,+): Promise<DecisionRecordResponse> {+ return apiPatch<DecisionRecordResponse>(+ `/api/repos/${repoId}/decisions/${decisionId}`,+ data,+ );+}++export async function getDecisionHealth(+ repoId: string,+): Promise<DecisionHealthResponse> {+ return apiGet<DecisionHealthResponse>(+ `/api/repos/${repoId}/decisions/health`,+ );+}diff --git a/packages/web/src/lib/api/git.ts b/packages/web/src/lib/api/git.tsnew file mode 100644index 000000000..d3aba0708--- /dev/null+++ b/packages/web/src/lib/api/git.ts@@ -0,0 +1,45 @@+import { apiGet } from "./client";+import type {+ GitMetadataResponse,+ HotspotResponse,+ OwnershipEntry,+ GitSummaryResponse,+} from "./types";++export async function getGitMetadata(+ repoId: string,+ filePath: string,+): Promise<GitMetadataResponse> {+ return apiGet<GitMetadataResponse>(`/api/repos/${repoId}/git-metadata`, {+ file_path: filePath,+ });+}++export async function getHotspots(+ repoId: string,+ limit = 20,+): Promise<HotspotResponse[]> {+ return apiGet<HotspotResponse[]>(`/api/repos/${repoId}/hotspots`, { limit });+}++export async function getOwnership(+ repoId: string,+ granularity: "file" | "module" = "module",+): Promise<OwnershipEntry[]> {+ return apiGet<OwnershipEntry[]>(`/api/repos/${repoId}/ownership`, { granularity });+}++export async function getCoChanges(+ repoId: string,+ filePath: string,+ minCount = 3,+): Promise<{ file_path: string; co_change_partners: Array<{ file_path: string; co_change_count: number }> }> {+ return apiGet(`/api/repos/${repoId}/co-changes`, {+ file_path: filePath,+ min_count: minCount,+ });+}++export async function getGitSummary(repoId: string): Promise<GitSummaryResponse> {+ return apiGet<GitSummaryResponse>(`/api/repos/${repoId}/git-summary`);+}diff --git a/packages/web/src/lib/api/graph.ts b/packages/web/src/lib/api/graph.tsnew file mode 100644index 000000000..2d142c1f8--- /dev/null+++ b/packages/web/src/lib/api/graph.ts@@ -0,0 +1,58 @@+import { apiGet } from "./client";+import type {+ DeadCodeGraphResponse,+ EgoGraphResponse,+ GraphExportResponse,+ GraphPathResponse,+ HotFilesGraphResponse,+ ModuleGraphResponse,+ NodeSearchResult,+} from "./types";++export async function getGraph(repoId: string): Promise<GraphExportResponse> {+ return apiGet<GraphExportResponse>(`/api/graph/${repoId}`);+}++export async function getGraphPath(+ repoId: string,+ from: string,+ to: string,+): Promise<GraphPathResponse> {+ return apiGet<GraphPathResponse>(`/api/graph/${repoId}/path`, { from, to });+}++export async function getModuleGraph(repoId: string): Promise<ModuleGraphResponse> {+ return apiGet<ModuleGraphResponse>(`/api/graph/${repoId}/modules`);+}++export async function getEgoGraph(+ repoId: string,+ nodeId: string,+ hops = 2,+): Promise<EgoGraphResponse> {+ return apiGet<EgoGraphResponse>(`/api/graph/${repoId}/ego`, { node_id: nodeId, hops });+}++export async function searchNodes(+ repoId: string,+ q: string,+ limit = 10,+): Promise<NodeSearchResult[]> {+ return apiGet<NodeSearchResult[]>(`/api/graph/${repoId}/nodes/search`, { q, limit });+}++export async function getArchitectureGraph(repoId: string): Promise<GraphExportResponse> {+ return apiGet<GraphExportResponse>(`/api/graph/${repoId}/entry-points`);+}++export async function getDeadCodeGraph(repoId: string): Promise<DeadCodeGraphResponse> {+ return apiGet<DeadCodeGraphResponse>(`/api/graph/${repoId}/dead-nodes`);+}++export async function getHotFilesGraph(+ repoId: string,+ days = 30,+ limit = 25,+): Promise<HotFilesGraphResponse> {+ return apiGet<HotFilesGraphResponse>(`/api/graph/${repoId}/hot-files`, { days, limit });+}diff --git a/packages/web/src/lib/api/health.ts b/packages/web/src/lib/api/health.tsnew file mode 100644index 000000000..4fe270505--- /dev/null+++ b/packages/web/src/lib/api/health.ts@@ -0,0 +1,6 @@+import { apiGet } from "./client";+import type { HealthResponse } from "./types";++export async function getHealth(): Promise<HealthResponse> {+ return apiGet<HealthResponse>("/health");+}diff --git a/packages/web/src/lib/api/jobs.ts b/packages/web/src/lib/api/jobs.tsnew file mode 100644index 000000000..0768e43f4--- /dev/null+++ b/packages/web/src/lib/api/jobs.ts@@ -0,0 +1,21 @@+import { apiGet } from "./client";+import type { JobResponse } from "./types";++export async function listJobs(opts?: {+ repo_id?: string;+ status?: string;+ limit?: number;+ offset?: number;+}): Promise<JobResponse[]> {+ return apiGet<JobResponse[]>("/api/jobs", opts);+}++export async function getJob(jobId: string): Promise<JobResponse> {+ return apiGet<JobResponse>(`/api/jobs/${jobId}`);+}++/** Returns the SSE stream URL for a job. Use with EventSource or the useSSE hook. */+export function getJobStreamUrl(jobId: string): string {+ const base = process.env.NEXT_PUBLIC_REPOWISE_API_URL ?? "";+ return `${base}/api/jobs/${jobId}/stream`;+}diff --git a/packages/web/src/lib/api/pages.ts b/packages/web/src/lib/api/pages.tsnew file mode 100644index 000000000..0d305e57f--- /dev/null+++ b/packages/web/src/lib/api/pages.ts@@ -0,0 +1,49 @@+import { apiGet, apiPost } from "./client";+import type { PageResponse, PageVersionResponse } from "./types";++export async function listPages(+ repoId: string,+ opts?: { page_type?: string; sort_by?: string; order?: string; limit?: number; offset?: number },+): Promise<PageResponse[]> {+ return apiGet<PageResponse[]>("/api/pages", { repo_id: repoId, ...opts });+}++/** Fetch all pages for a repo, auto-paginating through the 500-item backend limit. */+export async function listAllPages(+ repoId: string,+ opts?: { page_type?: string; sort_by?: string; order?: string },+): Promise<PageResponse[]> {+ const PAGE_SIZE = 500;+ const all: PageResponse[] = [];+ let offset = 0;++ while (true) {+ const batch = await listPages(repoId, { ...opts, limit: PAGE_SIZE, offset });+ all.push(...batch);+ if (batch.length < PAGE_SIZE) break;+ offset += PAGE_SIZE;+ }++ return all;+}++/** Get page by its ID using the query-param endpoint (avoids path conflicts) */+export async function getPageById(pageId: string): Promise<PageResponse> {+ return apiGet<PageResponse>("/api/pages/lookup", { page_id: pageId });+}++/** Get page versions by ID */+export async function getPageVersions(+ pageId: string,+ limit = 50,+): Promise<PageVersionResponse[]> {+ return apiGet<PageVersionResponse[]>("/api/pages/lookup/versions", {+ page_id: pageId,+ limit,+ });+}++/** Force-regenerate a page by ID */+export async function regeneratePage(pageId: string): Promise<{ job_id: string }> {+ return apiPost<{ job_id: string }>(`/api/pages/lookup/regenerate?page_id=${encodeURIComponent(pageId)}`);+}diff --git a/packages/web/src/lib/api/repos.ts b/packages/web/src/lib/api/repos.tsnew file mode 100644index 000000000..d9b8b047e--- /dev/null+++ b/packages/web/src/lib/api/repos.ts@@ -0,0 +1,30 @@+import { apiGet, apiPost, apiPatch } from "./client";+import type { RepoCreate, RepoUpdate, RepoResponse, JobResponse, RepoStatsResponse } from "./types";++export async function listRepos(): Promise<RepoResponse[]> {+ return apiGet<RepoResponse[]>("/api/repos");+}++export async function getRepo(repoId: string): Promise<RepoResponse> {+ return apiGet<RepoResponse>(`/api/repos/${repoId}`);+}++export async function createRepo(data: RepoCreate): Promise<RepoResponse> {+ return apiPost<RepoResponse>("/api/repos", data);+}++export async function updateRepo(repoId: string, data: RepoUpdate): Promise<RepoResponse> {+ return apiPatch<RepoResponse>(`/api/repos/${repoId}`, data);+}++export async function syncRepo(repoId: string): Promise<JobResponse> {+ return apiPost<JobResponse>(`/api/repos/${repoId}/sync`);+}++export async function fullResyncRepo(repoId: string): Promise<JobResponse> {+ return apiPost<JobResponse>(`/api/repos/${repoId}/full-resync`);+}++export async function getRepoStats(repoId: string): Promise<RepoStatsResponse> {+ return apiGet<RepoStatsResponse>(`/api/repos/${repoId}/stats`);+}diff --git a/packages/web/src/lib/api/search.ts b/packages/web/src/lib/api/search.tsnew file mode 100644index 000000000..2d3b62204--- /dev/null+++ b/packages/web/src/lib/api/search.ts@@ -0,0 +1,13 @@+import { apiGet } from "./client";+import type { SearchResultResponse } from "./types";++export async function search(+ query: string,+ opts?: { search_type?: "semantic" | "fulltext"; limit?: number },+): Promise<SearchResultResponse[]> {+ return apiGet<SearchResultResponse[]>("/api/search", {+ query,+ search_type: opts?.search_type ?? "semantic",+ limit: opts?.limit ?? 10,+ });+}diff --git a/packages/web/src/lib/api/symbols.ts b/packages/web/src/lib/api/symbols.tsnew file mode 100644index 000000000..cae363981--- /dev/null+++ b/packages/web/src/lib/api/symbols.ts@@ -0,0 +1,29 @@+import { apiGet } from "./client";+import type { SymbolResponse } from "./types";++export interface SymbolListParams {+ repo_id: string;+ q?: string;+ kind?: string;+ language?: string;+ limit?: number;+ offset?: number;+}++export async function listSymbols(params: SymbolListParams): Promise<SymbolResponse[]> {+ const p: Record<string, string | number | boolean | undefined> = { ...params };+ return apiGet<SymbolResponse[]>("/api/symbols", p);+}++export async function lookupSymbolByName(+ name: string,+ repoId: string,+): Promise<SymbolResponse[]> {+ return apiGet<SymbolResponse[]>(`/api/symbols/by-name/${encodeURIComponent(name)}`, {+ repo_id: repoId,+ });+}++export async function getSymbolById(symbolDbId: string): Promise<SymbolResponse> {+ return apiGet<SymbolResponse>(`/api/symbols/${encodeURIComponent(symbolDbId)}`);+}diff --git a/packages/web/src/lib/config.ts b/packages/web/src/lib/config.tsnew file mode 100644index 000000000..9f10936e7--- /dev/null+++ b/packages/web/src/lib/config.ts@@ -0,0 +1,44 @@+/**+ * Settings persisted in localStorage.+ * Keys are prefixed with "repowise_".+ * All helpers are safe to call in SSR — they return defaults when window is undefined.+ */++const KEYS = {+ apiKey: "repowise_api_key",+ apiUrl: "repowise_api_url",+ provider: "repowise_default_provider",+ model: "repowise_default_model",+ embedder: "repowise_embedder",+} as const;++function read(key: string): string {+ if (typeof window === "undefined") return "";+ return localStorage.getItem(key) ?? "";+}++function write(key: string, value: string): void {+ if (typeof window === "undefined") return;+ if (value) {+ localStorage.setItem(key, value);+ } else {+ localStorage.removeItem(key);+ }+}++export const config = {+ getApiKey: () => read(KEYS.apiKey),+ setApiKey: (v: string) => write(KEYS.apiKey, v),++ getApiUrl: () => read(KEYS.apiUrl),+ setApiUrl: (v: string) => write(KEYS.apiUrl, v),++ getProvider: () => read(KEYS.provider) || "litellm",+ setProvider: (v: string) => write(KEYS.provider, v),++ getModel: () => read(KEYS.model),+ setModel: (v: string) => write(KEYS.model, v),++ getEmbedder: () => read(KEYS.embedder) || "mock",+ setEmbedder: (v: string) => write(KEYS.embedder, v),+};diff --git a/packages/web/src/lib/hooks/use-debounce.ts b/packages/web/src/lib/hooks/use-debounce.tsnew file mode 100644index 000000000..16c4f0de2--- /dev/null+++ b/packages/web/src/lib/hooks/use-debounce.ts@@ -0,0 +1,12 @@+"use client";++import { useEffect, useState } from "react";++export function useDebounce<T>(value: T, delay: number): T {+ const [debounced, setDebounced] = useState(value);+ useEffect(() => {+ const timer = setTimeout(() => setDebounced(value), delay);+ return () => clearTimeout(timer);+ }, [value, delay]);+ return debounced;+}diff --git a/packages/web/src/lib/hooks/use-graph.ts b/packages/web/src/lib/hooks/use-graph.tsnew file mode 100644index 000000000..ac1b8232a--- /dev/null+++ b/packages/web/src/lib/hooks/use-graph.ts@@ -0,0 +1,74 @@+"use client";++import useSWR from "swr";+import {+ getArchitectureGraph,+ getDeadCodeGraph,+ getEgoGraph,+ getGraph,+ getHotFilesGraph,+ getModuleGraph,+} from "@/lib/api/graph";+import type {+ DeadCodeGraphResponse,+ EgoGraphResponse,+ GraphExportResponse,+ HotFilesGraphResponse,+ ModuleGraphResponse,+} from "@/lib/api/types";++const SWR_OPTS = { revalidateOnFocus: false, revalidateOnReconnect: false };++export function useGraph(repoId: string | null) {+ const { data, error, isLoading } = useSWR<GraphExportResponse>(+ repoId ? `graph:${repoId}` : null,+ () => getGraph(repoId!),+ SWR_OPTS,+ );+ return { graph: data, error, isLoading };+}++export function useModuleGraph(repoId: string | null) {+ const { data, error, isLoading } = useSWR<ModuleGraphResponse>(+ repoId ? `module-graph:${repoId}` : null,+ () => getModuleGraph(repoId!),+ SWR_OPTS,+ );+ return { graph: data, error, isLoading };+}++export function useEgoGraph(repoId: string | null, nodeId: string | null, hops = 2) {+ const { data, error, isLoading } = useSWR<EgoGraphResponse>(+ repoId && nodeId ? `ego-graph:${repoId}:${nodeId}:${hops}` : null,+ () => getEgoGraph(repoId!, nodeId!, hops),+ SWR_OPTS,+ );+ return { graph: data, error, isLoading };+}++export function useArchitectureGraph(repoId: string | null) {+ const { data, error, isLoading } = useSWR<GraphExportResponse>(+ repoId ? `arch-graph:${repoId}` : null,+ () => getArchitectureGraph(repoId!),+ SWR_OPTS,+ );+ return { graph: data, error, isLoading };+}++export function useDeadCodeGraph(repoId: string | null) {+ const { data, error, isLoading } = useSWR<DeadCodeGraphResponse>(+ repoId ? `dead-graph:${repoId}` : null,+ () => getDeadCodeGraph(repoId!),+ SWR_OPTS,+ );+ return { graph: data, error, isLoading };+}++export function useHotFilesGraph(repoId: string | null, days = 30, limit = 25) {+ const { data, error, isLoading } = useSWR<HotFilesGraphResponse>(+ repoId ? `hot-graph:${repoId}:${days}:${limit}` : null,+ () => getHotFilesGraph(repoId!, days, limit),+ SWR_OPTS,+ );+ return { graph: data, error, isLoading };+}diff --git a/packages/web/src/lib/hooks/use-job.ts b/packages/web/src/lib/hooks/use-job.tsnew file mode 100644index 000000000..dedc38868--- /dev/null+++ b/packages/web/src/lib/hooks/use-job.ts@@ -0,0 +1,34 @@+"use client";++import useSWR from "swr";+import { getJob, getJobStreamUrl } from "@/lib/api/jobs";+import { useSSE } from "./use-sse";+import type { JobResponse, JobProgressEvent } from "@/lib/api/types";++/**+ * Combines polling (SWR) for job metadata with SSE for live progress events.+ * - When the job is running, SSE is active and progress events update in real-time.+ * - When done/failed, SSE closes and SWR has the final state.+ */+export function useJob(jobId: string | null) {+ const { data: job, mutate } = useSWR<JobResponse>(+ jobId ? `/api/jobs/${jobId}` : null,+ jobId ? () => getJob(jobId) : null,+ {+ refreshInterval: (j) =>+ j?.status === "running" || j?.status === "pending" ? 5000 : 0,+ },+ );++ const isActive = job?.status === "running" || job?.status === "pending";+ const streamUrl = jobId && isActive ? getJobStreamUrl(jobId) : null;++ const sse = useSSE<JobProgressEvent>(streamUrl, { enabled: !!streamUrl });++ // When SSE marks done, trigger a final SWR revalidation+ if (sse.isDone && isActive) {+ mutate();+ }++ return { job, sse, isActive };+}diff --git a/packages/web/src/lib/hooks/use-page.ts b/packages/web/src/lib/hooks/use-page.tsnew file mode 100644index 000000000..369b65c5e--- /dev/null+++ b/packages/web/src/lib/hooks/use-page.ts@@ -0,0 +1,23 @@+"use client";++import useSWR from "swr";+import { getPageById, getPageVersions } from "@/lib/api/pages";+import type { PageResponse, PageVersionResponse } from "@/lib/api/types";++export function usePage(pageId: string | null) {+ const { data, error, isLoading, mutate } = useSWR<PageResponse>(+ pageId ? `page:${pageId}` : null,+ () => getPageById(pageId!),+ { revalidateOnFocus: false },+ );+ return { page: data, error, isLoading, mutate };+}++export function usePageVersions(pageId: string | null) {+ const { data, error, isLoading } = useSWR<PageVersionResponse[]>(+ pageId ? `page:${pageId}:versions` : null,+ () => getPageVersions(pageId!),+ { revalidateOnFocus: false },+ );+ return { versions: data ?? [], error, isLoading };+}diff --git a/packages/web/src/lib/hooks/use-pages.ts b/packages/web/src/lib/hooks/use-pages.tsnew file mode 100644index 000000000..8937afa4d--- /dev/null+++ b/packages/web/src/lib/hooks/use-pages.ts@@ -0,0 +1,14 @@+"use client";++import useSWR from "swr";+import { listAllPages } from "@/lib/api/pages";+import type { PageResponse } from "@/lib/api/types";++export function usePages(repoId: string | null, opts?: { page_type?: string }) {+ const { data, error, isLoading, mutate } = useSWR<PageResponse[]>(+ repoId ? `pages:${repoId}:${opts?.page_type ?? "all"}` : null,+ () => listAllPages(repoId!, { page_type: opts?.page_type }),+ { revalidateOnFocus: false },+ );+ return { pages: data ?? [], error, isLoading, mutate };+}diff --git a/packages/web/src/lib/hooks/use-repo.ts b/packages/web/src/lib/hooks/use-repo.tsnew file mode 100644index 000000000..e7f6e36f0--- /dev/null+++ b/packages/web/src/lib/hooks/use-repo.ts@@ -0,0 +1,23 @@+"use client";++import useSWR from "swr";+import { listRepos, getRepo } from "@/lib/api/repos";+import type { RepoResponse } from "@/lib/api/types";++export function useRepos() {+ const { data, error, isLoading, mutate } = useSWR<RepoResponse[]>(+ "repos",+ () => listRepos(),+ { refreshInterval: 30_000 },+ );+ return { repos: data ?? [], error, isLoading, mutate };+}++export function useRepo(repoId: string | null) {+ const { data, error, isLoading, mutate } = useSWR<RepoResponse>(+ repoId ? `repo:${repoId}` : null,+ () => getRepo(repoId!),+ { refreshInterval: 30_000 },+ );+ return { repo: data, error, isLoading, mutate };+}diff --git a/packages/web/src/lib/hooks/use-search.ts b/packages/web/src/lib/hooks/use-search.tsnew file mode 100644index 000000000..a3b81ed4d--- /dev/null+++ b/packages/web/src/lib/hooks/use-search.ts@@ -0,0 +1,25 @@+"use client";++import useSWR from "swr";+import { useDebounce } from "./use-debounce";+import { search } from "@/lib/api/search";+import type { SearchResultResponse } from "@/lib/api/types";++export function useSearch(+ query: string,+ opts?: { search_type?: "semantic" | "fulltext"; limit?: number; debounce?: number },+) {+ const debounced = useDebounce(query, opts?.debounce ?? 300);+ const key = debounced.trim().length >= 2 ? `search:${debounced}:${opts?.search_type}` : null;+ const { data, error, isLoading } = useSWR<SearchResultResponse[]>(+ key,+ () => search(debounced, { search_type: opts?.search_type, limit: opts?.limit }),+ { revalidateOnFocus: false },+ );+ return {+ results: data ?? [],+ error,+ isLoading: isLoading && !!key,+ isTyping: query !== debounced,+ };+}diff --git a/packages/web/src/lib/hooks/use-sse.ts b/packages/web/src/lib/hooks/use-sse.tsnew file mode 100644index 000000000..aa22ceff0--- /dev/null+++ b/packages/web/src/lib/hooks/use-sse.ts@@ -0,0 +1,119 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";++export interface SSEState<T> {+ data: T | null;+ error: Error | null;+ isConnected: boolean;+ isDone: boolean;+}++/**+ * Generic Server-Sent Events hook.+ * Connects to the given URL when enabled=true.+ * Parses events with format: "event: <name>\ndata: <json>\n\n"+ */+export function useSSE<T>(+ url: string | null,+ opts?: { enabled?: boolean; maxRetries?: number },+): SSEState<T> & { close: () => void } {+ const [state, setState] = useState<SSEState<T>>({+ data: null,+ error: null,+ isConnected: false,+ isDone: false,+ });+ const esRef = useRef<EventSource | null>(null);+ const retriesRef = useRef(0);+ const maxRetries = opts?.maxRetries ?? 3;+ const enabled = opts?.enabled !== false;++ const close = useCallback(() => {+ esRef.current?.close();+ esRef.current = null;+ setState((s) => ({ ...s, isConnected: false }));+ }, []);++ useEffect(() => {+ if (!url || !enabled) return;++ retriesRef.current = 0;++ function connect() {+ const es = new EventSource(url as string);+ esRef.current = es;++ es.onopen = () => {+ setState((s) => ({ ...s, isConnected: true, error: null }));+ retriesRef.current = 0;+ };++ es.onmessage = (event) => {+ try {+ const parsed = JSON.parse(event.data) as T;+ setState((s) => ({ ...s, data: parsed }));+ } catch {+ // non-JSON message, ignore+ }+ };++ // Named event handlers for "progress", "done", "error"+ es.addEventListener("progress", (e) => {+ try {+ setState((s) => ({ ...s, data: JSON.parse((e as MessageEvent).data) as T }));+ } catch { /* ignore */ }+ });++ es.addEventListener("done", (e) => {+ try {+ setState((s) => ({+ ...s,+ data: JSON.parse((e as MessageEvent).data) as T,+ isDone: true,+ isConnected: false,+ }));+ } catch { /* ignore */ }+ es.close();+ });++ es.addEventListener("error", (e) => {+ try {+ const parsed = JSON.parse((e as MessageEvent).data) as { error: string };+ setState((s) => ({+ ...s,+ error: new Error(parsed.error),+ isConnected: false,+ isDone: true,+ }));+ } catch { /* ignore */ }+ es.close();+ });++ es.onerror = () => {+ es.close();+ esRef.current = null;+ setState((s) => ({ ...s, isConnected: false }));+ if (retriesRef.current < maxRetries) {+ retriesRef.current++;+ const delay = Math.pow(2, retriesRef.current) * 1000;+ setTimeout(connect, delay);+ } else {+ setState((s) => ({+ ...s,+ error: new Error("SSE connection failed after max retries"),+ }));+ }+ };+ }++ connect();++ return () => {+ esRef.current?.close();+ esRef.current = null;+ };+ }, [url, enabled, maxRetries]);++ return { ...state, close };+}diff --git a/packages/web/src/lib/utils/cn.ts b/packages/web/src/lib/utils/cn.tsnew file mode 100644index 000000000..365058ceb--- /dev/null+++ b/packages/web/src/lib/utils/cn.ts@@ -0,0 +1,6 @@+import { type ClassValue, clsx } from "clsx";+import { twMerge } from "tailwind-merge";++export function cn(...inputs: ClassValue[]) {+ return twMerge(clsx(inputs));+}diff --git a/packages/web/src/lib/utils/confidence.ts b/packages/web/src/lib/utils/confidence.tsnew file mode 100644index 000000000..ab312d23a--- /dev/null+++ b/packages/web/src/lib/utils/confidence.ts@@ -0,0 +1,96 @@+/**+ * Helpers for the confidence score system.+ * Confidence: 0.0 – 1.0 float.+ * Freshness: "fresh" | "stale" | "outdated"+ */++export type FreshnessStatus = "fresh" | "stale" | "outdated";++export function scoreToStatus(score: number): FreshnessStatus {+ if (score >= 0.8) return "fresh";+ if (score >= 0.6) return "stale";+ return "outdated";+}++/** CSS color variable for a given freshness status */+export function statusColor(status: FreshnessStatus): string {+ switch (status) {+ case "fresh":+ return "var(--color-confidence-fresh)";+ case "stale":+ return "var(--color-confidence-stale)";+ case "outdated":+ return "var(--color-confidence-outdated)";+ }+}++/** Tailwind text color class for a given freshness status */+export function statusTextClass(status: FreshnessStatus): string {+ switch (status) {+ case "fresh":+ return "text-green-500";+ case "stale":+ return "text-yellow-500";+ case "outdated":+ return "text-red-500";+ }+}++/** Tailwind bg + text badge classes for a given freshness status */+export function statusBadgeClasses(status: FreshnessStatus): string {+ switch (status) {+ case "fresh":+ return "bg-green-500/10 text-green-500 border-green-500/20";+ case "stale":+ return "bg-yellow-500/10 text-yellow-500 border-yellow-500/20";+ case "outdated":+ return "bg-red-500/10 text-red-500 border-red-500/20";+ }+}++/** Human-readable label for freshness */+export function statusLabel(status: FreshnessStatus): string {+ switch (status) {+ case "fresh":+ return "Fresh";+ case "stale":+ return "Stale";+ case "outdated":+ return "Outdated";+ }+}++/** Color hex for a graph language node */+export const LANGUAGE_COLORS: Record<string, string> = {+ python: "#3776AB",+ typescript: "#3178C6",+ javascript: "#3178C6",+ go: "#00ADD8",+ rust: "#DEA584",+ java: "#ED8B00",+ cpp: "#00599C",+ "c++": "#00599C",+ c: "#00599C",+ config: "#6B7280",+ yaml: "#6B7280",+ dockerfile: "#6B7280",+ other: "#8B5CF6",+};++export function languageColor(lang: string): string {+ return LANGUAGE_COLORS[lang.toLowerCase()] ?? LANGUAGE_COLORS.other;+}++/** Color hex for a graph edge type */+export const EDGE_COLORS: Record<string, string> = {+ imports: "#5B9CF6",+ calls: "#22c55e",+ inherits: "#a855f7",+ implements: "#ec4899",+ co_change: "#8b5cf6",+ co_changes: "#8b5cf6",+};++export function edgeColor(edgeType: string): string {+ return EDGE_COLORS[edgeType.toLowerCase()] ?? "#5B9CF6";+}diff --git a/packages/web/src/lib/utils/format.ts b/packages/web/src/lib/utils/format.tsnew file mode 100644index 000000000..75daa757e--- /dev/null+++ b/packages/web/src/lib/utils/format.ts@@ -0,0 +1,97 @@+/**+ * Number, date, token, and other formatters for repowise UI.+ */++/** Format a number with commas: 1234567 → "1,234,567" */+export function formatNumber(n: number): string {+ return new Intl.NumberFormat().format(n);+}++/** Format token counts: 4200000 → "4.2M", 980000 → "980K", 1234 → "1,234" */+export function formatTokens(n: number): string {+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;+ if (n >= 1_000) return `${(n / 1_000).toFixed(0)}K`;+ return formatNumber(n);+}++/** Format USD cost: 0.004 → "$0.00", 4.2 → "$4.20", 18.6 → "$18.60" */+export function formatCost(usd: number): string {+ return new Intl.NumberFormat("en-US", {+ style: "currency",+ currency: "USD",+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ }).format(usd);+}++/** Format a datetime to a relative string: "2h ago", "3d ago", "just now" */+export function formatRelativeTime(date: string | Date): string {+ const d = typeof date === "string" ? new Date(date) : date;+ const now = Date.now();+ const diff = now - d.getTime();+ const seconds = Math.floor(diff / 1000);+ const minutes = Math.floor(seconds / 60);+ const hours = Math.floor(minutes / 60);+ const days = Math.floor(hours / 24);+ const weeks = Math.floor(days / 7);+ const months = Math.floor(days / 30);++ if (seconds < 10) return "just now";+ if (seconds < 60) return `${seconds}s ago`;+ if (minutes < 60) return `${minutes}m ago`;+ if (hours < 24) return `${hours}h ago`;+ if (days < 7) return `${days}d ago`;+ if (weeks < 5) return `${weeks}w ago`;+ if (months < 12) return `${months}mo ago`;+ return `${Math.floor(months / 12)}y ago`;+}++/** Format a datetime to an absolute string: "Mar 19, 2026" */+export function formatDate(date: string | Date): string {+ const d = typeof date === "string" ? new Date(date) : date;+ return new Intl.DateTimeFormat("en-US", {+ month: "short",+ day: "numeric",+ year: "numeric",+ }).format(d);+}++/** Format a datetime to full: "Mar 19, 2026 at 10:30 AM" */+export function formatDateTime(date: string | Date): string {+ const d = typeof date === "string" ? new Date(date) : date;+ return new Intl.DateTimeFormat("en-US", {+ month: "short",+ day: "numeric",+ year: "numeric",+ hour: "numeric",+ minute: "2-digit",+ }).format(d);+}++/** Format LOC counts: 50000 → "50K", 1234 → "1.2K" */+export function formatLOC(n: number): string {+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;+ if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;+ return String(n);+}++/** Truncate a file path to fit in constrained UI: src/very/long/path/file.py → …/path/file.py */+export function truncatePath(path: string, maxChars = 40): string {+ if (path.length <= maxChars) return path;+ const parts = path.split("/");+ if (parts.length <= 2) return `…${path.slice(-(maxChars - 1))}`;+ // Keep the filename + one parent+ const tail = parts.slice(-2).join("/");+ return `…/${tail}`;+}++/** Format a confidence score as a percentage string: 0.87 → "87%" */+export function formatConfidence(score: number): string {+ return `${Math.round(score * 100)}%`;+}++/** Format a job progress: 340 / 847 → "340 / 847 (40%)" */+export function formatProgress(done: number, total: number): string {+ const pct = total > 0 ? Math.round((done / total) * 100) : 0;+ return `${formatNumber(done)} / ${formatNumber(total)} (${pct}%)`;+}