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
feat: machine-readable interfaces, live range risk scoring, dead-code line spans, shared API client (#642)
Raghav Chamadiya8d48b7194d8a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex ea9250de0..83f28081e 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -84,10 +84,19 @@ jobs:cache-dependency-path: package-lock.json- name: Install dependencies- run: npm ci --workspace packages/web+ run: npm ci- name: Type checkrun: npm run type-check --workspace packages/web- name: Lintrun: npm run lint --workspace packages/web++ - name: Lint shared packages (no framework imports)+ run: npm run lint:shared++ - name: Type check api-client+ run: npm run type-check --workspace @repowise-dev/api-client++ - name: Test api-client+ run: npm run test --workspace @repowise-dev/api-clientdiff --git a/package-lock.json b/package-lock.jsonindex f24b5da20..fbea5e80c 100644--- a/package-lock.json+++ b/package-lock.json@@ -10,6 +10,7 @@"workspaces": ["packages/types","packages/ui",+ "packages/api-client","packages/web"],"engines": {@@ -1293,6 +1294,7 @@"os": ["darwin"],+ "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1315,6 +1317,7 @@"os": ["darwin"],+ "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1337,6 +1340,7 @@"os": ["darwin"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1353,6 +1357,7 @@"os": ["darwin"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1369,6 +1374,7 @@"os": ["linux"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1385,6 +1391,7 @@"os": ["linux"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1401,6 +1408,7 @@"os": ["linux"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1417,6 +1425,7 @@"os": ["linux"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1433,6 +1442,7 @@"os": ["linux"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1449,6 +1459,7 @@"os": ["linux"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1465,6 +1476,7 @@"os": ["linux"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1481,6 +1493,7 @@"os": ["linux"],+ "peer": true,"funding": {"url": "https://opencollective.com/libvips"}@@ -1497,6 +1510,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1519,6 +1533,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1541,6 +1556,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1563,6 +1579,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1585,6 +1602,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1607,6 +1625,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1629,6 +1648,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1651,6 +1671,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1670,6 +1691,7 @@],"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT","optional": true,+ "peer": true,"dependencies": {"@emnapi/runtime": "^1.7.0"},@@ -1692,6 +1714,7 @@"os": ["win32"],+ "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1711,6 +1734,7 @@"os": ["win32"],+ "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -1730,6 +1754,7 @@"os": ["win32"],+ "peer": true,"engines": {"node": "^18.17.0 || ^20.3.0 || >=21.0.0"},@@ -3155,6 +3180,10 @@"url": "https://opencollective.com/immer"}},+ "node_modules/@repowise-dev/api-client": {+ "resolved": "packages/api-client",+ "link": true+ },"node_modules/@repowise-dev/types": {"resolved": "packages/types","link": true@@ -14454,6 +14483,20 @@"url": "https://github.com/sponsors/wooorm"}},+ "packages/api-client": {+ "name": "@repowise-dev/api-client",+ "version": "0.1.0",+ "dependencies": {+ "@repowise-dev/types": "*"+ },+ "devDependencies": {+ "@repowise-dev/ui": "*",+ "@types/react": "^19.0.0",+ "react": "^19.0.0",+ "typescript": "^5.6.0",+ "vitest": "^4.1.5"+ }+ },"packages/types": {"name": "@repowise-dev/types","version": "0.0.1",diff --git a/package.json b/package.jsonindex afdad20fa..8a96ecba9 100644--- a/package.json+++ b/package.json@@ -6,6 +6,7 @@"workspaces": ["packages/types","packages/ui",+ "packages/api-client","packages/web"],"scripts": {@@ -13,7 +14,8 @@"build": "npm run build --workspaces --if-present","lint": "npm run lint --workspaces --if-present","type-check": "npm run type-check --workspaces --if-present",- "test": "npm run test --workspaces --if-present"+ "test": "npm run test --workspaces --if-present",+ "lint:shared": "node scripts/check-shared-imports.mjs"},"engines": {"node": ">=20.0.0"diff --git a/packages/api-client/package.json b/packages/api-client/package.jsonnew file mode 100644index 000000000..ffc3905ed--- /dev/null+++ b/packages/api-client/package.json@@ -0,0 +1,61 @@+{+ "name": "@repowise-dev/api-client",+ "version": "0.1.0",+ "private": true,+ "description": "Framework-free TypeScript client for the repowise REST API, shared by packages/web and downstream consumers.",+ "type": "module",+ "files": ["src"],+ "main": "./src/index.ts",+ "types": "./src/index.ts",+ "exports": {+ ".": "./src/index.ts",+ "./types": "./src/types.ts",+ "./blast-radius": "./src/blast-radius.ts",+ "./c4": "./src/c4.ts",+ "./chat": "./src/chat.ts",+ "./code-health": "./src/code-health.ts",+ "./costs": "./src/costs.ts",+ "./coupling": "./src/coupling.ts",+ "./dead-code": "./src/dead-code.ts",+ "./decisions": "./src/decisions.ts",+ "./external-systems": "./src/external-systems.ts",+ "./files": "./src/files.ts",+ "./git": "./src/git.ts",+ "./graph": "./src/graph.ts",+ "./health": "./src/health.ts",+ "./jobs": "./src/jobs.ts",+ "./knowledge-map": "./src/knowledge-map.ts",+ "./mcp-tools": "./src/mcp-tools.ts",+ "./meta": "./src/meta.ts",+ "./modules": "./src/modules.ts",+ "./overview": "./src/overview.ts",+ "./owners": "./src/owners.ts",+ "./pages": "./src/pages.ts",+ "./providers": "./src/providers.ts",+ "./refactoring": "./src/refactoring.ts",+ "./repos": "./src/repos.ts",+ "./search": "./src/search.ts",+ "./security": "./src/security.ts",+ "./stats": "./src/stats.ts",+ "./symbols": "./src/symbols.ts",+ "./workspace": "./src/workspace.ts"+ },+ "publishConfig": {+ "registry": "https://npm.pkg.github.com",+ "access": "restricted"+ },+ "scripts": {+ "type-check": "tsc --noEmit",+ "test": "vitest run"+ },+ "dependencies": {+ "@repowise-dev/types": "*"+ },+ "devDependencies": {+ "@repowise-dev/ui": "*",+ "@types/react": "^19.0.0",+ "react": "^19.0.0",+ "typescript": "^5.6.0",+ "vitest": "^4.1.5"+ }+}diff --git a/packages/api-client/src/blast-radius.ts b/packages/api-client/src/blast-radius.tsnew file mode 100644index 000000000..32b383b4c--- /dev/null+++ b/packages/api-client/src/blast-radius.ts@@ -0,0 +1,24 @@+import { apiPost } from "./client";+import type {+ BlastRadiusRequest,+ BlastRadiusResponse,+} from "@repowise-dev/types/blast-radius";++export type {+ DirectRiskEntry,+ TransitiveEntry,+ CochangeWarning,+ ReviewerEntry,+ BlastRadiusResponse,+ BlastRadiusRequest,+} from "@repowise-dev/types/blast-radius";++export async function analyzeBlastRadius(+ repoId: string,+ body: BlastRadiusRequest,+): Promise<BlastRadiusResponse> {+ return apiPost<BlastRadiusResponse>(+ `/api/repos/${repoId}/blast-radius`,+ body,+ );+}diff --git a/packages/api-client/src/c4.ts b/packages/api-client/src/c4.tsnew file mode 100644index 000000000..f2e9bbb70--- /dev/null+++ b/packages/api-client/src/c4.ts@@ -0,0 +1,48 @@+/**+ * REST client for the C4 endpoints.+ * Backend: packages/server/src/repowise/server/routers/c4.py+ */++import { apiGet, BASE_URL, buildHeaders, doFetch } from "./client";+import type { C4L1, C4L2, C4L3, ArchitectureView } from "@repowise-dev/ui/c4";++export async function getC4L1(repoId: string): Promise<C4L1> {+ return apiGet<C4L1>(`/api/graph/${repoId}/c4/l1`);+}++export async function getC4L2(repoId: string): Promise<C4L2> {+ return apiGet<C4L2>(`/api/graph/${repoId}/c4/l2`);+}++export async function getC4L3(repoId: string, containerId: string): Promise<C4L3> {+ return apiGet<C4L3>(`/api/graph/${repoId}/c4/l3`, { container_id: containerId });+}++/**+ * Fetch the Mermaid C4 source for the current view. Backend is the source+ * of truth so the exported diagram matches what the API serves.+ */+export async function getC4Mermaid(+ repoId: string,+ level: 1 | 2 | 3,+ containerId?: string | null,+): Promise<string> {+ const params = new URLSearchParams({ level: String(level) });+ if (level === 3 && containerId) params.set("container_id", containerId);+ const res = await doFetch(`${BASE_URL}/api/graph/${repoId}/c4/mermaid?${params.toString()}`, {+ headers: buildHeaders(),+ });+ if (!res.ok) {+ throw new Error(`Failed to fetch Mermaid C4 source (${res.status})`);+ }+ return res.text();+}++export async function getArchitectureView(+ repoId: string,+ includeSymbols: boolean = false,+): Promise<ArchitectureView> {+ return apiGet<ArchitectureView>(`/api/graph/${repoId}/architecture-view`, {+ include_symbols: includeSymbols,+ });+}diff --git a/packages/api-client/src/chat.ts b/packages/api-client/src/chat.tsnew file mode 100644index 000000000..2eb9def7e--- /dev/null+++ b/packages/api-client/src/chat.ts@@ -0,0 +1,73 @@+/**+ * Chat API module — conversation management and SSE message streaming.+ */++import { apiGet, apiDelete, BASE_URL, buildHeaders } from "./client";+import type { ConversationResponse, ChatMessageResponse } from "./types";++export async function listConversations(+ repoId: string,+): Promise<ConversationResponse[]> {+ return apiGet<ConversationResponse[]>(+ `/api/repos/${repoId}/chat/conversations`,+ );+}++export async function getConversation(+ repoId: string,+ conversationId: string,+): Promise<{+ conversation: ConversationResponse;+ messages: ChatMessageResponse[];+}> {+ return apiGet(`/api/repos/${repoId}/chat/conversations/${conversationId}`);+}++export async function deleteConversation(+ repoId: string,+ conversationId: string,+): Promise<void> {+ await apiDelete(`/api/repos/${repoId}/chat/conversations/${conversationId}`);+}++/**+ * POST a chat message and return the raw Response for SSE streaming.+ * The caller reads response.body as a ReadableStream.+ */+export async function postChatMessage(+ repoId: string,+ opts: {+ message: string;+ conversationId?: string;+ provider?: string;+ model?: string;+ },+): Promise<Response> {+ const url = `${BASE_URL}/api/repos/${repoId}/chat/messages`;+ const headers = buildHeaders();+ headers.set("Accept", "text/event-stream");++ const res = await fetch(url, {+ method: "POST",+ headers,+ body: JSON.stringify({+ message: opts.message,+ conversation_id: opts.conversationId ?? null,+ provider: opts.provider ?? null,+ model: opts.model ?? null,+ }),+ });++ if (!res.ok) {+ let detail = res.statusText;+ try {+ const json = (await res.json()) as { detail?: string };+ detail = json.detail ?? detail;+ } catch {+ // not JSON+ }+ throw new Error(`Chat error ${res.status}: ${detail}`);+ }++ return res;+}diff --git a/packages/api-client/src/client.ts b/packages/api-client/src/client.tsnew file mode 100644index 000000000..d2fc76317--- /dev/null+++ b/packages/api-client/src/client.ts@@ -0,0 +1,170 @@+/**+ * Base fetch wrapper for the repowise REST API. Framework-free: the base URL+ * and auth token are not read from any env var here; a host app calls+ * `configureApiClient` once, before making requests, to supply them.+ */++import type { ApiError } from "./types";++/**+ * `token` may be a literal string, or a resolver called fresh on every+ * request (e.g. to read a value that can change without a page reload, like+ * a token stored in localStorage).+ */+export interface ApiClientConfig {+ baseUrl: string;+ token?: string | null | (() => string | null);+ fetch?: typeof fetch;+}++let config: ApiClientConfig = { baseUrl: "" };++/** Sets the base URL / token / fetch implementation used by every request. */+export function configureApiClient(next: ApiClientConfig): void {+ config = next;+ BASE_URL = next.baseUrl;+}++export function getApiClientConfig(): ApiClientConfig {+ return config;+}++// Live binding: reflects whatever `configureApiClient` last set. Kept as a+// direct export (rather than a getter function) so existing call sites that+// read `BASE_URL` as a value keep working unchanged.+export let BASE_URL = "";++function resolveToken(): string | null {+ const { token } = config;+ if (typeof token === "function") return token();+ return token ?? null;+}++function buildHeaders(extra?: Record<string, string>): Headers {+ const headers = new Headers({+ "Content-Type": "application/json",+ ...extra,+ });+ const token = resolveToken();+ if (token) {+ headers.set("Authorization", `Bearer ${token}`);+ }+ return headers;+}++export class ApiClientError extends Error {+ constructor(+ public readonly status: number,+ public readonly detail: string,+ ) {+ super(`API error ${status}: ${detail}`);+ this.name = "ApiClientError";+ }+}++async function handleResponse<T>(res: Response): Promise<T> {+ if (!res.ok) {+ let detail = res.statusText;+ try {+ const json = (await res.json()) as ApiError;+ detail = json.detail ?? detail;+ } catch {+ // response body is not JSON+ }+ throw new ApiClientError(res.status, detail);+ }+ return res.json() as Promise<T>;+}++export function doFetch(url: string, init: RequestInit): Promise<Response> {+ return (config.fetch ?? fetch)(url, init);+}++export async function apiGet<T>(+ path: string,+ params?: Record<string, string | number | boolean | undefined>,+ fetchOptions?: RequestInit,+): Promise<T> {+ const url = new URL(`${BASE_URL}${path}`, typeof window !== "undefined" ? window.location.href : "http://localhost");+ if (params) {+ for (const [k, v] of Object.entries(params)) {+ if (v !== undefined && v !== null) {+ url.searchParams.set(k, String(v));+ }+ }+ }+ const res = await doFetch(url.toString(), {+ method: "GET",+ headers: buildHeaders(),+ ...fetchOptions,+ });+ return handleResponse<T>(res);+}++export async function apiPost<T>(+ path: string,+ body?: unknown,+ fetchOptions?: RequestInit,+ params?: Record<string, string | number | boolean | undefined>,+): Promise<T> {+ const url = new URL(`${BASE_URL}${path}`, typeof window !== "undefined" ? window.location.href : "http://localhost");+ if (params) {+ for (const [k, v] of Object.entries(params)) {+ if (v !== undefined && v !== null) {+ url.searchParams.set(k, String(v));+ }+ }+ }+ const res = await doFetch(url.toString(), {+ method: "POST",+ headers: buildHeaders(),+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),+ ...fetchOptions,+ });+ return handleResponse<T>(res);+}++export async function apiPut<T>(+ path: string,+ body?: unknown,+ fetchOptions?: RequestInit,+): Promise<T> {+ const url = `${BASE_URL}${path}`;+ const res = await doFetch(url, {+ method: "PUT",+ headers: buildHeaders(),+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),+ ...fetchOptions,+ });+ return handleResponse<T>(res);+}++export async function apiPatch<T>(+ path: string,+ body?: unknown,+ fetchOptions?: RequestInit,+): Promise<T> {+ const url = `${BASE_URL}${path}`;+ const res = await doFetch(url, {+ method: "PATCH",+ headers: buildHeaders(),+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),+ ...fetchOptions,+ });+ return handleResponse<T>(res);+}++export async function apiDelete<T>(+ path: string,+ fetchOptions?: RequestInit,+): Promise<T> {+ const url = `${BASE_URL}${path}`;+ const res = await doFetch(url, {+ method: "DELETE",+ headers: buildHeaders(),+ ...fetchOptions,+ });+ return handleResponse<T>(res);+}++export { buildHeaders };diff --git a/packages/api-client/src/code-health.ts b/packages/api-client/src/code-health.tsnew file mode 100644index 000000000..2be784473--- /dev/null+++ b/packages/api-client/src/code-health.ts@@ -0,0 +1,133 @@+/**+ * Code-health API client. The response/query *types* now live in the shared+ * `@repowise-dev/types/health` contract (migrated out of this web-local file so+ * the hosted frontend and the bot read the same shapes); this module re-exports+ * them for back-compat and keeps only the fetch functions.+ */+import type {+ ChurnComplexityResponse,+ HealthFilesQuery,+ HealthFilesResponse,+ HealthFinding,+ HealthCoverageResponse,+ HealthFileBreakdownResponse,+ HealthOverviewResponse,+ HealthTrendResponse,+ RefactoringQuery,+ RefactoringTargetsResponse,+} from "@repowise-dev/types/health";+import { apiGet, apiPatch } from "./client";++export type {+ BiomarkerBreakdownRow,+ ChurnComplexityPoint,+ ChurnComplexityResponse,+ CoverageFileRow,+ CoverageSummary,+ DefectAccuracy,+ FileBreakdownCategory,+ FileBreakdownFinding,+ HealthBand,+ HealthCoverageResponse,+ HealthDistribution,+ HealthFileBreakdownResponse,+ HealthFileMetric,+ HealthFilesQuery,+ HealthFilesResponse,+ HealthFinding,+ HealthModuleRow,+ HealthOverviewResponse,+ HealthTrendResponse,+ ModuleCoverageRow,+ RefactoringQuery,+ RefactoringTarget,+ RefactoringTargetsResponse,+} from "@repowise-dev/types/health";++export async function getHealthOverview(+ repoId: string,+ limit = 25,+): Promise<HealthOverviewResponse> {+ return apiGet<HealthOverviewResponse>(+ `/api/repos/${repoId}/health/overview`,+ { limit },+ );+}++export async function listHealthFindings(+ repoId: string,+ opts?: {+ biomarker_type?: string;+ file_path?: string;+ min_severity?: string;+ dimension?: string;+ limit?: number;+ },+): Promise<HealthFinding[]> {+ return apiGet<HealthFinding[]>(`/api/repos/${repoId}/health/findings`, opts);+}++export async function listHealthFiles(+ repoId: string,+ opts?: HealthFilesQuery,+): Promise<HealthFilesResponse> {+ return apiGet<HealthFilesResponse>(+ `/api/repos/${repoId}/health/files`,+ opts as Record<string, string | number | boolean | undefined>,+ );+}++export async function getHealthFileBreakdown(+ repoId: string,+ filePath: string,+): Promise<HealthFileBreakdownResponse> {+ return apiGet<HealthFileBreakdownResponse>(+ `/api/repos/${repoId}/health/files/breakdown`,+ { file_path: filePath },+ );+}++export async function getHealthTrend(repoId: string, limit = 20): Promise<HealthTrendResponse> {+ return apiGet<HealthTrendResponse>(`/api/repos/${repoId}/health/trend`, { limit });+}++export async function updateFindingStatus(+ repoId: string,+ findingId: string,+ status: "open" | "acknowledged" | "resolved" | "false_positive",+): Promise<HealthFinding> {+ return apiPatch<HealthFinding>(+ `/api/repos/${repoId}/health/findings/${findingId}`,+ { status },+ );+}++export async function getHealthCoverage(+ repoId: string,+ opts?: { file_path?: string; limit?: number },+): Promise<HealthCoverageResponse> {+ return apiGet<HealthCoverageResponse>(+ `/api/repos/${repoId}/health/coverage`,+ opts,+ );+}++export async function getRefactoringTargets(+ repoId: string,+ opts?: RefactoringQuery,+): Promise<RefactoringTargetsResponse> {+ return apiGet<RefactoringTargetsResponse>(+ `/api/repos/${repoId}/health/refactoring-targets`,+ opts as Record<string, string | number | boolean | undefined>,+ );+}++export async function getChurnComplexity(+ repoId: string,+ opts?: { limit?: number },+): Promise<ChurnComplexityResponse> {+ return apiGet<ChurnComplexityResponse>(+ `/api/repos/${repoId}/health/churn-complexity`,+ opts,+ );+}diff --git a/packages/api-client/src/costs.ts b/packages/api-client/src/costs.tsnew file mode 100644index 000000000..b301bc874--- /dev/null+++ b/packages/api-client/src/costs.ts@@ -0,0 +1,94 @@+import { apiGet } from "./client";++// ---------------------------------------------------------------------------+// Types+// ---------------------------------------------------------------------------++export interface CostGroup {+ group: string;+ calls: number;+ input_tokens: number;+ output_tokens: number;+ cost_usd: number;+}++export interface CostSummary {+ total_cost_usd: number;+ total_calls: number;+ total_input_tokens: number;+ total_output_tokens: number;+ since: string | null;+}++export interface DistillSavingsGroup {+ group: string;+ events: number;+ raw_tokens: number;+ distilled_tokens: number;+ saved_tokens: number;+}++export interface McpDropGroup {+ tool: string;+ events: number;+ tokens: number;+ /** "counterfactual" (answer replaced raw exploration) or "truncation" (budget drop). */+ kind?: string;+}++export interface DistillSavings {+ available: boolean;+ events: number;+ raw_tokens: number;+ distilled_tokens: number;+ saved_tokens: number;+ estimated_usd_saved: number;+ pricing_model: string;+ /** How the pricing model was resolved (Phase 1 model-aware pricing). */+ pricing_agent: string;+ pricing_source: string;+ per_filter: DistillSavingsGroup[];+ per_day: DistillSavingsGroup[];+ /** Unified MCP savings — counterfactual ledger + truncation drops. */+ mcp_events: number;+ mcp_tokens: number;+ /** Count of counterfactual MCP queries answered ("N MCP queries answered"). */+ mcp_queries: number;+ mcp_per_tool: McpDropGroup[];+ /** Raw (non-distilled) agent commands a filter would have caught. */+ missed_events: number;+ missed_tokens_est: number;+ missed_window_days: number;+}++// ---------------------------------------------------------------------------+// API functions+// ---------------------------------------------------------------------------++export async function listCosts(+ repoId: string,+ opts: { since?: string; by?: "operation" | "model" | "day" } = {},+): Promise<CostGroup[]> {+ return apiGet<CostGroup[]>(`/api/repos/${repoId}/costs`, {+ since: opts.since,+ by: opts.by ?? "day",+ });+}++export async function getCostSummary(+ repoId: string,+ since?: string,+): Promise<CostSummary> {+ return apiGet<CostSummary>(`/api/repos/${repoId}/costs/summary`, {+ since,+ });+}++export async function getDistillSavings(+ repoId: string,+ since?: string,+): Promise<DistillSavings> {+ return apiGet<DistillSavings>(`/api/repos/${repoId}/distill-savings`, {+ since,+ });+}diff --git a/packages/api-client/src/coupling.ts b/packages/api-client/src/coupling.tsnew file mode 100644index 000000000..2c6bf1861--- /dev/null+++ b/packages/api-client/src/coupling.ts@@ -0,0 +1,20 @@+/**+ * Change-coupling API client. The response types live in the shared+ * `@repowise-dev/types/coupling` contract; this module re-exports them and+ * keeps only the fetch function.+ */+import type { CouplingGraphResponse } from "@repowise-dev/types/coupling";+import { apiGet } from "./client";++export type {+ CouplingEdge,+ CouplingGraphResponse,+ CouplingNode,+} from "@repowise-dev/types/coupling";++export async function getCoupling(+ repoId: string,+ opts?: { limit?: number },+): Promise<CouplingGraphResponse> {+ return apiGet<CouplingGraphResponse>(`/api/repos/${repoId}/coupling`, opts);+}diff --git a/packages/api-client/src/dead-code.ts b/packages/api-client/src/dead-code.tsnew file mode 100644index 000000000..4990e927d--- /dev/null+++ b/packages/api-client/src/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/api-client/src/decisions.ts b/packages/api-client/src/decisions.tsnew file mode 100644index 000000000..a214969ab--- /dev/null+++ b/packages/api-client/src/decisions.ts@@ -0,0 +1,76 @@+import { apiGet, apiPost, apiPatch } from "./client";+import type {+ DecisionCreate,+ DecisionEvidence,+ DecisionEvidenceResponse,+ DecisionGraph,+ DecisionLineageEntry,+ DecisionLineageResponse,+ 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 getDecisionEvidence(+ repoId: string,+ decisionId: string,+): Promise<DecisionEvidence[]> {+ const res = await apiGet<DecisionEvidenceResponse>(+ `/api/repos/${repoId}/decisions/${decisionId}/evidence`,+ );+ return res.evidence;+}++export async function getDecisionLineage(+ repoId: string,+ decisionId: string,+): Promise<DecisionLineageEntry[]> {+ const res = await apiGet<DecisionLineageResponse>(+ `/api/repos/${repoId}/decisions/${decisionId}/lineage`,+ );+ return res.lineage;+}++export async function getDecisionGraph(repoId: string): Promise<DecisionGraph> {+ return apiGet<DecisionGraph>(`/api/repos/${repoId}/decisions/graph`);+}diff --git a/packages/api-client/src/external-systems.ts b/packages/api-client/src/external-systems.tsnew file mode 100644index 000000000..2adf37d54--- /dev/null+++ b/packages/api-client/src/external-systems.ts@@ -0,0 +1,12 @@+import type { ExternalSystemsRegistry } from "@repowise-dev/types/external-systems";++import { apiGet } from "./client";++/** Full dependency registry (one row per name + manifest, undeduplicated). */+export async function getExternalSystems(+ repoId: string,+): Promise<ExternalSystemsRegistry> {+ return apiGet<ExternalSystemsRegistry>(+ `/api/repos/${repoId}/external-systems`,+ );+}diff --git a/packages/api-client/src/files.ts b/packages/api-client/src/files.tsnew file mode 100644index 000000000..d1e621ed1--- /dev/null+++ b/packages/api-client/src/files.ts@@ -0,0 +1,30 @@+import type { FileDetailResponse, FilesIndexResponse } from "@repowise-dev/types/files";+import { apiGet, BASE_URL, buildHeaders } from "./client";++/** Slim per-file rows for the browsable Files index + treemap. */+export async function getFilesIndex(repoId: string): Promise<FilesIndexResponse> {+ return apiGet<FilesIndexResponse>(`/api/repos/${repoId}/files`);+}++/** Canonical file-detail aggregate for the file entity page. */+export async function getFileDetail(+ repoId: string,+ filePath: string,+): Promise<FileDetailResponse> {+ // Encode each segment but keep the slashes — the server route uses a+ // catch-all path converter.+ const encoded = filePath.split("/").map(encodeURIComponent).join("/");+ return apiGet<FileDetailResponse>(`/api/repos/${repoId}/files/${encoded}`);+}++/** Raw file content from the repo checkout (plain text, not JSON). */+export async function getFileContent(repoId: string, filePath: string): Promise<string> {+ const url = new URL(+ `${BASE_URL}/api/repos/${repoId}/file-content`,+ typeof window !== "undefined" ? window.location.href : "http://localhost",+ );+ url.searchParams.set("file_path", filePath);+ const res = await fetch(url.toString(), { headers: buildHeaders() });+ if (!res.ok) throw new Error(`Failed to fetch file content (${res.status})`);+ return res.text();+}diff --git a/packages/api-client/src/git.ts b/packages/api-client/src/git.tsnew file mode 100644index 000000000..d8430d052--- /dev/null+++ b/packages/api-client/src/git.ts@@ -0,0 +1,160 @@+import { apiGet } from "./client";+import type {+ AgentTrend,+ CommitEvolution,+ CommitStats,+ CommitDetailResponse,+ CommitResponse,+ GitMetadataResponse,+ GitSummaryResponse,+ HotspotResponse,+ OwnershipEntry,+ Paginated,+ ReviewerSuggestionsResponse,+} from "./types";++export async function getGitMetadata(+ repoId: string,+ filePath: string,+): Promise<GitMetadataResponse> {+ return apiGet<GitMetadataResponse>(`/api/repos/${repoId}/git-metadata`, {+ file_path: filePath,+ });+}++/**+ * Paginated hotspot fetch — returns the full envelope so the UI can render+ * "Showing N of M / Load more". New callers should prefer this over+ * {@link getHotspots}, which is kept for back-compat (returns just the+ * items list, but no longer hides the long tail since the server cap is+ * 500 rather than the old 100).+ */+export async function getHotspotsPage(+ repoId: string,+ options: { limit?: number; offset?: number } = {},+): Promise<Paginated<HotspotResponse>> {+ const { limit = 50, offset = 0 } = options;+ return apiGet<Paginated<HotspotResponse>>(`/api/repos/${repoId}/hotspots`, {+ limit,+ offset,+ });+}++/**+ * Back-compat helper — keeps the legacy `(repoId, limit) → list` signature+ * used by widgets that don't (yet) render a "load more" affordance.+ */+export async function getHotspots(+ repoId: string,+ limit = 50,+): Promise<HotspotResponse[]> {+ const page = await getHotspotsPage(repoId, { limit });+ return page.items;+}++export async function getOwnershipPage(+ repoId: string,+ granularity: "file" | "module" = "module",+ options: { limit?: number; offset?: number } = {},+): Promise<Paginated<OwnershipEntry>> {+ const { limit = 500, offset = 0 } = options;+ return apiGet<Paginated<OwnershipEntry>>(`/api/repos/${repoId}/ownership`, {+ granularity,+ limit,+ offset,+ });+}++export async function getOwnership(+ repoId: string,+ granularity: "file" | "module" = "module",+): Promise<OwnershipEntry[]> {+ const page = await getOwnershipPage(repoId, granularity, { limit: 5000 });+ return page.items;+}++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 }>;+ total?: number;+}> {+ return apiGet(`/api/repos/${repoId}/co-changes`, {+ file_path: filePath,+ min_count: minCount,+ });+}++export async function getReviewerSuggestions(+ repoId: string,+ paths: string[],+ limit = 10,+): Promise<ReviewerSuggestionsResponse> {+ // FastAPI repeats `?paths=` per entry; URLSearchParams handles that for+ // us when we hand it tuples.+ const sp = new URLSearchParams();+ for (const p of paths) sp.append("paths", p);+ sp.append("limit", String(limit));+ return apiGet<ReviewerSuggestionsResponse>(+ `/api/repos/${repoId}/reviewer-suggestions?${sp.toString()}`,+ );+}++export async function getGitSummary(+ repoId: string,+ topOwnersLimit?: number,+): Promise<GitSummaryResponse> {+ const params = topOwnersLimit ? { top_owners_limit: topOwnersLimit } : undefined;+ return apiGet<GitSummaryResponse>(`/api/repos/${repoId}/git-summary`, params);+}++/**+ * Paginated per-commit change-risk feed — the review-priority queue. `sort`+ * defaults to `risk` (review-priority order); `date` orders by recency. Each+ * commit carries a repo-relative `risk_percentile` + `review_priority`.+ */+export async function getCommitsPage(+ repoId: string,+ options: {+ sort?: "risk" | "date";+ authorship?: "all" | "agent" | "human";+ limit?: number;+ offset?: number;+ } = {},+): Promise<Paginated<CommitResponse>> {+ const { sort = "risk", authorship = "all", limit = 50, offset = 0 } = options;+ return apiGet<Paginated<CommitResponse>>(`/api/repos/${repoId}/commits`, {+ sort,+ authorship,+ limit,+ offset,+ });+}++/** Monthly agent-vs-human commit volume across the indexed window. */+export async function getAgentTrend(repoId: string): Promise<AgentTrend> {+ return apiGet<AgentTrend>(`/api/repos/${repoId}/commits/agent-trend`);+}++export async function getCommitEvolution(+ repoId: string,+ granularity: "auto" | "month" | "week" = "auto",+): Promise<CommitEvolution> {+ return apiGet<CommitEvolution>(+ `/api/repos/${repoId}/commits/evolution?granularity=${granularity}`,+ );+}++export async function getCommitStats(repoId: string): Promise<CommitStats> {+ return apiGet<CommitStats>(`/api/repos/${repoId}/commits/stats`);+}++export async function getCommit(+ repoId: string,+ sha: string,+): Promise<CommitDetailResponse> {+ return apiGet<CommitDetailResponse>(`/api/repos/${repoId}/commits/${sha}`);+}diff --git a/packages/api-client/src/graph.ts b/packages/api-client/src/graph.tsnew file mode 100644index 000000000..8beac3618--- /dev/null+++ b/packages/api-client/src/graph.ts@@ -0,0 +1,156 @@+import { apiGet } from "./client";+import type {+ ArchitectureGraphResponse,+ CallersCalleesResponse,+ CommunityDetailResponse,+ CommunitySliceResponse,+ CommunitySummaryItem,+ DeadCodeGraphResponse,+ EgoGraphResponse,+ ExecutionFlowsResponse,+ GraphExportResponse,+ GraphMetricsResponse,+ GraphPathResponse,+ HotFilesGraphResponse,+ ModuleGraphResponse,+ NodeSearchResult,+} from "./types";++export async function getGraph(+ repoId: string,+ limit?: number,+): Promise<GraphExportResponse> {+ return apiGet<GraphExportResponse>(+ `/api/graph/${repoId}`,+ limit != null ? { limit } : undefined,+ );+}++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`);+}++/**+ * Community super-node view: one node per detected community, with+ * cross-community edges. Endpoint introduced in Phase A of the graph+ * UX overhaul; rendering surface is incremental and the legacy+ * entry-point view above remains the default until adapter support lands.+ */+export async function getArchitectureCommunityGraph(+ repoId: string,+ minMembers = 2,+): Promise<ArchitectureGraphResponse> {+ return apiGet<ArchitectureGraphResponse>(`/api/graph/${repoId}/architecture`, {+ min_members: minMembers,+ });+}++/**+ * Constellation (radial Knowledge Graph) data source — the community+ * super-graph. Thin alias over {@link getArchitectureCommunityGraph} so the+ * G3 wiring reads cleanly.+ */+export async function getArchitecture(+ repoId: string,+ minMembers = 2,+): Promise<ArchitectureGraphResponse> {+ return getArchitectureCommunityGraph(repoId, minMembers);+}++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 });+}++// ---------------------------------------------------------------------------+// Graph Intelligence+// ---------------------------------------------------------------------------++export async function getCommunities(repoId: string): Promise<CommunitySummaryItem[]> {+ return apiGet<CommunitySummaryItem[]>(`/api/graph/${repoId}/communities`);+}++export async function getCommunityDetail(+ repoId: string,+ communityId: number,+ params?: { include_members?: boolean; member_limit?: number },+): Promise<CommunityDetailResponse> {+ return apiGet<CommunityDetailResponse>(+ `/api/graph/${repoId}/communities/${communityId}`,+ params,+ );+}++/**+ * Constellation blossom slice: a single community's member file nodes, the+ * edges among them, and one-hop boundary stubs (neighbor nodes flagged+ * `is_boundary`) so cross-cluster edges render. Fetched on hub expand.+ */+export async function getCommunitySlice(+ repoId: string,+ communityId: number,+): Promise<CommunitySliceResponse> {+ return apiGet<CommunitySliceResponse>(+ `/api/graph/${repoId}/communities/${communityId}/slice`,+ );+}++export async function getGraphMetrics(+ repoId: string,+ nodeId: string,+): Promise<GraphMetricsResponse> {+ return apiGet<GraphMetricsResponse>(`/api/graph/${repoId}/metrics`, { node_id: nodeId });+}++export async function getCallersCallees(+ repoId: string,+ symbolId: string,+ params?: { direction?: string; edge_types?: string; limit?: number },+): Promise<CallersCalleesResponse> {+ return apiGet<CallersCalleesResponse>(`/api/graph/${repoId}/callers-callees`, {+ symbol_id: symbolId,+ ...params,+ });+}++export async function getExecutionFlows(+ repoId: string,+ params?: { top_n?: number; max_depth?: number; entry_point?: string },+): Promise<ExecutionFlowsResponse> {+ return apiGet<ExecutionFlowsResponse>(`/api/graph/${repoId}/execution-flows`, params);+}diff --git a/packages/api-client/src/health.ts b/packages/api-client/src/health.tsnew file mode 100644index 000000000..ff97c20d0--- /dev/null+++ b/packages/api-client/src/health.ts@@ -0,0 +1,24 @@+import { apiGet } from "./client";+import type { HealthResponse } from "./types";++export async function getHealth(): Promise<HealthResponse> {+ return apiGet<HealthResponse>("/health");+}++export interface CoordinatorHealth {+ sql_pages: number | null;+ sql_decisions: number | null;+ vector_count: number | null;+ vector_page_count: number | null;+ vector_decision_count: number | null;+ graph_nodes: number | null;+ drift_pct: number | null;+ page_drift_pct: number | null;+ decision_drift_pct: number | null;+ status: "ok" | "warning" | "critical";+ detail: string | null;+}++export async function getCoordinatorHealth(repoId: string): Promise<CoordinatorHealth> {+ return apiGet<CoordinatorHealth>(`/api/repos/${repoId}/health/coordinator`);+}diff --git a/packages/api-client/src/index.ts b/packages/api-client/src/index.tsnew file mode 100644index 000000000..5ec76921e--- /dev/null+++ b/packages/api-client/src/index.ts@@ -0,0 +1 @@+export * from "./client";diff --git a/packages/api-client/src/jobs.ts b/packages/api-client/src/jobs.tsnew file mode 100644index 000000000..f28477286--- /dev/null+++ b/packages/api-client/src/jobs.ts@@ -0,0 +1,26 @@+import { apiGet, apiPost, BASE_URL } 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}`);+}++/** Cancel a pending or running job. Marks it failed so the active-job+ * guard releases and a new sync can be started. */+export async function cancelJob(jobId: string): Promise<JobResponse> {+ return apiPost<JobResponse>(`/api/jobs/${jobId}/cancel`);+}++/** Returns the SSE stream URL for a job. Use with EventSource or the useSSE hook. */+export function getJobStreamUrl(jobId: string): string {+ return `${BASE_URL}/api/jobs/${jobId}/stream`;+}diff --git a/packages/api-client/src/knowledge-map.ts b/packages/api-client/src/knowledge-map.tsnew file mode 100644index 000000000..900aff9bc--- /dev/null+++ b/packages/api-client/src/knowledge-map.ts@@ -0,0 +1,38 @@+import { apiGet } from "./client";++// ---------------------------------------------------------------------------+// Types+// ---------------------------------------------------------------------------++export interface KnowledgeMapOwner {+ email: string;+ name: string;+ files_owned: number;+ percentage: number;+}++export interface KnowledgeMapSilo {+ file_path: string;+ owner_email: string;+ owner_pct: number;+}++export interface KnowledgeMapTarget {+ path: string;+ pagerank: number;+ doc_words: number;+}++export interface KnowledgeMapResponse {+ top_owners: KnowledgeMapOwner[];+ knowledge_silos: KnowledgeMapSilo[];+ onboarding_targets: KnowledgeMapTarget[];+}++// ---------------------------------------------------------------------------+// API call+// ---------------------------------------------------------------------------++export async function getKnowledgeMap(repoId: string): Promise<KnowledgeMapResponse> {+ return apiGet<KnowledgeMapResponse>(`/api/repos/${repoId}/knowledge-map`);+}diff --git a/packages/api-client/src/mcp-tools.ts b/packages/api-client/src/mcp-tools.tsnew file mode 100644index 000000000..18c35e82e--- /dev/null+++ b/packages/api-client/src/mcp-tools.ts@@ -0,0 +1,17 @@+import { apiGet, apiPatch } from "./client";+import type { McpToolSurface, UpdateMcpToolsRequest } from "./types";++/** Fetch the configurable MCP tool surface for a repo. */+export async function getMcpToolSurface(repoId?: string): Promise<McpToolSurface> {+ return apiGet<McpToolSurface>(+ "/api/mcp/tools",+ repoId ? { repo_id: repoId } : undefined,+ );+}++/** Persist a new `mcp.tools` override for a repo and return the updated surface. */+export async function updateMcpTools(+ body: UpdateMcpToolsRequest,+): Promise<McpToolSurface> {+ return apiPatch<McpToolSurface>("/api/mcp/tools", body);+}diff --git a/packages/api-client/src/meta.ts b/packages/api-client/src/meta.tsnew file mode 100644index 000000000..6e8c3d5b7--- /dev/null+++ b/packages/api-client/src/meta.ts@@ -0,0 +1,44 @@+/**+ * Meta endpoints: repowise version freshness + release changelog.+ * Powers the upgrade banner, what's-new view, and version footer.+ */++import { apiGet } from "./client";++export interface MetaVersion {+ server_version: string;+ latest_version: string | null;+ /** null when PyPI could not be reached (distinct from "up to date"). */+ update_available: boolean | null;+ upgrade_command: string;+ store_format_version: number | null;+ store_compatible: boolean | null;+ reindex_recommended: boolean;+ reindex_command: string | null;+}++export interface ChangelogSection {+ name: string;+ items: string[];+}++export interface ChangelogEntry {+ version: string;+ label: string | null;+ sections: ChangelogSection[];+}++export interface ChangelogData {+ entries: ChangelogEntry[];+}++export async function getMetaVersion(repoId?: string): Promise<MetaVersion> {+ return apiGet<MetaVersion>(+ "/api/meta/version",+ repoId ? { repo_id: repoId } : undefined,+ );+}++export async function getChangelog(limit = 20): Promise<ChangelogData> {+ return apiGet<ChangelogData>("/api/meta/changelog", { limit });+}diff --git a/packages/api-client/src/modules.ts b/packages/api-client/src/modules.tsnew file mode 100644index 000000000..ca2d9bebb--- /dev/null+++ b/packages/api-client/src/modules.ts@@ -0,0 +1,31 @@+import { apiGet } from "./client";+import type {+ ModuleHealthDetail,+ ModuleHealthSummary,+ Paginated,+} from "./types";++export type ModuleHealthSortKey =+ | "health_score"+ | "hotspot_count"+ | "dead_code_lines"+ | "file_count";++export async function listModuleHealth(+ repoId: string,+ options: { sort?: ModuleHealthSortKey; limit?: number; offset?: number } = {},+): Promise<Paginated<ModuleHealthSummary>> {+ return apiGet<Paginated<ModuleHealthSummary>>(+ `/api/repos/${repoId}/modules/health`,+ options,+ );+}++export async function getModuleHealth(+ repoId: string,+ modulePath: string,+): Promise<ModuleHealthDetail> {+ return apiGet<ModuleHealthDetail>(+ `/api/repos/${repoId}/modules/health/${encodeURIComponent(modulePath)}`,+ );+}diff --git a/packages/api-client/src/overview.ts b/packages/api-client/src/overview.tsnew file mode 100644index 000000000..9427c893d--- /dev/null+++ b/packages/api-client/src/overview.ts@@ -0,0 +1,7 @@+import type { OverviewSummaryResponse } from "@repowise-dev/types/overview";+import { apiGet } from "./client";++/** One-call Overview payload — replaces the old N-call waterfall. */+export async function getOverviewSummary(repoId: string): Promise<OverviewSummaryResponse> {+ return apiGet<OverviewSummaryResponse>(`/api/repos/${repoId}/overview-summary`);+}diff --git a/packages/api-client/src/owners.ts b/packages/api-client/src/owners.tsnew file mode 100644index 000000000..f570a944f--- /dev/null+++ b/packages/api-client/src/owners.ts@@ -0,0 +1,37 @@+import { apiGet } from "./client";+import type {+ OwnerListEntry,+ OwnerProfileResponse,+ Paginated,+} from "./types";++export type OwnerSortKey =+ | "files_owned"+ | "hotspots_owned"+ | "commit_count_90d"+ | "dead_code_lines_owned"+ | "bus_factor_risk_files";++export interface ListOwnersParams {+ repoId: string;+ q?: string;+ sort?: OwnerSortKey;+ limit?: number;+ offset?: number;+}++export async function listOwnersPage(+ params: ListOwnersParams,+): Promise<Paginated<OwnerListEntry>> {+ const { repoId, ...rest } = params;+ return apiGet<Paginated<OwnerListEntry>>(`/api/repos/${repoId}/owners`, rest);+}++export async function getOwnerProfile(+ repoId: string,+ ownerKey: string,+): Promise<OwnerProfileResponse> {+ return apiGet<OwnerProfileResponse>(+ `/api/repos/${repoId}/owners/${encodeURIComponent(ownerKey)}`,+ );+}diff --git a/packages/web/src/lib/api/pages.test.ts b/packages/api-client/src/pages.test.tssimilarity index 100%rename from packages/web/src/lib/api/pages.test.tsrename to packages/api-client/src/pages.test.tsdiff --git a/packages/api-client/src/pages.ts b/packages/api-client/src/pages.tsnew file mode 100644index 000000000..b9094fb3b--- /dev/null+++ b/packages/api-client/src/pages.ts@@ -0,0 +1,69 @@+import { apiGet, apiPatch, 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,+ });+}++/** Set or clear the human-curated note pinned above a page's generated content. */+export async function updatePageNotes(+ pageId: string,+ humanNotes: string | null,+): Promise<PageResponse> {+ return apiPatch<PageResponse>(+ `/api/pages/lookup/notes?page_id=${encodeURIComponent(pageId)}`,+ { human_notes: humanNotes },+ );+}++/**+ * Force-regenerate a page by ID. Pass `style` to regenerate this page in a+ * specific wiki style (per-page override); omit it to use the repo's style.+ */+export async function regeneratePage(+ pageId: string,+ style?: string,+): Promise<{ job_id: string }> {+ return apiPost<{ job_id: string }>("/api/pages/lookup/regenerate", undefined, undefined, {+ page_id: pageId,+ ...(style ? { style } : {}),+ });+}diff --git a/packages/api-client/src/providers.ts b/packages/api-client/src/providers.tsnew file mode 100644index 000000000..2bd3a6dee--- /dev/null+++ b/packages/api-client/src/providers.ts@@ -0,0 +1,36 @@+/**+ * Provider management API module.+ */++import { apiGet, apiPatch, apiPost, apiDelete } from "./client";+import type { ProvidersResponse } from "./types";++export async function getProviders(+ repoId?: string,+): Promise<ProvidersResponse> {+ const qs = repoId ? `?repo_id=${encodeURIComponent(repoId)}` : "";+ return apiGet<ProvidersResponse>(`/api/providers${qs}`);+}++export async function setActiveProvider(+ provider: string,+ model?: string,+ repoId?: string,+): Promise<ProvidersResponse> {+ return apiPatch<ProvidersResponse>("/api/providers/active", {+ provider,+ model: model ?? null,+ repo_id: repoId ?? null,+ });+}++export async function addProviderKey(+ providerId: string,+ apiKey: string,+): Promise<void> {+ await apiPost(`/api/providers/${providerId}/key`, { api_key: apiKey });+}++export async function removeProviderKey(providerId: string): Promise<void> {+ await apiDelete(`/api/providers/${providerId}/key`);+}diff --git a/packages/api-client/src/refactoring.ts b/packages/api-client/src/refactoring.tsnew file mode 100644index 000000000..d24db8317--- /dev/null+++ b/packages/api-client/src/refactoring.ts@@ -0,0 +1,63 @@+/**+ * REST client for the refactoring endpoints.+ * Backend: packages/server/src/repowise/server/routers/refactoring.py+ */++import { apiGet, apiPost, apiPut } from "./client";+import type { GeneratedCode, RefactoringPlan, RefactoringTargets } from "@repowise-dev/ui/refactoring";++export interface RefactoringSettings {+ enabled: boolean;+ provider: string | null;+ model: string | null;+}++export interface GenerateCodeOverrides {+ provider?: string;+ model?: string;+}++export interface RefactoringTargetsParams {+ refactoringType?: string;+ minConfidence?: string;+}++export async function getRefactoringTargets(+ repoId: string,+ params: RefactoringTargetsParams = {},+): Promise<RefactoringTargets> {+ return apiGet<RefactoringTargets>(`/api/repos/${repoId}/refactoring/targets`, {+ refactoring_type: params.refactoringType,+ min_confidence: params.minConfidence,+ });+}++export async function getRefactoringPlan(+ repoId: string,+ suggestionId: string,+): Promise<RefactoringPlan> {+ return apiGet<RefactoringPlan>(`/api/repos/${repoId}/refactoring/${suggestionId}`);+}++/** Opt-in: generate the refactored code + a diff for one plan (Phase-5 endpoint). */+export async function generateRefactoringCode(+ repoId: string,+ suggestionId: string,+ overrides: GenerateCodeOverrides = {},+): Promise<GeneratedCode> {+ return apiPost<GeneratedCode>(+ `/api/repos/${repoId}/refactoring/${suggestionId}/generate-code`,+ overrides,+ );+}++export async function getRefactoringSettings(repoId: string): Promise<RefactoringSettings> {+ return apiGet<RefactoringSettings>(`/api/repos/${repoId}/refactoring/settings`);+}++export async function updateRefactoringSettings(+ repoId: string,+ settings: RefactoringSettings,+): Promise<RefactoringSettings> {+ return apiPut<RefactoringSettings>(`/api/repos/${repoId}/refactoring/settings`, settings);+}diff --git a/packages/api-client/src/repos.ts b/packages/api-client/src/repos.tsnew file mode 100644index 000000000..a0d3c0382--- /dev/null+++ b/packages/api-client/src/repos.ts@@ -0,0 +1,34 @@+import { apiGet, apiPost, apiPatch, apiDelete } 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 deleteRepo(repoId: string): Promise<{ ok: boolean; deleted_pages: number }> {+ return apiDelete<{ ok: boolean; deleted_pages: number }>(`/api/repos/${repoId}`);+}++export async function getRepoStats(repoId: string): Promise<RepoStatsResponse> {+ return apiGet<RepoStatsResponse>(`/api/repos/${repoId}/stats`);+}diff --git a/packages/api-client/src/search.ts b/packages/api-client/src/search.tsnew file mode 100644index 000000000..d7c60afc4--- /dev/null+++ b/packages/api-client/src/search.ts@@ -0,0 +1,21 @@+import { apiGet } from "./client";+import type { SearchResultResponse } from "./types";++export async function search(+ query: string,+ opts?: {+ search_type?: "semantic" | "fulltext";+ limit?: number;+ repo_id?: string;+ },+): Promise<SearchResultResponse[]> {+ const params: Record<string, string | number> = {+ query,+ search_type: opts?.search_type ?? "semantic",+ limit: opts?.limit ?? 10,+ };+ if (opts?.repo_id) {+ params.repo_id = opts.repo_id;+ }+ return apiGet<SearchResultResponse[]>("/api/search", params);+}diff --git a/packages/api-client/src/security.ts b/packages/api-client/src/security.tsnew file mode 100644index 000000000..768a59687--- /dev/null+++ b/packages/api-client/src/security.ts@@ -0,0 +1,25 @@+import { apiGet } from "./client";++export interface SecurityFinding {+ id: number;+ file_path: string;+ kind: string;+ severity: "high" | "med" | "low" | string;+ snippet: string | null;+ detected_at: string;+}++export async function listSecurityFindings(+ repoId: string,+ opts: {+ file_path?: string;+ severity?: string;+ limit?: number;+ } = {},+): Promise<SecurityFinding[]> {+ return apiGet<SecurityFinding[]>(`/api/repos/${repoId}/security`, {+ file_path: opts.file_path,+ severity: opts.severity,+ limit: opts.limit,+ });+}diff --git a/packages/api-client/src/stats.ts b/packages/api-client/src/stats.tsnew file mode 100644index 000000000..c8bca0fb0--- /dev/null+++ b/packages/api-client/src/stats.ts@@ -0,0 +1,7 @@+import type { StatsHighlights } from "@repowise-dev/types/stats";+import { apiGet } from "./client";++/** One-call payload for the repo Stats ("By the Numbers") page. */+export async function getStatsHighlights(repoId: string): Promise<StatsHighlights> {+ return apiGet<StatsHighlights>(`/api/repos/${repoId}/stats/highlights`);+}diff --git a/packages/api-client/src/symbols.ts b/packages/api-client/src/symbols.tsnew file mode 100644index 000000000..b6bcc2b0a--- /dev/null+++ b/packages/api-client/src/symbols.ts@@ -0,0 +1,61 @@+import type { SymbolDetailResponse } from "@repowise-dev/types/symbols";+import { apiGet } from "./client";+import type { Paginated, SymbolResponse } from "./types";++export type SymbolSortKey = "importance" | "name" | "complexity" | "kind";++export interface SymbolListParams {+ repo_id: string;+ q?: string;+ kind?: string;+ language?: string;+ visibility?: string;+ file_path?: string;+ in_hot_files?: boolean;+ in_entry_points?: boolean;+ sort?: SymbolSortKey;+ limit?: number;+ offset?: number;+}++/** Paginated symbol search — preferred entry point. */+export async function listSymbolsPage(+ params: SymbolListParams,+): Promise<Paginated<SymbolResponse>> {+ const p: Record<string, string | number | boolean | undefined> = { ...params };+ return apiGet<Paginated<SymbolResponse>>("/api/symbols", p);+}++/**+ * Back-compat: returns just the items array. Existing callers that don't+ * (yet) render pagination keep working but get importance-ranked output+ * by default.+ */+export async function listSymbols(params: SymbolListParams): Promise<SymbolResponse[]> {+ const page = await listSymbolsPage(params);+ return page.items;+}++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)}`);+}++/** Symbol entity-page aggregate: row + blame + callers/callees + decisions. */+export async function getSymbolDetail(+ repoId: string,+ symbolId: string,+): Promise<SymbolDetailResponse> {+ return apiGet<SymbolDetailResponse>("/api/symbols/detail", {+ repo_id: repoId,+ symbol_id: symbolId,+ });+}diff --git a/packages/api-client/src/types.ts b/packages/api-client/src/types.tsnew file mode 100644index 000000000..06f97d7c1--- /dev/null+++ b/packages/api-client/src/types.ts@@ -0,0 +1,23 @@+/**+ * TypeScript types mirroring the backend Pydantic schemas.+ * Source of truth: packages/server/src/repowise/server/schemas/+ *+ * This module was split into a per-domain `types/` package. It re-exports+ * every type so existing `@/lib/api/types` imports keep working unchanged.+ */++export * from "./types/pagination";+export * from "./types/repository";+export * from "./types/pages";+export * from "./types/search";+export * from "./types/symbols";+export * from "./types/graph";+export * from "./types/intelligence";+export * from "./types/git";+export * from "./types/dead-code";+export * from "./types/decisions";+export * from "./types/chat";+export * from "./types/workspace";+export * from "./types/ownership";+export * from "./types/mcp";+export * from "./types/misc";diff --git a/packages/web/src/lib/api/types/chat.ts b/packages/api-client/src/types/chat.tssimilarity index 100%rename from packages/web/src/lib/api/types/chat.tsrename to packages/api-client/src/types/chat.tsdiff --git a/packages/web/src/lib/api/types/dead-code.ts b/packages/api-client/src/types/dead-code.tssimilarity index 95%rename from packages/web/src/lib/api/types/dead-code.tsrename to packages/api-client/src/types/dead-code.tsindex abea92e7e..ccc39d005 100644--- a/packages/web/src/lib/api/types/dead-code.ts+++ b/packages/api-client/src/types/dead-code.ts@@ -13,6 +13,8 @@ export interface DeadCodeFindingResponse {confidence: number;reason: string;lines: number;+ start_line: number | null;+ end_line: number | null;/** Effective deletion-readiness — re-derived from confidence + risk factors. */safe_to_delete: boolean;/** Runtime-load risk factors that make this a review candidate, not a delete. */diff --git a/packages/web/src/lib/api/types/decisions.ts b/packages/api-client/src/types/decisions.tssimilarity index 100%rename from packages/web/src/lib/api/types/decisions.tsrename to packages/api-client/src/types/decisions.tsdiff --git a/packages/web/src/lib/api/types/git.ts b/packages/api-client/src/types/git.tssimilarity index 100%rename from packages/web/src/lib/api/types/git.tsrename to packages/api-client/src/types/git.tsdiff --git a/packages/web/src/lib/api/types/graph.ts b/packages/api-client/src/types/graph.tssimilarity index 100%rename from packages/web/src/lib/api/types/graph.tsrename to packages/api-client/src/types/graph.tsdiff --git a/packages/web/src/lib/api/types/intelligence.ts b/packages/api-client/src/types/intelligence.tssimilarity index 100%rename from packages/web/src/lib/api/types/intelligence.tsrename to packages/api-client/src/types/intelligence.tsdiff --git a/packages/web/src/lib/api/types/mcp.ts b/packages/api-client/src/types/mcp.tssimilarity index 100%rename from packages/web/src/lib/api/types/mcp.tsrename to packages/api-client/src/types/mcp.tsdiff --git a/packages/web/src/lib/api/types/misc.ts b/packages/api-client/src/types/misc.tssimilarity index 100%rename from packages/web/src/lib/api/types/misc.tsrename to packages/api-client/src/types/misc.tsdiff --git a/packages/web/src/lib/api/types/ownership.ts b/packages/api-client/src/types/ownership.tssimilarity index 100%rename from packages/web/src/lib/api/types/ownership.tsrename to packages/api-client/src/types/ownership.tsdiff --git a/packages/web/src/lib/api/types/pages.ts b/packages/api-client/src/types/pages.tssimilarity index 100%rename from packages/web/src/lib/api/types/pages.tsrename to packages/api-client/src/types/pages.tsdiff --git a/packages/web/src/lib/api/types/pagination.ts b/packages/api-client/src/types/pagination.tssimilarity index 100%rename from packages/web/src/lib/api/types/pagination.tsrename to packages/api-client/src/types/pagination.tsdiff --git a/packages/web/src/lib/api/types/repository.ts b/packages/api-client/src/types/repository.tssimilarity index 100%rename from packages/web/src/lib/api/types/repository.tsrename to packages/api-client/src/types/repository.tsdiff --git a/packages/web/src/lib/api/types/search.ts b/packages/api-client/src/types/search.tssimilarity index 100%rename from packages/web/src/lib/api/types/search.tsrename to packages/api-client/src/types/search.tsdiff --git a/packages/web/src/lib/api/types/symbols.ts b/packages/api-client/src/types/symbols.tssimilarity index 100%rename from packages/web/src/lib/api/types/symbols.tsrename to packages/api-client/src/types/symbols.tsdiff --git a/packages/web/src/lib/api/types/workspace.ts b/packages/api-client/src/types/workspace.tssimilarity index 100%rename from packages/web/src/lib/api/types/workspace.tsrename to packages/api-client/src/types/workspace.tsdiff --git a/packages/api-client/src/workspace.ts b/packages/api-client/src/workspace.tsnew file mode 100644index 000000000..80e9e3780--- /dev/null+++ b/packages/api-client/src/workspace.ts@@ -0,0 +1,134 @@+import { apiGet, apiPost } from "./client";+import type {+ WorkspaceResponse,+ WorkspaceContractsResponse,+ WorkspaceCoChangesResponse,+ WorkspaceGraphResponse,+ WorkspaceSyncResponse,+ WorkspaceSystemGraphResponse,+ WorkspaceBlastRadiusResponse,+ WorkspaceBreakingChangesResponse,+ WorkspaceConformanceResponse,+ WorkspaceArchitectureResponse,+} from "./types";++export async function getWorkspace(+ fetchOptions?: RequestInit,+): Promise<WorkspaceResponse> {+ return apiGet<WorkspaceResponse>("/api/workspace", undefined, fetchOptions);+}++export async function getWorkspaceContracts(opts?: {+ contract_type?: string;+ repo?: string;+ role?: string;+ limit?: number;+ offset?: number;+}): Promise<WorkspaceContractsResponse> {+ const params: Record<string, string> = {};+ if (opts?.contract_type) params.contract_type = opts.contract_type;+ if (opts?.repo) params.repo = opts.repo;+ if (opts?.role) params.role = opts.role;+ if (opts?.limit != null) params.limit = String(opts.limit);+ if (opts?.offset != null) params.offset = String(opts.offset);+ return apiGet<WorkspaceContractsResponse>("/api/workspace/contracts", params);+}++export async function getWorkspaceCoChanges(opts?: {+ repo?: string;+ min_strength?: number;+ limit?: number;+}): Promise<WorkspaceCoChangesResponse> {+ const params: Record<string, string> = {};+ if (opts?.repo) params.repo = opts.repo;+ if (opts?.min_strength != null) params.min_strength = String(opts.min_strength);+ if (opts?.limit != null) params.limit = String(opts.limit);+ return apiGet<WorkspaceCoChangesResponse>("/api/workspace/co-changes", params);+}++export async function getWorkspaceGraph(): Promise<WorkspaceGraphResponse> {+ return apiGet<WorkspaceGraphResponse>("/api/workspace/graph");+}++/**+ * The service-granular system graph (nodes = services, typed directed edges)+ * that the Live System Map renders. Thin pass-through over the persisted+ * `system_graph.json` artifact.+ */+export async function getWorkspaceSystemGraph(+ fetchOptions?: RequestInit,+): Promise<WorkspaceSystemGraphResponse> {+ return apiGet<WorkspaceSystemGraphResponse>(+ "/api/workspace/system-graph",+ undefined,+ fetchOptions,+ );+}++/**+ * Cross-repo blast radius from a service node (or repo alias): the downstream+ * services impacted if it changes, ranked by impact. Reads the same system+ * graph the map renders.+ */+export async function getWorkspaceBlastRadius(opts: {+ target: string;+ maxDepth?: number;+ includeBehavioral?: boolean;+}): Promise<WorkspaceBlastRadiusResponse> {+ const params: Record<string, string | number | boolean> = { target: opts.target };+ if (opts.maxDepth != null) params.max_depth = opts.maxDepth;+ if (opts.includeBehavioral != null) params.include_behavioral = opts.includeBehavioral;+ return apiGet<WorkspaceBlastRadiusResponse>("/api/workspace/blast-radius", params);+}++/**+ * Provider contract changes from the most recent update that break consumers+ * across repos, with the impacted consumer files. Optionally filter by provider+ * repo or severity.+ */+export async function getWorkspaceBreakingChanges(opts?: {+ repo?: string;+ severity?: "breaking" | "warning";+}): Promise<WorkspaceBreakingChangesResponse> {+ const params: Record<string, string> = {};+ if (opts?.repo) params.repo = opts.repo;+ if (opts?.severity) params.severity = opts.severity;+ return apiGet<WorkspaceBreakingChangesResponse>("/api/workspace/breaking-changes", params);+}++/**+ * Architecture conformance from the most recent update: dependency-rule+ * violations + dependency cycles over the system graph. Optionally filter to+ * findings involving one repo.+ */+export async function getWorkspaceConformance(opts?: {+ repo?: string;+}): Promise<WorkspaceConformanceResponse> {+ const params: Record<string, string> = {};+ if (opts?.repo) params.repo = opts.repo;+ return apiGet<WorkspaceConformanceResponse>("/api/workspace/conformance", params);+}++export async function getWorkspaceArchitecture(): Promise<WorkspaceArchitectureResponse> {+ return apiGet<WorkspaceArchitectureResponse>("/api/workspace/architecture");+}++/**+ * Trigger a re-sync (re-index) of the workspace. Pass ``repoAlias`` to+ * scope to one repo; otherwise the server fans out across every loaded+ * workspace repo. Returns one result per repo (accepted / skipped / error).+ */+export async function syncWorkspace(opts?: {+ repoAlias?: string;+ fullResync?: boolean;+}): Promise<WorkspaceSyncResponse> {+ const params: Record<string, string> = {};+ if (opts?.repoAlias) params.repo_alias = opts.repoAlias;+ if (opts?.fullResync) params.full_resync = "true";+ return apiPost<WorkspaceSyncResponse>(+ "/api/workspace/sync",+ undefined,+ undefined,+ params,+ );+}diff --git a/packages/api-client/tsconfig.json b/packages/api-client/tsconfig.jsonnew file mode 100644index 000000000..0ecff06fc--- /dev/null+++ b/packages/api-client/tsconfig.json@@ -0,0 +1,27 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "lib": ["ES2022", "DOM"],+ "jsx": "react-jsx",+ "strict": true,+ "noUncheckedIndexedAccess": true,+ "exactOptionalPropertyTypes": true,+ "noImplicitOverride": true,+ "isolatedModules": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "declaration": true,+ "declarationMap": true,+ "noEmit": true,+ "types": ["vitest/globals"],+ "paths": {+ "@repowise-dev/types": ["../types/src/index.ts"],+ "@repowise-dev/types/*": ["../types/src/*"],+ "@repowise-dev/ui": ["../ui/src/index.ts"],+ "@repowise-dev/ui/*": ["../ui/src/*"]+ }+ },+ "include": ["src/**/*.ts", "__tests__/**/*.ts"]+}diff --git a/packages/api-client/vitest.config.ts b/packages/api-client/vitest.config.tsnew file mode 100644index 000000000..09ced2a82--- /dev/null+++ b/packages/api-client/vitest.config.ts@@ -0,0 +1,13 @@+import { defineConfig } from "vitest/config";+import path from "node:path";++export default defineConfig({+ test: {+ include: ["src/**/*.test.ts"],+ },+ resolve: {+ alias: {+ "@repowise-dev/ui": path.resolve(__dirname, "../ui/src/index.ts"),+ },+ },+});diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd.py b/packages/cli/src/repowise/cli/commands/doctor_cmd.pyindex 21ce29bf1..b48d5e9ea 100644--- a/packages/cli/src/repowise/cli/commands/doctor_cmd.py+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd.py@@ -3,24 +3,37 @@from __future__ import annotationsimport contextlib+import jsonfrom pathlib import Path as _DoctorPath+from typing import NamedTupleimport clickfrom rich.table import Tablefrom repowise.cli.helpers import (console,+ err_console,get_db_url_for_repo,get_repowise_dir,load_state,resolve_command_target,run_async,+ silence_logs_for_machine_output,)-def _check(name: str, ok: bool, detail: str = "") -> tuple[str, str, str]:- status = "[green]OK[/green]" if ok else "[red]FAIL[/red]"- return (name, status, detail)+class DoctorCheck(NamedTuple):+ name: str+ ok: bool+ detail: str = ""+++def _check(name: str, ok: bool, detail: str = "") -> DoctorCheck:+ return DoctorCheck(name, ok, detail)+++def _status_markup(ok: bool) -> str:+ return "[green]OK[/green]" if ok else "[red]FAIL[/red]"def _claude_md_stamp_status(repo_path, state: dict) -> tuple[bool, str] | None:@@ -146,14 +159,18 @@ def _print_cli_version_status() -> None:console.print(" [dim]Restart Claude/Codex/Cursor or any MCP client after updating.[/dim]")-def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:- """Run the standard health checks against one repo. Returns ``True`` if- all checks passed.+def _run_repo_checks(+ repo_path: _DoctorPath, repair: bool, *, fmt: str = "table"+) -> tuple[bool, list[DoctorCheck]]:+ """Run the standard health checks against one repo.- Extracted so workspace mode can iterate over every repo without- duplicating the full check body.+ Returns ``(all_ok, checks)``. Extracted so workspace mode can iterate+ over every repo without duplicating the full check body. When+ ``fmt != "table"`` the table and advisory lines are not printed (repair+ is also skipped; callers must not pass ``repair=True`` with a+ non-table format)."""- checks: list[tuple[str, str, str]] = []+ checks: list[DoctorCheck] = []# 1. Git repository?try:@@ -237,7 +254,6 @@ def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:config_detail = "All required API keys configured" if config_ok else "; ".join(config_warnings)checks.append(_check("Provider config", config_ok, config_detail))-# 7. Stale page countstale_count = 0if db_ok and page_count > 0:@@ -366,6 +382,8 @@ def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:coord_drift: float | None = Nonecoord_sql_pages: int | None = Nonecoord_vector_count: int | None = None+ coord_drift_color = "white"+ coord_drift_pct = "N/A"if db_ok:try:@@ -452,25 +470,37 @@ def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:if coord_vector_count != -1 and coord_vector_count is not Noneelse "unknown")- drift_detail = (- f"SQL={coord_sql_pages}, Vector={vec_display}, "- f"Drift=[{drift_color}]{drift_pct}[/{drift_color}]"- )+ drift_detail = f"SQL={coord_sql_pages}, Vector={vec_display}, Drift={drift_pct}"coord_ok = coord_drift is None or coord_drift < 0.05checks.append(_check("Coordinator drift", coord_ok, drift_detail))+ coord_drift_color = drift_color+ coord_drift_pct = drift_pctexcept Exception as exc:checks.append(_check("Coordinator drift", True, f"Could not check: {exc}"))# 11. Distill — config block, omission store, rewrite hook (advisory)checks.extend(_distill_checks(repo_path))- # Display+ all_ok = all(c.ok for c in checks)++ if fmt != "table":+ return all_ok, checks++ # Display: the "Coordinator drift" row's detail gets its drift+ # percentage colored here, since that highlight is orthogonal to the+ # row's own OK/FAIL status.table = Table(title=f"repowise Doctor — {repo_path.name}")table.add_column("Check", style="cyan")table.add_column("Status")table.add_column("Detail")- for name, status, detail in checks:- table.add_row(name, status, detail)+ for c in checks:+ detail = c.detail+ if c.name == "Coordinator drift":+ detail = detail.replace(+ f"Drift={coord_drift_pct}",+ f"Drift=[{coord_drift_color}]{coord_drift_pct}[/{coord_drift_color}]",+ )+ table.add_row(c.name, _status_markup(c.ok), detail)console.print(table)# CLAUDE.md freshness stamp — advisory, never fails the run. The managed@@ -479,7 +509,6 @@ def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:# on and agents reading the stale "Last indexed" line distrust the tools._advise_claude_md_stamp(repo_path, state)- all_ok = all("[green]OK[/green]" in status for _, status, _ in checks)if all_ok:console.print("[bold green]All checks passed![/bold green]")else:@@ -574,17 +603,17 @@ def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:elif repair and not has_mismatches:console.print("[green]Nothing to repair.[/green]")- return all_ok+ return all_ok, checks-def _distill_checks(repo_path: _DoctorPath) -> list[tuple[str, str, str]]:+def _distill_checks(repo_path: _DoctorPath) -> list[DoctorCheck]:"""Distill feature health: config validity, store sizing, rewrite hook.The rewrite hook is opt-in, so its absence is informational, never afailure. Any unexpected error degrades to an advisory OK row — distillproblems must not break doctor."""- checks: list[tuple[str, str, str]] = []+ checks: list[DoctorCheck] = []# Config block valid?distill_cfg = None@@ -668,11 +697,20 @@ def _distill_checks(repo_path: _DoctorPath) -> list[tuple[str, str, str]]:default=False,help="Force single-repo mode even when invoked from a workspace.",)+ "--format",+ "fmt",+ default="table",+ type=click.Choice(["table", "json"]),+ help="Output format. json is read-only (incompatible with --repair) and exits "+ "1 when any check fails.",+)def doctor_command(path: str | None,repair: bool,workspace: bool,no_workspace: bool,+ fmt: str,) -> None:"""Run health checks on the wiki setup.@@ -680,19 +718,35 @@ def doctor_command(workspace mode, runs the full check battery against each indexed repoand prints a per-repo table plus a workspace-level summary."""+ if fmt != "table" and repair:+ raise click.UsageError(+ "--repair is not supported with --format json (json mode is read-only)."+ )++ if fmt != "table":+ silence_logs_for_machine_output()++ status = err_console if fmt != "table" else console+target = resolve_command_target(path=path,workspace_flag=workspace,no_workspace_flag=no_workspace,)- target.notice(console, command="doctor")+ target.notice(status, command="doctor")- # Advisory CLI update check — printed once, above the repo check table(s).- _print_cli_version_status()+ if fmt == "table":+ # Advisory CLI update check, printed once above the repo check table(s).+ _print_cli_version_status()if not target.is_workspace:assert target.repo_path is not None- _run_repo_checks(target.repo_path, repair)+ all_ok, checks = _run_repo_checks(target.repo_path, repair, fmt=fmt)+ if fmt != "table":+ payload = {"ok": all_ok, "checks": [c._asdict() for c in checks]}+ click.echo(json.dumps(payload, indent=2))+ if not all_ok:+ raise SystemExit(1)return# Workspace mode — iterate over every entry, run workspace-level@@ -702,10 +756,11 @@ def doctor_command(ws_root = target.ws_rootws_config = target.ws_config- ws_issues = _run_workspace_checks(ws_root, ws_config, repair=repair)+ ws_issues = _run_workspace_checks(ws_root, ws_config, repair=repair, fmt=fmt)overall_ok = Truenot_indexed: list[str] = []+ all_checks: list[DoctorCheck] = []for entry in ws_config.repos:abs_path = (ws_root / entry.path).resolve()if not abs_path.is_dir():@@ -713,18 +768,36 @@ def doctor_command(if not (abs_path / ".repowise").is_dir():not_indexed.append(entry.alias)continue- console.print()- console.print(- f"[bold]── {entry.alias}[/bold] "- f"[dim]({entry.path})[/dim]"- + (- " [bold cyan](primary)[/bold cyan]"- if entry.alias == ws_config.default_repo- else ""+ if fmt == "table":+ console.print()+ console.print(+ f"[bold]── {entry.alias}[/bold] "+ f"[dim]({entry.path})[/dim]"+ + (+ " [bold cyan](primary)[/bold cyan]"+ if entry.alias == ws_config.default_repo+ else ""+ ))- )- ok = _run_repo_checks(abs_path, repair)+ ok, checks = _run_repo_checks(abs_path, repair, fmt=fmt)overall_ok = overall_ok and ok+ all_checks.extend(DoctorCheck(f"{entry.alias}: {c.name}", c.ok, c.detail) for c in checks)++ if fmt != "table":+ all_ok = overall_ok and not ws_issues and not not_indexed+ payload = {+ "ok": all_ok,+ "checks": [c._asdict() for c in all_checks],+ "workspace": {+ "checked": True,+ "issues": list(ws_issues),+ "not_indexed": not_indexed,+ },+ }+ click.echo(json.dumps(payload, indent=2))+ if not all_ok:+ raise SystemExit(1)+ returnconsole.print()if not_indexed:@@ -750,6 +823,7 @@ def _run_workspace_checks(ws_config,*,repair: bool,+ fmt: str = "table",) -> list[str]:"""Run workspace-level validation. Returns a list of issue strings.@@ -759,7 +833,8 @@ def _run_workspace_checks(each repo's ``.repowise/state.json``.- MCP server registration (best-effort detection in claude config).- ``--repair``: rebuild missing ``state.json``, drop dead workspace- entries (with a notice).+ entries (with a notice). Skipped when ``fmt != "table"``; callers+ must not pass ``repair=True`` with a non-table format."""from repowise.core.workspace.update import (read_state_commit,@@ -816,16 +891,17 @@ def _run_workspace_checks(else:rows.append((entry.alias, "[green]OK[/green]", entry.path))- table = Table(title="repowise Workspace Doctor")- table.add_column("Repo", style="cyan")- table.add_column("Status")- table.add_column("Detail")- for r in rows:- table.add_row(*r)- console.print(table)-- # MCP server registration — best-effort, advisory only.- _check_mcp_registered(ws_root)+ if fmt == "table":+ table = Table(title="repowise Workspace Doctor")+ table.add_column("Repo", style="cyan")+ table.add_column("Status")+ table.add_column("Detail")+ for r in rows:+ table.add_row(*r)+ console.print(table)++ # MCP server registration: best-effort, advisory only.+ _check_mcp_registered(ws_root)# --repair: sync the workspace config from disk and drop dead entries.if repair:diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd.py b/packages/cli/src/repowise/cli/commands/risk_cmd.pyindex 78bfed5e5..a5d8c48a6 100644--- a/packages/cli/src/repowise/cli/commands/risk_cmd.py+++ b/packages/cli/src/repowise/cli/commands/risk_cmd.py@@ -14,7 +14,6 @@ Examples:from __future__ import annotationsimport json-import subprocessfrom dataclasses import replaceimport click@@ -43,61 +42,6 @@ def _ordinal(n: int) -> str:return f"{n}{suffix}"-def _baseline_scores(- repo_path: str,- anchor: str,- limit: int,- extensions: tuple[str, ...],- exclude: str,-) -> list[float]:- """Score the repo's recent commits to build a local risk distribution.-- One ``git log --numstat`` call (no per-commit author lookup), so it stays- cheap enough for a pre-merge gate. Experience is left unknown for the- baseline; the target is ranked with experience likewise unknown, so the- comparison is like-with-like — a diff-shape percentile within this repo.- """- from repowise.core.analysis.change_risk import (- features_from_file_changes,- score_change,- )-- out = subprocess.run(- ["git", "log", f"-n{limit}", "--no-merges", "--format=%x1e%H", "--numstat", anchor],- cwd=repo_path,- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- ).stdout-- scores: list[float] = []- for block in out.split("\x1e"):- lines = block.strip().split("\n")- if not lines or not lines[0]:- continue- sha, rows = lines[0].strip(), lines[1:]- # Drop the target itself from its own baseline (short or full sha).- if exclude and (sha.startswith(exclude) or exclude.startswith(sha)):- continue- changes: list[tuple[str, int, int]] = []- for row in rows:- parts = row.split("\t")- if len(parts) != 3:- continue- a_raw, d_raw, path = parts- if extensions and not path.endswith(extensions):- continue- a = int(a_raw) if a_raw.isdigit() else 0- d = int(d_raw) if d_raw.isdigit() else 0- changes.append((path, a, d))- if not changes:- continue- feats = features_from_file_changes(changes, exp=None)- scores.append(score_change(feats).score)- return scores--@click.command("risk")@click.argument("revspec", required=False, default="HEAD")@click.option(@@ -134,6 +78,7 @@ def risk_command() -> None:"""Score the defect risk of a change (commit or ``base..head`` range)."""from repowise.core.analysis.change_risk import (+ baseline_scores,extract_commit_features,extract_range_features,score_change,@@ -176,7 +121,7 @@ def risk_command(anchor, exclude = revspec, features.refif fmt == "table":status.print(f"[dim]Sampling up to {baseline} recent commits…[/dim]")- scores = _baseline_scores(repo_path, anchor, baseline, extensions, exclude)+ scores = baseline_scores(repo_path, anchor, baseline, extensions, exclude)if len(scores) >= _MIN_BASELINE:from repowise.core.analysis.change_risk import RiskNormalizerdiff --git a/packages/cli/src/repowise/cli/commands/serve_cmd.py b/packages/cli/src/repowise/cli/commands/serve_cmd.pyindex f4dc696f3..786a0a7c8 100644--- a/packages/cli/src/repowise/cli/commands/serve_cmd.py+++ b/packages/cli/src/repowise/cli/commands/serve_cmd.py@@ -2,12 +2,15 @@from __future__ import annotations+import contextlib+import jsonimport osimport shutilimport socketimport subprocessimport tarfileimport tempfile+from datetime import UTC, datetimefrom pathlib import Pathimport click@@ -17,6 +20,56 @@ from repowise.cli.helpers import console, load_config_GLOBAL_CONFIG_DIR = Path.home() / ".repowise"+_SERVE_LOCK_NAME = "serve.lock.json"+++def _serve_lock_path(cwd: Path | None = None) -> Path | None:+ """Return where the serve lockfile belongs for this directory, if anywhere.++ The lockfile lets other local tooling discover a running server (port,+ pid) without port-scanning. It lives next to the index the server is+ serving: ``.repowise/`` for a single repo, ``.repowise-workspace/`` for a+ workspace root. Returns None when neither exists (nothing to serve).+ """+ base = cwd or Path.cwd()+ for dirname in (".repowise", ".repowise-workspace"):+ candidate = base / dirname+ if candidate.is_dir():+ return candidate / _SERVE_LOCK_NAME+ return None+++def _write_serve_lock(lock_path: Path, *, host: str, port: int, ui_port: int | None) -> None:+ """Best-effort write of the discovery lockfile. Never blocks startup.++ Consumers must treat ``pid`` as the liveness check: a killed server+ cannot clean up after itself, so a stale file with a dead pid means+ "not running".+ """+ # A wildcard bind isn't a connectable URL; loopback always is.+ url_host = "127.0.0.1" if host in ("0.0.0.0", "::") else host+ payload = {+ "pid": os.getpid(),+ "host": host,+ "port": port,+ "url": f"http://{url_host}:{port}",+ "ui_port": ui_port,+ "server_version": __version__,+ "started_at": datetime.now(UTC).isoformat(),+ }+ with contextlib.suppress(OSError):+ lock_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")+++def _remove_serve_lock(lock_path: Path) -> None:+ """Best-effort removal; only removes a lock owned by this process."""+ try:+ data = json.loads(lock_path.read_text(encoding="utf-8"))+ if data.get("pid") == os.getpid():+ lock_path.unlink()+ except (OSError, ValueError):+ pass+def _setup_embedder() -> None:"""Ensure REPOWISE_EMBEDDER is set before the server starts.@@ -625,6 +678,15 @@ def serve_command(console.print(f"[green]API server starting on http://{host}:{port}[/green]")+ lock_path = _serve_lock_path()+ if lock_path:+ _write_serve_lock(+ lock_path,+ host=host,+ port=port,+ ui_port=None if (no_ui or frontend_proc is None) else ui_port,+ )+try:uvicorn.run("repowise.server.app:create_app",@@ -635,6 +697,8 @@ def serve_command(log_level="info",)finally:+ if lock_path:+ _remove_serve_lock(lock_path)if frontend_proc:frontend_proc.terminate()frontend_proc.wait(timeout=5)diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.pyindex 33cf64bd6..a3251707c 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py@@ -9,6 +9,7 @@ rendering (:mod:`.reporting`).from __future__ import annotations+import sysimport timeimport click@@ -33,6 +34,7 @@ from repowise.cli.helpers import (rotate_update_log_if_needed,run_async,save_state,+ silence_logs_for_machine_output,write_update_pending,)from repowise.core.reasoning import REASONING_MODES@@ -50,6 +52,7 @@ from .persistence import (_run_full_health_rescore,)from .reporting import (+ JsonProgressEmitter,_render_update_report,make_generation_progress,render_changed_files,@@ -194,6 +197,17 @@ def _surface_release_news(*, written_by: str | None) -> None:"warnings, and the detailed generation report)."),)+ "--progress",+ type=click.Choice(["rich", "json"]),+ default="rich",+ help=(+ "Progress output. 'rich' (default) shows the interactive owl-spinner "+ "progress bar. 'json' silences it and prints one newline-delimited "+ "JSON event per line to stdout instead, for driving this from "+ "another process."+ ),+)def update_command(path: str | None,provider_name: str | None,@@ -212,6 +226,7 @@ def update_command(concurrency: int = 10,no_cost_tracking: bool = False,verbose: bool = False,+ progress: str = "rich",) -> None:"""Incrementally update wiki pages for files changed since last sync.@@ -221,6 +236,28 @@ def update_command("""start = time.monotonic()+ # --- Machine-readable progress (--progress json) --------------------+ # Silence structlog/stdlib logging and redirect the shared Rich console+ # (used throughout this module and its sibling helpers via `log=console.print`+ # callbacks) to stderr, so stdout carries nothing but the JSON event+ # stream below. Emitter is None in the default 'rich' mode, so every call+ # site below is a no-op there. The redirect is undone when the command's+ # click context closes (success or error), since `console` is a+ # process-wide singleton and leaving it pointed at stderr would bleed+ # into whatever runs next in the same process.+ emitter: JsonProgressEmitter | None = None+ if progress == "json":+ silence_logs_for_machine_output()+ console.file = sys.stderr+ # Restore to None (rather than a captured file object) so `console`+ # goes back to resolving sys.stdout dynamically on each print, its+ # default behavior. Capturing `console.file` here would instead+ # snapshot whatever stdout happens to be at this instant (e.g. a+ # test runner's isolated buffer) and pin the shared console to it.+ click.get_current_context().call_on_close(lambda: setattr(console, "file", None))+ emitter = JsonProgressEmitter()+ emitter.start(repo=str(path or "."), since=since)+# --- Resolve target up front (single repo or workspace) ---target = resolve_command_target(path=path,@@ -236,7 +273,16 @@ def update_command("--full is single-repo only. Run it inside a specific repo ""(or pass --no-workspace / --repo <alias>).")- _workspace_update(target, dry_run=dry_run, agents_md=agents_md, verbose=verbose)+ try:+ _workspace_update(target, dry_run=dry_run, agents_md=agents_md, verbose=verbose)+ except Exception as exc:+ if emitter is not None:+ emitter.error(str(exc))+ raise+ if emitter is not None:+ emitter.done(+ ok=True, pages_generated=0, cost_usd=0.0, duration_s=time.monotonic() - start+ )return# --- Single-repo path from here on. ---@@ -258,13 +304,24 @@ def update_command(if full:from repowise.cli.commands.upgrade_flow import upgrade_to_full- upgrade_to_full(- repo_path,- provider_name=provider_name,- model=model,- reasoning=reasoning,- concurrency=concurrency,- )+ if emitter is not None:+ emitter.stage("full_upgrade")+ try:+ upgrade_to_full(+ repo_path,+ provider_name=provider_name,+ model=model,+ reasoning=reasoning,+ concurrency=concurrency,+ )+ except Exception as exc:+ if emitter is not None:+ emitter.error(str(exc))+ raise+ if emitter is not None:+ emitter.done(+ ok=True, pages_generated=0, cost_usd=0.0, duration_s=time.monotonic() - start+ )return# Truncate the hook-managed log if it has grown past the cap. The hook# appends each run unconditionally — without this opportunistic rotation@@ -293,10 +350,13 @@ def update_command(f"\nA workspace was detected at {upstream_ws}. ""Did you mean: repowise update --workspace?")- raise click.ClickException(+ message = (f"No previous sync found for {repo_path}. ""Run 'repowise init' there first, or pass --since <ref>." + hint)+ if emitter is not None:+ emitter.error(message)+ raise click.ClickException(message)# A config.yaml / health-rules.json change warrants a full health re-score# even when git is unchanged. A missing prior fingerprint is backfilled, not@@ -311,6 +371,10 @@ def update_command(console.print("[green]Already up to date.[/green]")if prev_config_fp is None and not dry_run:save_state(repo_path, {**state, "config_fingerprint": curr_config_fp})+ if emitter is not None:+ emitter.done(+ ok=True, pages_generated=0, cost_usd=0.0, duration_s=time.monotonic() - start+ )return# --- Single-flight check ------------------------------------------------@@ -338,6 +402,10 @@ def update_command(f"[dim]HEAD {head[:8] if head else 'HEAD'} marked as pending; ""the running update will roll forward to it.[/dim]")+ if emitter is not None:+ emitter.done(+ ok=True, pages_generated=0, cost_usd=0.0, duration_s=time.monotonic() - start+ )return# Backfill docs_enabled on legacy state files using the same@@ -397,13 +465,16 @@ def update_command(# so the background post-commit hook never spams output. The store's# ``written_by`` (read before this run re-stamps it) bounds the panel to# releases the user has actually crossed.- if console.is_terminal:+ if console.is_terminal and emitter is None:_surface_release_news(written_by=verdict.written_by)except Exception as exc: # never block a routine update on the upgrade layerlog.debug("store_upgrade_skipped", error=str(exc))render_header(repo_path, base_ref, head)+ if emitter is not None:+ emitter.stage("detect_changes")+from repowise.core.ingestion import ChangeDetectordetector = ChangeDetector(repo_path)@@ -415,6 +486,10 @@ def update_command(repo_path,{**state, "last_sync_commit": head, "config_fingerprint": curr_config_fp},)+ if emitter is not None:+ emitter.done(+ ok=True, pages_generated=0, cost_usd=0.0, duration_s=time.monotonic() - start+ )returnif config_changed:@@ -423,10 +498,25 @@ def update_command(console.print("[yellow]Config files changed — re-running health analysis.[/yellow]")if dry_run:console.print("[yellow]Dry run — health would be re-scored. No changes made.[/yellow]")+ if emitter is not None:+ emitter.done(+ ok=True, pages_generated=0, cost_usd=0.0, duration_s=time.monotonic() - start+ )returncfg = load_config(repo_path)exclude_patterns = list(cfg.get("exclude_patterns") or [])- _run_full_health_rescore(repo_path, exclude_patterns, state, head, curr_config_fp)+ if emitter is not None:+ emitter.stage("rescore_health")+ try:+ _run_full_health_rescore(repo_path, exclude_patterns, state, head, curr_config_fp)+ except Exception as exc:+ if emitter is not None:+ emitter.error(str(exc))+ raise+ if emitter is not None:+ emitter.done(+ ok=True, pages_generated=0, cost_usd=0.0, duration_s=time.monotonic() - start+ )returnrender_changed_files(file_diffs, verbose=verbose)@@ -437,6 +527,9 @@ def update_command(# Read exclude patterns from config (set during init or via web UI)exclude_patterns: list[str] = list(cfg.get("exclude_patterns") or [])+ if emitter is not None:+ emitter.stage("rebuild_graph")+parsed_files, source_map, graph_builder, repo_structure, file_count, git_meta_map = (_rebuild_graph_and_git(repo_path,@@ -449,6 +542,9 @@ def update_command())+ if emitter is not None:+ emitter.stage("plan_pages")+# Determine affected pages (auto-scale budget if not explicitly set)if cascade_budget is None:from repowise.core.ingestion.change_detector import compute_adaptive_budget@@ -464,6 +560,10 @@ def update_command(if dry_run:console.print("[yellow]Dry run — no pages regenerated.[/yellow]")+ if emitter is not None:+ emitter.done(+ ok=True, pages_generated=0, cost_usd=0.0, duration_s=time.monotonic() - start+ )returnpartial_health_report, dead_code_report = _run_partial_analysis(@@ -478,18 +578,29 @@ def update_command(drop_transient_git_signals(list(git_meta_map.values()))if index_only:- _persist_index_only_update(- repo_path,- graph_builder,- git_meta_map,- dead_code_report,- partial_health_report,- state,- head,- start,- [fd.path for fd in file_diffs],- file_diffs=file_diffs,- )+ if emitter is not None:+ emitter.stage("persist")+ try:+ _persist_index_only_update(+ repo_path,+ graph_builder,+ git_meta_map,+ dead_code_report,+ partial_health_report,+ state,+ head,+ start,+ [fd.path for fd in file_diffs],+ file_diffs=file_diffs,+ )+ except Exception as exc:+ if emitter is not None:+ emitter.error(str(exc))+ raise+ if emitter is not None:+ emitter.done(+ ok=True, pages_generated=0, cost_usd=0.0, duration_s=time.monotonic() - start+ )return# The generation/LLM layer is only needed past this point — importing it@@ -685,32 +796,63 @@ def update_command()repo_name = repo_path.name+ if emitter is not None:+ emitter.stage("generate")+# Drive a live progress bar (owl spinner + running cost) off generate_all's# page callbacks, matching init's generation phase. Cost is read from the- # tracker as each page lands so the readout ticks up in real time.- with make_generation_progress() as gen_progress:- gen_task = gen_progress.add_task("Generating pages...", total=None, cost=0.0)-- def _on_total_known(total: int) -> None:+ # tracker as each page lands so the readout ticks up in real time. In+ # json progress mode there is no bar, so the same callbacks emit+ # total_known / page_done events on stdout instead.+ from contextlib import nullcontext++ completed_pages = 0+ total_pages: int | None = None++ def _on_total_known(total: int) -> None:+ nonlocal total_pages+ total_pages = total+ if emitter is not None:+ emitter.total_known(total)+ else:gen_progress.update(gen_task, total=total)- def _on_page_done(_page_id: str) -> None:+ def _on_page_done(_page_id: str) -> None:+ nonlocal completed_pages+ completed_pages += 1+ if emitter is not None:+ emitter.page_done(+ completed=completed_pages, total=total_pages, cost_usd=cost_tracker.session_cost+ )+ else:gen_progress.update(gen_task, advance=1, cost=cost_tracker.session_cost)- generated_pages = run_async(- generator.generate_all(- affected_parsed,- affected_source,- graph_builder,- repo_structure,- repo_name,- on_page_done=_on_page_done,- on_total_known=_on_total_known,- git_meta_map=git_meta_map,- repo_path=repo_path,- )+ with (make_generation_progress() if emitter is None else nullcontext()) as gen_progress:+ gen_task = (+ gen_progress.add_task("Generating pages...", total=None, cost=0.0)+ if gen_progress is not None+ else None)+ try:+ generated_pages = run_async(+ generator.generate_all(+ affected_parsed,+ affected_source,+ graph_builder,+ repo_structure,+ repo_name,+ on_page_done=_on_page_done,+ on_total_known=_on_total_known,+ git_meta_map=git_meta_map,+ repo_path=repo_path,+ )+ )+ except Exception as exc:+ if emitter is not None:+ emitter.error(str(exc))+ raise+# Flush the buffered LLM cost rows now that generation is done — a single# transaction outside the contended generation window (issue #326).from repowise.cli.providers import flush_cost_tracker@@ -913,7 +1055,14 @@ def update_command(await engine.dispose()- run_async(_persist())+ if emitter is not None:+ emitter.stage("persist")+ try:+ run_async(_persist())+ except Exception as exc:+ if emitter is not None:+ emitter.error(str(exc))+ raise# ---- Editor project files (best-effort) ----try:@@ -978,6 +1127,14 @@ def update_command(pass # cross-repo hooks must never fail the updateelapsed = time.monotonic() - start+ if emitter is not None:+ emitter.done(+ ok=True,+ pages_generated=len(generated_pages),+ cost_usd=cost_tracker.session_cost,+ duration_s=elapsed,+ )+ returnshow_full_completion(generated_pages=generated_pages,decay_count=len(affected.decay_only),diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/reporting.py b/packages/cli/src/repowise/cli/commands/update_cmd/reporting.pyindex 39fc0f077..a7647fa67 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/reporting.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/reporting.py@@ -9,8 +9,11 @@ happens here.from __future__ import annotations+import json+import sysfrom typing import Any+import clickfrom rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElapsedColumnfrom repowise.cli.helpers import console@@ -87,6 +90,54 @@ def make_generation_progress() -> Progress:)+# ---------------------------------------------------------------------------+# Machine-readable progress (--progress json)+# ---------------------------------------------------------------------------+++class JsonProgressEmitter:+ """Emits newline-delimited JSON progress events to stdout.++ One JSON object per line, flushed immediately, so a supervising process+ can stream ``repowise update`` progress without parsing Rich's terminal+ output. Pairs with ``silence_logs_for_machine_output`` and redirecting+ the Rich ``console`` to stderr, so stdout carries nothing but these+ events.+ """++ def _emit(self, event: dict[str, Any]) -> None:+ click.echo(json.dumps(event))+ sys.stdout.flush()++ def start(self, *, repo: str, since: str | None) -> None:+ self._emit({"event": "start", "repo": repo, "since": since})++ def stage(self, name: str) -> None:+ self._emit({"event": "stage", "name": name})++ def total_known(self, total: int) -> None:+ self._emit({"event": "total_known", "total": total})++ def page_done(self, *, completed: int, total: int | None, cost_usd: float) -> None:+ self._emit(+ {"event": "page_done", "completed": completed, "total": total, "cost_usd": cost_usd}+ )++ def done(self, *, ok: bool, pages_generated: int, cost_usd: float, duration_s: float) -> None:+ self._emit(+ {+ "event": "done",+ "ok": ok,+ "pages_generated": pages_generated,+ "cost_usd": cost_usd,+ "duration_s": duration_s,+ }+ )++ def error(self, message: str) -> None:+ self._emit({"event": "error", "message": message})++# ---------------------------------------------------------------------------# Completion panels# ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/analysis/change_risk/__init__.py b/packages/core/src/repowise/core/analysis/change_risk/__init__.pyindex 48386cb75..e1b6d4ce1 100644--- a/packages/core/src/repowise/core/analysis/change_risk/__init__.py+++ b/packages/core/src/repowise/core/analysis/change_risk/__init__.py@@ -9,6 +9,7 @@ and is a natural pre-merge / PR gate.from __future__ import annotations+from .baseline import baseline_scoresfrom .features import (ChangeFeatures,extract_commit_features,@@ -23,6 +24,7 @@ __all__ = ["ChangeRisk","RiskDriver","RiskNormalizer",+ "baseline_scores","extract_commit_features","extract_range_features","features_from_file_changes",diff --git a/packages/core/src/repowise/core/analysis/change_risk/baseline.py b/packages/core/src/repowise/core/analysis/change_risk/baseline.pynew file mode 100644index 000000000..c7f2adda7--- /dev/null+++ b/packages/core/src/repowise/core/analysis/change_risk/baseline.py@@ -0,0 +1,64 @@+"""Repo-relative baseline sampling for change-risk percentiles.++Scores a repo's recent commits so a single change's raw risk score can be+ranked against them (see :mod:`.normalize`). Lives in core (not the CLI) so+both the CLI and the server can build a percentile off the same live-git+sample without duplicating the walk.+"""++from __future__ import annotations++import subprocess++from .features import features_from_file_changes+from .model import score_change+++def baseline_scores(+ repo_path: str,+ anchor: str,+ limit: int,+ extensions: tuple[str, ...],+ exclude: str,+) -> list[float]:+ """Score the repo's recent commits to build a local risk distribution.++ One ``git log --numstat`` call (no per-commit author lookup), so it stays+ cheap enough for a pre-merge gate. Experience is left unknown for the+ baseline; the target is ranked with experience likewise unknown, so the+ comparison is like-with-like: a diff-shape percentile within this repo.+ """+ out = subprocess.run(+ ["git", "log", f"-n{limit}", "--no-merges", "--format=%x1e%H", "--numstat", anchor],+ cwd=repo_path,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ ).stdout++ scores: list[float] = []+ for block in out.split("\x1e"):+ lines = block.strip().split("\n")+ if not lines or not lines[0]:+ continue+ sha, rows = lines[0].strip(), lines[1:]+ # Drop the target itself from its own baseline (short or full sha).+ if exclude and (sha.startswith(exclude) or exclude.startswith(sha)):+ continue+ changes: list[tuple[str, int, int]] = []+ for row in rows:+ parts = row.split("\t")+ if len(parts) != 3:+ continue+ a_raw, d_raw, path = parts+ if extensions and not path.endswith(extensions):+ continue+ a = int(a_raw) if a_raw.isdigit() else 0+ d = int(d_raw) if d_raw.isdigit() else 0+ changes.append((path, a, d))+ if not changes:+ continue+ feats = features_from_file_changes(changes, exp=None)+ scores.append(score_change(feats).score)+ return scoresdiff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex 652fe6d20..5c9e28d85 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -46,17 +46,19 @@ from .risk_factors import RISK_CAP_CONFIDENCE, path_risk_factors, risk_evidence# namespace. C# auto-properties land in the graph as ``variable``;# fields / enum members / type aliases / namespace anchors share the# same property.-_UNIVERSAL_NON_IMPORTABLE: frozenset[str] = frozenset({- "method",- "variable",- "field",- "property",- "enum_member",- "constant",- "type_alias",- "namespace",- "module",-})+_UNIVERSAL_NON_IMPORTABLE: frozenset[str] = frozenset(+ {+ "method",+ "variable",+ "field",+ "property",+ "enum_member",+ "constant",+ "type_alias",+ "namespace",+ "module",+ }+)# Additional kinds skipped only for languages where the graph cannot yet# observe interface usage. In practice these are DI-heavy languages@@ -103,132 +105,136 @@ _NON_IMPORTABLE_SYMBOL_KINDS: frozenset[str] = _UNIVERSAL_NON_IMPORTABLE | froze# so "no callers" is not evidence of deadness. Such types are still subject# to the *unused-export* pass (which reasons over import names / type_use),# so genuinely-dead exported types are still surfaced there.-_UNCALLABLE_TYPE_KINDS: frozenset[str] = frozenset({- "struct",- "interface",- "enum",- "type_alias",-})+_UNCALLABLE_TYPE_KINDS: frozenset[str] = frozenset(+ {+ "struct",+ "interface",+ "enum",+ "type_alias",+ }+)# Symbol names that are language-runtime entry points or compiler-implicit# anchors — never invoked by user-authored callers, never dead.-_ENTRY_POINT_SYMBOL_NAMES: frozenset[str] = frozenset({- "Main", # C#, Java, Kotlin, Go, Rust, Swift, Scala- "main", # most others- # ---- Go runtime / test conventions ------------------------------- # ``func init`` is run by the Go runtime when the package is linked —- # never called by name, so it has no inbound call edge. ``TestMain``- # is the test-binary entry the ``go test`` runner invokes by reflection.- "init",- "TestMain",- "MauiProgram", # .NET MAUI- "Program", # C# top-level / classic console- "Startup", # ASP.NET Core legacy- "__module__", # synthetic per-file module anchor- "_start", # C runtime- # ---- Python WSGI / ASGI / app-factory conventions ---------------- # Loaded by external servers (uvicorn / gunicorn / hypercorn /- # Tornado / aiohttp / Django) via dotted-path string such as- # ``module:create_app`` or ``module:application``. The graph never- # sees a call edge from the launching server, so without this- # allowlist every web entry point shows up as an unused public- # symbol with 1.0 confidence.- "create_app",- "make_app",- "create_application",- "make_application",- "application",- "asgi_app",- "wsgi_app",- "asgi_application",- "wsgi_application",- "get_asgi_application",- "get_wsgi_application",- # ---- Windows DLL / COM entry points ------------------------------ # Invoked by the Windows loader or COM runtime; never referenced- # statically from user code.- "DllMain",- "DllGetClassObject",- "DllCanUnloadNow",- "DllRegisterServer",- "DllUnregisterServer",- "DllGetActivationFactory",- "DllInstall", # legacy MSI custom-action entry- # ---- Win32 GUI / console entry points ---------------------------- "wWinMain", # Unicode WinMain- "WinMain", # ANSI WinMain- "wmain", # Unicode console main- "ServiceMain", # Win32 service entry- # ---- libFuzzer / Honggfuzz / AFL fuzz harness entries ------------- # The fuzzer driver invokes these by name via dlsym; no static- # caller will ever exist.- "LLVMFuzzerTestOneInput",- "LLVMFuzzerInitialize",- # ---- Windows hook / ETW callbacks invoked by macros / runtime ----- "LowLevelKeyboardProc",- "LowLevelMouseProc",- "RegisterProvider", # ETW provider registration (macro-invoked)- # ---- MSTest unit-test macro --------------------------------------- # ``TEST_METHOD(Name)`` expands into a public static function with- # ``TEST_METHOD`` as the captured symbol name; the runner finds it- # by attribute reflection. Same shape on every C++ unit test file.- "TEST_METHOD",- "TEST_CLASS",- "TEST_METHOD_INITIALIZE",- "TEST_METHOD_CLEANUP",- "TEST_CLASS_INITIALIZE",- "TEST_CLASS_CLEANUP",- "BEGIN_TEST_METHOD_PROPERTIES",- "END_TEST_METHOD_PROPERTIES",- # ---- Next.js (app + pages router) convention exports -------------- # Loaded by the Next.js runtime by name; never appear as user-code- # imports. The convention file globs already cover ``page.tsx``/- # ``route.ts``/``layout.tsx``, so this set only catches the long- # tail of route exports that escape file-glob protection (e.g.- # routes placed in non-standard paths). Limited to names that are- # distinctive enough not to risk masking dead code in unrelated- # files; common identifiers (``load``, ``action``, ``metadata``,- # ``config``, ``headers``, ``meta``, ``links``, ``runtime``) are- # deliberately omitted — they get file-level protection via the- # convention globs in :data:`_NEVER_FLAG_PATTERNS`.- "generateStaticParams",- "generateMetadata",- "generateViewport",- "generateImageMetadata",- "generateSitemaps",- "dynamicParams",- "fetchCache",- "preferredRegion",- "maxDuration",- "getStaticProps",- "getStaticPaths",- "getServerSideProps",- "getInitialProps",- "reportWebVitals",- # ---- Remix route module exports (distinctive names only) ---------- "shouldRevalidate",- "ErrorBoundary",- "CatchBoundary",- "HydrateFallback",- "clientLoader",- "clientAction",- # ---- SvelteKit page/layout module exports (distinctive names) ----- "trailingSlash",- # ---- JVM (Java + Kotlin) runtime / serialization / contract anchors ----- # ``main`` is already covered above; these are the rest of the names- # the JVM resolves through reflection / serialization / Lombok-equivalent- # generation, never through static call edges. ``INSTANCE`` is the- # Kotlin ``object Foo`` singleton field; the JVM accesses it directly.- "serialVersionUID",- "readObject",- "writeObject",- "readObjectNoData",- "readResolve",- "writeReplace",- "canEqual", # Lombok-equivalent generated method- "INSTANCE", # Kotlin object singleton field- "Companion", # Kotlin companion-object accessor-})+_ENTRY_POINT_SYMBOL_NAMES: frozenset[str] = frozenset(+ {+ "Main", # C#, Java, Kotlin, Go, Rust, Swift, Scala+ "main", # most others+ # ---- Go runtime / test conventions ------------------------------+ # ``func init`` is run by the Go runtime when the package is linked —+ # never called by name, so it has no inbound call edge. ``TestMain``+ # is the test-binary entry the ``go test`` runner invokes by reflection.+ "init",+ "TestMain",+ "MauiProgram", # .NET MAUI+ "Program", # C# top-level / classic console+ "Startup", # ASP.NET Core legacy+ "__module__", # synthetic per-file module anchor+ "_start", # C runtime+ # ---- Python WSGI / ASGI / app-factory conventions ---------------+ # Loaded by external servers (uvicorn / gunicorn / hypercorn /+ # Tornado / aiohttp / Django) via dotted-path string such as+ # ``module:create_app`` or ``module:application``. The graph never+ # sees a call edge from the launching server, so without this+ # allowlist every web entry point shows up as an unused public+ # symbol with 1.0 confidence.+ "create_app",+ "make_app",+ "create_application",+ "make_application",+ "application",+ "asgi_app",+ "wsgi_app",+ "asgi_application",+ "wsgi_application",+ "get_asgi_application",+ "get_wsgi_application",+ # ---- Windows DLL / COM entry points -----------------------------+ # Invoked by the Windows loader or COM runtime; never referenced+ # statically from user code.+ "DllMain",+ "DllGetClassObject",+ "DllCanUnloadNow",+ "DllRegisterServer",+ "DllUnregisterServer",+ "DllGetActivationFactory",+ "DllInstall", # legacy MSI custom-action entry+ # ---- Win32 GUI / console entry points ---------------------------+ "wWinMain", # Unicode WinMain+ "WinMain", # ANSI WinMain+ "wmain", # Unicode console main+ "ServiceMain", # Win32 service entry+ # ---- libFuzzer / Honggfuzz / AFL fuzz harness entries ------------+ # The fuzzer driver invokes these by name via dlsym; no static+ # caller will ever exist.+ "LLVMFuzzerTestOneInput",+ "LLVMFuzzerInitialize",+ # ---- Windows hook / ETW callbacks invoked by macros / runtime ----+ "LowLevelKeyboardProc",+ "LowLevelMouseProc",+ "RegisterProvider", # ETW provider registration (macro-invoked)+ # ---- MSTest unit-test macro --------------------------------------+ # ``TEST_METHOD(Name)`` expands into a public static function with+ # ``TEST_METHOD`` as the captured symbol name; the runner finds it+ # by attribute reflection. Same shape on every C++ unit test file.+ "TEST_METHOD",+ "TEST_CLASS",+ "TEST_METHOD_INITIALIZE",+ "TEST_METHOD_CLEANUP",+ "TEST_CLASS_INITIALIZE",+ "TEST_CLASS_CLEANUP",+ "BEGIN_TEST_METHOD_PROPERTIES",+ "END_TEST_METHOD_PROPERTIES",+ # ---- Next.js (app + pages router) convention exports -------------+ # Loaded by the Next.js runtime by name; never appear as user-code+ # imports. The convention file globs already cover ``page.tsx``/+ # ``route.ts``/``layout.tsx``, so this set only catches the long+ # tail of route exports that escape file-glob protection (e.g.+ # routes placed in non-standard paths). Limited to names that are+ # distinctive enough not to risk masking dead code in unrelated+ # files; common identifiers (``load``, ``action``, ``metadata``,+ # ``config``, ``headers``, ``meta``, ``links``, ``runtime``) are+ # deliberately omitted — they get file-level protection via the+ # convention globs in :data:`_NEVER_FLAG_PATTERNS`.+ "generateStaticParams",+ "generateMetadata",+ "generateViewport",+ "generateImageMetadata",+ "generateSitemaps",+ "dynamicParams",+ "fetchCache",+ "preferredRegion",+ "maxDuration",+ "getStaticProps",+ "getStaticPaths",+ "getServerSideProps",+ "getInitialProps",+ "reportWebVitals",+ # ---- Remix route module exports (distinctive names only) ---------+ "shouldRevalidate",+ "ErrorBoundary",+ "CatchBoundary",+ "HydrateFallback",+ "clientLoader",+ "clientAction",+ # ---- SvelteKit page/layout module exports (distinctive names) ----+ "trailingSlash",+ # ---- JVM (Java + Kotlin) runtime / serialization / contract anchors ----+ # ``main`` is already covered above; these are the rest of the names+ # the JVM resolves through reflection / serialization / Lombok-equivalent+ # generation, never through static call edges. ``INSTANCE`` is the+ # Kotlin ``object Foo`` singleton field; the JVM accesses it directly.+ "serialVersionUID",+ "readObject",+ "writeObject",+ "readObjectNoData",+ "readResolve",+ "writeReplace",+ "canEqual", # Lombok-equivalent generated method+ "INSTANCE", # Kotlin object singleton field+ "Companion", # Kotlin companion-object accessor+ }+)# Compiler-intrinsic preprocessor macros C/C++ libraries redefine as a@@ -238,25 +244,32 @@ _ENTRY_POINT_SYMBOL_NAMES: frozenset[str] = frozenset({# preprocessor ``#if __has_include(...)`` directives, which the static# graph cannot observe — so without this skip every such fallback flags# as an unused export.-_CPP_BUILTIN_MACROS: frozenset[str] = frozenset({- "__has_include",- "__has_include_next",- "__has_feature",- "__has_extension",- "__has_attribute",- "__has_cpp_attribute",- "__has_c_attribute",- "__has_declspec_attribute",- "__has_builtin",- "__has_warning",- "__builtin_expect",- "__builtin_unreachable",- "__builtin_assume",- "__builtin_constant_p",- "__is_identifier",- "__FILE__", "__LINE__", "__DATE__", "__TIME__",- "__func__", "__FUNCTION__", "__PRETTY_FUNCTION__",-})+_CPP_BUILTIN_MACROS: frozenset[str] = frozenset(+ {+ "__has_include",+ "__has_include_next",+ "__has_feature",+ "__has_extension",+ "__has_attribute",+ "__has_cpp_attribute",+ "__has_c_attribute",+ "__has_declspec_attribute",+ "__has_builtin",+ "__has_warning",+ "__builtin_expect",+ "__builtin_unreachable",+ "__builtin_assume",+ "__builtin_constant_p",+ "__is_identifier",+ "__FILE__",+ "__LINE__",+ "__DATE__",+ "__TIME__",+ "__func__",+ "__FUNCTION__",+ "__PRETTY_FUNCTION__",+ }+)from .dynamic_markers import find_dynamic_edge_files, find_dynamic_import_filesfrom .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReport@@ -268,17 +281,19 @@ logger = structlog.get_logger(__name__)# ``exports``/``main``), so a barrel with no inbound graph edge is not dead.# They are NOT skipped in the unused-export pass — a genuine symbol defined# in a barrel that nobody imports should still be flagged.-_BARREL_FILENAMES: frozenset[str] = frozenset({- "__init__.py",- "index.ts",- "index.tsx",- "index.js",- "index.jsx",- "index.mts",- "index.cts",- "index.mjs",- "index.cjs",-})+_BARREL_FILENAMES: frozenset[str] = frozenset(+ {+ "__init__.py",+ "index.ts",+ "index.tsx",+ "index.js",+ "index.jsx",+ "index.mts",+ "index.cts",+ "index.mjs",+ "index.cjs",+ }+)def _find_jsx_namespace_files(parsed_files: dict) -> set[str]:@@ -368,9 +383,7 @@ class DeadCodeAnalyzer:self._dynamic_import_files = find_dynamic_import_files(parsed_files or {}) | find_dynamic_edge_files(graph)- self._jsx_namespace_files: set[str] = _find_jsx_namespace_files(- parsed_files or {}- )+ self._jsx_namespace_files: set[str] = _find_jsx_namespace_files(parsed_files or {})# Lazily-built ``.go`` package-directory → file-node map, used by the# Go package-granular reachability hook (see ``go_reachability``).self._go_package_files: dict[str, list[str]] | None = None@@ -887,8 +900,7 @@ class DeadCodeAnalyzer:# Kotlin sealed parents, Scala typeclass traits).if self.graph.has_node(sym_id) and any(self.graph[pred][sym_id].get("edge_type")- in ("calls", "method_implements", "reads",- "extends", "implements", "type_use")+ in ("calls", "method_implements", "reads", "extends", "implements", "type_use")for pred in self.graph.predecessors(sym_id)):continue@@ -918,9 +930,7 @@ class DeadCodeAnalyzer:# edge will ever land in the graph. Clamp below the# safe-to-delete threshold so we never ship them as# confident dead code on Windows / COM-heavy C++ repos.- if is_contract_method(- sym_name, sym.get("kind"), sym.get("language", "unknown")- ):+ if is_contract_method(sym_name, sym.get("kind"), sym.get("language", "unknown")):confidence = min(confidence, 0.4)# Runtime-load risk factors for the defining file (config /@@ -953,6 +963,9 @@ class DeadCodeAnalyzer:else None,commit_count_90d=git_meta.get("commit_count_90d", 0),lines=sym.get("end_line", 0) - sym.get("start_line", 0),+ # Both-or-neither: a half-known span is worse than none.+ start_line=(sym.get("start_line") or None) if sym.get("end_line") else None,+ end_line=(sym.get("end_line") or None) if sym.get("start_line") else None,package=self._get_package(str(node)),evidence=evidence,safe_to_delete=safe,@@ -1030,6 +1043,7 @@ class DeadCodeAnalyzer:# method is invoked by the container, not by a source call.decorators = node_data.get("decorators") or []if decorators:+def _dec_base(d: str) -> str:stripped = d.lstrip("@")paren = stripped.find("(")@@ -1089,6 +1103,13 @@ class DeadCodeAnalyzer:else None,commit_count_90d=git_meta.get("commit_count_90d", 0),lines=node_data.get("end_line", 0) - node_data.get("start_line", 0),+ # Both-or-neither: a half-known span is worse than none.+ start_line=(node_data.get("start_line") or None)+ if node_data.get("end_line")+ else None,+ end_line=(node_data.get("end_line") or None)+ if node_data.get("start_line")+ else None,package=self._get_package(file_path),evidence=[f"No CALL edges to '{sym_name}'"],safe_to_delete=False,@@ -1133,8 +1154,7 @@ class DeadCodeAnalyzer:# every file under the candidate dir is config/data (YAML,# JSON, MD, TOML), it is not a package — it is metadata.has_code_file = any(- self.graph.nodes.get(f, {}).get("language", "unknown")- not in _NON_CODE_LANGUAGES+ self.graph.nodes.get(f, {}).get("language", "unknown") not in _NON_CODE_LANGUAGESfor f in files)if not has_code_file:diff --git a/packages/core/src/repowise/core/analysis/dead_code/models.py b/packages/core/src/repowise/core/analysis/dead_code/models.pyindex d93f31a11..869550426 100644--- a/packages/core/src/repowise/core/analysis/dead_code/models.py+++ b/packages/core/src/repowise/core/analysis/dead_code/models.py@@ -34,6 +34,10 @@ class DeadCodeFindingData:# script). Non-empty means the finding is a review candidate, never# deletion-ready, regardless of confidence. See :mod:`risk_factors`.risk_factors: list[str] = field(default_factory=list)+ # Symbol span in the defining file, when known (symbol-kind findings+ # only; file/package-kind findings leave both None).+ start_line: int | None = None+ end_line: int | None = None@dataclassdiff --git a/packages/core/src/repowise/core/persistence/crud/analysis.py b/packages/core/src/repowise/core/persistence/crud/analysis.pyindex 4334404e0..8a55dc232 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis.py@@ -55,6 +55,8 @@ def _dead_code_row_kwargs(finding: Any, repository_id: str) -> dict:"last_commit_at": finding.last_commit_at,"commit_count_90d": finding.commit_count_90d,"lines": finding.lines,+ "start_line": finding.start_line,+ "end_line": finding.end_line,"package": finding.package,"evidence_json": json.dumps(finding.evidence if hasattr(finding, "evidence") else []),"safe_to_delete": finding.safe_to_delete,diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 91cbcd301..f6720ab5d 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -886,6 +886,8 @@ class DeadCodeFinding(Base):last_commit_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)commit_count_90d: Mapped[int] = mapped_column(Integer, nullable=False, default=0)lines: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ start_line: Mapped[int | None] = mapped_column(Integer, nullable=True)+ end_line: Mapped[int | None] = mapped_column(Integer, nullable=True)package: Mapped[str | None] = mapped_column(String(255), nullable=True)evidence_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")safe_to_delete: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.pyindex fd42911fe..e1c6961af 100644--- a/packages/server/src/repowise/server/routers/git.py+++ b/packages/server/src/repowise/server/routers/git.py@@ -3,7 +3,10 @@from __future__ import annotationsimport json+import os+import subprocessfrom collections import Counter+from dataclasses import replacefrom datetime import datetime, timedeltafrom fastapi import APIRouter, Depends, HTTPException, Query@@ -13,6 +16,8 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.analysis.change_risk import (ChangeFeatures,RiskNormalizer,+ baseline_scores,+ extract_range_features,score_change,)from repowise.core.ingestion.git_indexer._constants import (@@ -20,12 +25,13 @@ from repowise.core.ingestion.git_indexer._constants import (classify_commit_category,)from repowise.core.persistence import crud-from repowise.core.persistence.models import GitCommit, GitMetadata+from repowise.core.persistence.models import GitCommit, GitMetadata, Repositoryfrom repowise.server.deps import get_db_session, verify_api_keyfrom repowise.server.mcp_server.tool_risk import _check_test_gapfrom repowise.server.schemas import (AgentTrendBucket,AgentTrendResponse,+ ChangeFeaturesResponse,CommitDetailResponse,CommitEvolutionBucket,CommitEvolutionResponse,@@ -38,9 +44,14 @@ from repowise.server.schemas import (Paginated,ReviewerSuggestionsResponse,RiskDriverResponse,+ RiskRangeResponse,)from repowise.server.services.reviewer_suggestions import suggest_reviewers+# Below this many sampled commits a percentile isn't worth showing; mirrors+# the CLI's ``repowise risk`` threshold so the two surfaces agree.+_MIN_BASELINE = 8+router = APIRouter(prefix="/api/repos",tags=["git"],@@ -315,9 +326,7 @@ async def get_commit_evolution(buckets to show how the development emphasis shifts as the repo matures."""result = await session.execute(- select(GitCommit.committed_at, GitCommit.subject).where(- GitCommit.repository_id == repo_id- )+ select(GitCommit.committed_at, GitCommit.subject).where(GitCommit.repository_id == repo_id))rows = [(ts, subj) for ts, subj in result.all() if ts is not None]@@ -559,6 +568,107 @@ async def get_reviewer_suggestions(return ReviewerSuggestionsResponse(paths=paths, suggestions=suggestions)+async def _resolve_local_repo(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session), # noqa: B008+) -> Repository:+ """Resolve a repository with a usable local checkout, or raise 404."""+ repo = await crud.get_repository(session, repo_id)+ if repo is None or not repo.local_path or not os.path.isdir(repo.local_path):+ raise HTTPException(status_code=404, detail="Repository not found")+ return repo+++def _revision_exists(repo_path: str, rev: str) -> bool:+ # Reject option-shaped input outright; git refuses ref names starting+ # with "-", so this loses no legitimate revision and keeps user input+ # from ever being parsed as a git flag here or downstream.+ if not rev or rev.startswith("-"):+ return False+ result = subprocess.run(+ ["git", "rev-parse", "--verify", "--quiet", f"{rev}^{{commit}}"],+ cwd=repo_path,+ capture_output=True,+ text=True,+ )+ return result.returncode == 0++[email protected]("/{repo_id}/risk/range", response_model=RiskRangeResponse)+def get_risk_range(+ repo_id: str,+ base: str = Query(..., description="Base revision of the range"),+ head: str = Query("HEAD", description="Head revision of the range"),+ baseline: int = Query(+ 200,+ ge=0,+ description="Recent commits to sample for the repo-relative percentile (0 skips it)",+ ),+ repo: Repository = Depends(_resolve_local_repo), # noqa: B008+) -> RiskRangeResponse:+ """Score a ``base..head`` git range's defect risk from its live diff shape.++ Mirrors ``repowise risk <base>..<head> --format json``: same Kamei+ change-risk model, scored on demand against the working tree instead of+ the indexed commit table, so it also covers ranges that haven't been+ indexed yet (an open PR branch). Runs sync so FastAPI dispatches it to+ the threadpool, since it shells out to git.+ """+ local_path = repo.local_path+ if not _revision_exists(local_path, base) or not _revision_exists(local_path, head):+ raise HTTPException(status_code=400, detail=f"Unknown revision in range {base!r}..{head!r}")++ try:+ features = extract_range_features(local_path, base, head)+ except Exception as exc:+ raise HTTPException(+ status_code=400, detail=f"Could not read range {base!r}..{head!r}: {exc}"+ ) from exc++ risk = score_change(features)++ percentile: float | None = None+ priority: str | None = None+ if baseline:+ scores = baseline_scores(local_path, head, baseline, (), "")+ if len(scores) >= _MIN_BASELINE:+ normalizer = RiskNormalizer.from_scores(scores)+ # Rank with experience unknown, matching the baseline (diff-shape+ # percentile within the repo), keeping the comparison like-with-like.+ rank_score = score_change(replace(features, exp=None)).score+ percentile = normalizer.percentile(rank_score)+ priority = normalizer.priority(rank_score)++ return RiskRangeResponse(+ base=base,+ head=head,+ score=risk.score,+ probability=risk.probability,+ level=risk.level,+ risk_percentile=percentile,+ review_priority=priority,+ is_fix=features.is_fix,+ features=ChangeFeaturesResponse(+ la=features.la,+ ld=features.ld,+ nf=features.nf,+ nd=features.nd,+ ns=features.ns,+ entropy=features.entropy,+ exp=features.exp,+ ),+ drivers=[+ RiskDriverResponse(+ feature=d.feature,+ value=None if d.value != d.value else d.value, # drop NaN (unknown feature)+ contribution=d.contribution,+ label=d.label,+ )+ for d in risk.top_drivers+ ],+ )++@router.get("/{repo_id}/git-summary", response_model=GitSummaryResponse)async def get_git_summary(repo_id: str,diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.pyindex d6ea8db88..fd95474a6 100644--- a/packages/server/src/repowise/server/schemas/__init__.py+++ b/packages/server/src/repowise/server/schemas/__init__.py@@ -71,6 +71,7 @@ from .external_systems import (from .git import (AgentTrendBucket,AgentTrendResponse,+ ChangeFeaturesResponse,CommitDetailResponse,CommitEvolutionBucket,CommitEvolutionResponse,@@ -81,6 +82,7 @@ from .git import (HotspotResponse,OwnershipEntry,RiskDriverResponse,+ RiskRangeResponse,)from .graph import (ArchitectureEdgeResponse,@@ -235,6 +237,7 @@ __all__ = ["C4SystemResponse","CallerCalleeEntry","CallersCalleesResponse",+ "ChangeFeaturesResponse","ChangelogEntryModel","ChangelogResponse","ChangelogSectionModel",@@ -320,6 +323,7 @@ __all__ = ["ReviewerSuggestion","ReviewerSuggestionsResponse","RiskDriverResponse",+ "RiskRangeResponse","SearchRequest","SearchResultResponse","SecurityFindingResponse",diff --git a/packages/server/src/repowise/server/schemas/code_quality.py b/packages/server/src/repowise/server/schemas/code_quality.pyindex 6402fd437..2f17a2850 100644--- a/packages/server/src/repowise/server/schemas/code_quality.py+++ b/packages/server/src/repowise/server/schemas/code_quality.py@@ -22,6 +22,8 @@ class DeadCodeFindingResponse(BaseModel):confidence: floatreason: strlines: int+ start_line: int | None+ end_line: int | None# Effective deletion-readiness — re-derived from confidence + path risk# factors, not the raw persisted boolean. A config/bootstrap/database/# environment/script file is never deletion-ready even when stored safe.@@ -55,6 +57,8 @@ class DeadCodeFindingResponse(BaseModel):confidence=confidence,reason=obj.reason, # type: ignore[attr-defined]lines=obj.lines, # type: ignore[attr-defined]+ start_line=obj.start_line, # type: ignore[attr-defined]+ end_line=obj.end_line, # type: ignore[attr-defined]safe_to_delete=effective_safe_to_delete(confidence, file_path, stored_safe),risk_factors=list(path_risk_factors(file_path)),evidence=evidence,diff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.pyindex e332985f9..05e74dbf2 100644--- a/packages/server/src/repowise/server/schemas/git.py+++ b/packages/server/src/repowise/server/schemas/git.py@@ -251,6 +251,39 @@ class CommitEvolutionResponse(BaseModel):last_commit_at: str | None = None+class ChangeFeaturesResponse(BaseModel):+ """The Kamei change-shape features the risk model scores."""++ la: int+ ld: int+ nf: int+ nd: int+ ns: int+ entropy: float+ exp: int | None+++class RiskRangeResponse(BaseModel):+ """Change-risk score for a live ``base..head`` git range.++ Scored on demand from the working tree rather than the indexed commit+ table, so it works for ranges that haven't been indexed yet (an open PR+ branch). Mirrors ``repowise risk <base>..<head> --format json`` field for+ field.+ """++ base: str+ head: str+ score: float+ probability: float+ level: str+ risk_percentile: float | None+ review_priority: str | None+ is_fix: bool+ features: ChangeFeaturesResponse+ drivers: list[RiskDriverResponse]++class CommitStatsResponse(BaseModel):"""Repo-wide commit aggregates for the commits-page headline stat cards.diff --git a/packages/web/next.config.ts b/packages/web/next.config.tsindex 9b72565f5..3411c9bc3 100644--- a/packages/web/next.config.ts+++ b/packages/web/next.config.ts@@ -2,11 +2,12 @@ import type { NextConfig } from "next";const nextConfig: NextConfig = {output: "standalone",- transpilePackages: ["@repowise-dev/ui", "@repowise-dev/types"],+ transpilePackages: ["@repowise-dev/ui", "@repowise-dev/types", "@repowise-dev/api-client"],experimental: {optimizePackageImports: ["lucide-react", "recharts"],},- // The workspace packages (@repowise-dev/types, @repowise-dev/ui) are ESM+ // The workspace packages (@repowise-dev/types, @repowise-dev/ui,+ // @repowise-dev/api-client) are ESM// ("type": "module") and their barrel files re-export with explicit ".js"// specifiers (e.g. export * from "./graph.js") that point at ".ts" sources.// Webpack needs an extension alias to map those ".js" specifiers back to thediff --git a/packages/web/src/lib/api/blast-radius.ts b/packages/web/src/lib/api/blast-radius.tsindex 32b383b4c..a82d1b3c1 100644--- a/packages/web/src/lib/api/blast-radius.ts+++ b/packages/web/src/lib/api/blast-radius.ts@@ -1,24 +1,3 @@-import { apiPost } from "./client";-import type {- BlastRadiusRequest,- BlastRadiusResponse,-} from "@repowise-dev/types/blast-radius";+import "./client";-export type {- DirectRiskEntry,- TransitiveEntry,- CochangeWarning,- ReviewerEntry,- BlastRadiusResponse,- BlastRadiusRequest,-} from "@repowise-dev/types/blast-radius";--export async function analyzeBlastRadius(- repoId: string,- body: BlastRadiusRequest,-): Promise<BlastRadiusResponse> {- return apiPost<BlastRadiusResponse>(- `/api/repos/${repoId}/blast-radius`,- body,- );-}+export * from "@repowise-dev/api-client/blast-radius";diff --git a/packages/web/src/lib/api/c4.ts b/packages/web/src/lib/api/c4.tsindex de0f5786b..d30bb9fde 100644--- a/packages/web/src/lib/api/c4.ts+++ b/packages/web/src/lib/api/c4.ts@@ -1,56 +1,3 @@-/**- * REST client for the C4 endpoints.- * Backend: packages/server/src/repowise/server/routers/c4.py- */+import "./client";-import { apiGet } from "./client";-import type { C4L1, C4L2, C4L3, ArchitectureView } from "@repowise-dev/ui/c4";--export async function getC4L1(repoId: string): Promise<C4L1> {- return apiGet<C4L1>(`/api/graph/${repoId}/c4/l1`);-}--export async function getC4L2(repoId: string): Promise<C4L2> {- return apiGet<C4L2>(`/api/graph/${repoId}/c4/l2`);-}--export async function getC4L3(repoId: string, containerId: string): Promise<C4L3> {- return apiGet<C4L3>(`/api/graph/${repoId}/c4/l3`, { container_id: containerId });-}--/**- * Fetch the Mermaid C4 source for the current view. Backend is the source- * of truth so the exported diagram matches what the API serves.- */-export async function getC4Mermaid(- repoId: string,- level: 1 | 2 | 3,- containerId?: string | null,-): Promise<string> {- const params = new URLSearchParams({ level: String(level) });- if (level === 3 && containerId) params.set("container_id", containerId);- const apiBase =- typeof window !== "undefined"- ? (process.env.NEXT_PUBLIC_REPOWISE_API_URL ?? "")- : "";- const apiKey =- typeof window !== "undefined"- ? localStorage.getItem("repowise_api_key")- : null;- const res = await fetch(`${apiBase}/api/graph/${repoId}/c4/mermaid?${params.toString()}`, {- headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : {},- });- if (!res.ok) {- throw new Error(`Failed to fetch Mermaid C4 source (${res.status})`);- }- return res.text();-}--export async function getArchitectureView(- repoId: string,- includeSymbols: boolean = false,-): Promise<ArchitectureView> {- return apiGet<ArchitectureView>(`/api/graph/${repoId}/architecture-view`, {- include_symbols: includeSymbols,- });-}+export * from "@repowise-dev/api-client/c4";diff --git a/packages/web/src/lib/api/chat.ts b/packages/web/src/lib/api/chat.tsindex 2eb9def7e..98a2129a0 100644--- a/packages/web/src/lib/api/chat.ts+++ b/packages/web/src/lib/api/chat.ts@@ -1,73 +1,3 @@-/**- * Chat API module — conversation management and SSE message streaming.- */+import "./client";-import { apiGet, apiDelete, BASE_URL, buildHeaders } from "./client";-import type { ConversationResponse, ChatMessageResponse } from "./types";--export async function listConversations(- repoId: string,-): Promise<ConversationResponse[]> {- return apiGet<ConversationResponse[]>(- `/api/repos/${repoId}/chat/conversations`,- );-}--export async function getConversation(- repoId: string,- conversationId: string,-): Promise<{- conversation: ConversationResponse;- messages: ChatMessageResponse[];-}> {- return apiGet(`/api/repos/${repoId}/chat/conversations/${conversationId}`);-}--export async function deleteConversation(- repoId: string,- conversationId: string,-): Promise<void> {- await apiDelete(`/api/repos/${repoId}/chat/conversations/${conversationId}`);-}--/**- * POST a chat message and return the raw Response for SSE streaming.- * The caller reads response.body as a ReadableStream.- */-export async function postChatMessage(- repoId: string,- opts: {- message: string;- conversationId?: string;- provider?: string;- model?: string;- },-): Promise<Response> {- const url = `${BASE_URL}/api/repos/${repoId}/chat/messages`;- const headers = buildHeaders();- headers.set("Accept", "text/event-stream");-- const res = await fetch(url, {- method: "POST",- headers,- body: JSON.stringify({- message: opts.message,- conversation_id: opts.conversationId ?? null,- provider: opts.provider ?? null,- model: opts.model ?? null,- }),- });-- if (!res.ok) {- let detail = res.statusText;- try {- const json = (await res.json()) as { detail?: string };- detail = json.detail ?? detail;- } catch {- // not JSON- }- throw new Error(`Chat error ${res.status}: ${detail}`);- }-- return res;-}+export * from "@repowise-dev/api-client/chat";diff --git a/packages/web/src/lib/api/client.ts b/packages/web/src/lib/api/client.tsindex d6a3d9b88..cdd7e613d 100644--- a/packages/web/src/lib/api/client.ts+++ b/packages/web/src/lib/api/client.ts@@ -1,14 +1,20 @@/**- * Base fetch wrapper for the repowise REST API.+ * Configures the shared @repowise-dev/api-client package with this app's+ * base URL and auth token resolution, then re-exports what the rest of the+ * app still imports from "@/lib/api/client" (ApiClientError).*- * Reads the API base URL from NEXT_PUBLIC_REPOWISE_API_URL (default: empty string,- * meaning requests go to the same origin — the Next.js rewrite proxies them).+ * Runs as a side effect the first time any "@/lib/api/*" module is imported+ * (every domain module below imports this file first), which matches the+ * timing of the module-level singleton this replaced.*- * API key is read from NEXT_PUBLIC_REPOWISE_API_KEY. For production use, the key- * should be stored in an httpOnly cookie set by the settings page.+ * Base URL: NEXT_PUBLIC_REPOWISE_API_URL (default: empty string, meaning+ * requests go to the same origin, proxied by the Next.js rewrite).+ *+ * API key: read from localStorage in the browser (set by the settings page)+ * and from REPOWISE_API_KEY / NEXT_PUBLIC_REPOWISE_API_KEY on the server.*/-import type { ApiError } from "./types";+import { configureApiClient } from "@repowise-dev/api-client";// Client-side: empty string → relative requests proxied via Next.js rewrites.// Server-side: use REPOWISE_API_URL (the backend) since server `fetch` bypasses rewrites.@@ -26,127 +32,6 @@ function getApiKey(): string | null {return process.env.REPOWISE_API_KEY ?? process.env.NEXT_PUBLIC_REPOWISE_API_KEY ?? null;}-function buildHeaders(extra?: Record<string, string>): Headers {- const headers = new Headers({- "Content-Type": "application/json",- ...extra,- });- const key = getApiKey();- if (key) {- headers.set("Authorization", `Bearer ${key}`);- }- return headers;-}--export class ApiClientError extends Error {- constructor(- public readonly status: number,- public readonly detail: string,- ) {- super(`API error ${status}: ${detail}`);- this.name = "ApiClientError";- }-}--async function handleResponse<T>(res: Response): Promise<T> {- if (!res.ok) {- let detail = res.statusText;- try {- const json = (await res.json()) as ApiError;- detail = json.detail ?? detail;- } catch {- // response body is not JSON- }- throw new ApiClientError(res.status, detail);- }- return res.json() as Promise<T>;-}--export async function apiGet<T>(- path: string,- params?: Record<string, string | number | boolean | undefined>,- fetchOptions?: RequestInit,-): Promise<T> {- const url = new URL(`${BASE_URL}${path}`, typeof window !== "undefined" ? window.location.href : "http://localhost");- if (params) {- for (const [k, v] of Object.entries(params)) {- if (v !== undefined && v !== null) {- url.searchParams.set(k, String(v));- }- }- }- const res = await fetch(url.toString(), {- method: "GET",- headers: buildHeaders(),- ...fetchOptions,- });- return handleResponse<T>(res);-}--export async function apiPost<T>(- path: string,- body?: unknown,- fetchOptions?: RequestInit,- params?: Record<string, string | number | boolean | undefined>,-): Promise<T> {- const url = new URL(`${BASE_URL}${path}`, typeof window !== "undefined" ? window.location.href : "http://localhost");- if (params) {- for (const [k, v] of Object.entries(params)) {- if (v !== undefined && v !== null) {- url.searchParams.set(k, String(v));- }- }- }- const res = await fetch(url.toString(), {- method: "POST",- headers: buildHeaders(),- body: body !== undefined ? JSON.stringify(body) : undefined,- ...fetchOptions,- });- return handleResponse<T>(res);-}--export async function apiPut<T>(- path: string,- body?: unknown,- fetchOptions?: RequestInit,-): Promise<T> {- const url = `${BASE_URL}${path}`;- const res = await fetch(url, {- method: "PUT",- headers: buildHeaders(),- body: body !== undefined ? JSON.stringify(body) : undefined,- ...fetchOptions,- });- return handleResponse<T>(res);-}--export async function apiPatch<T>(- path: string,- body?: unknown,- fetchOptions?: RequestInit,-): Promise<T> {- const url = `${BASE_URL}${path}`;- const res = await fetch(url, {- method: "PATCH",- headers: buildHeaders(),- body: body !== undefined ? JSON.stringify(body) : undefined,- ...fetchOptions,- });- return handleResponse<T>(res);-}--export async function apiDelete<T>(- path: string,- fetchOptions?: RequestInit,-): Promise<T> {- const url = `${BASE_URL}${path}`;- const res = await fetch(url, {- method: "DELETE",- headers: buildHeaders(),- ...fetchOptions,- });- return handleResponse<T>(res);-}+configureApiClient({ baseUrl: BASE_URL, token: getApiKey });-export { BASE_URL, buildHeaders };+export { ApiClientError } from "@repowise-dev/api-client";diff --git a/packages/web/src/lib/api/code-health.ts b/packages/web/src/lib/api/code-health.tsindex 2be784473..f230906fb 100644--- a/packages/web/src/lib/api/code-health.ts+++ b/packages/web/src/lib/api/code-health.ts@@ -1,133 +1,3 @@-/**- * Code-health API client. The response/query *types* now live in the shared- * `@repowise-dev/types/health` contract (migrated out of this web-local file so- * the hosted frontend and the bot read the same shapes); this module re-exports- * them for back-compat and keeps only the fetch functions.- */-import type {- ChurnComplexityResponse,- HealthFilesQuery,- HealthFilesResponse,- HealthFinding,- HealthCoverageResponse,- HealthFileBreakdownResponse,- HealthOverviewResponse,- HealthTrendResponse,- RefactoringQuery,- RefactoringTargetsResponse,-} from "@repowise-dev/types/health";-import { apiGet, apiPatch } from "./client";+import "./client";-export type {- BiomarkerBreakdownRow,- ChurnComplexityPoint,- ChurnComplexityResponse,- CoverageFileRow,- CoverageSummary,- DefectAccuracy,- FileBreakdownCategory,- FileBreakdownFinding,- HealthBand,- HealthCoverageResponse,- HealthDistribution,- HealthFileBreakdownResponse,- HealthFileMetric,- HealthFilesQuery,- HealthFilesResponse,- HealthFinding,- HealthModuleRow,- HealthOverviewResponse,- HealthTrendResponse,- ModuleCoverageRow,- RefactoringQuery,- RefactoringTarget,- RefactoringTargetsResponse,-} from "@repowise-dev/types/health";--export async function getHealthOverview(- repoId: string,- limit = 25,-): Promise<HealthOverviewResponse> {- return apiGet<HealthOverviewResponse>(- `/api/repos/${repoId}/health/overview`,- { limit },- );-}--export async function listHealthFindings(- repoId: string,- opts?: {- biomarker_type?: string;- file_path?: string;- min_severity?: string;- dimension?: string;- limit?: number;- },-): Promise<HealthFinding[]> {- return apiGet<HealthFinding[]>(`/api/repos/${repoId}/health/findings`, opts);-}--export async function listHealthFiles(- repoId: string,- opts?: HealthFilesQuery,-): Promise<HealthFilesResponse> {- return apiGet<HealthFilesResponse>(- `/api/repos/${repoId}/health/files`,- opts as Record<string, string | number | boolean | undefined>,- );-}--export async function getHealthFileBreakdown(- repoId: string,- filePath: string,-): Promise<HealthFileBreakdownResponse> {- return apiGet<HealthFileBreakdownResponse>(- `/api/repos/${repoId}/health/files/breakdown`,- { file_path: filePath },- );-}--export async function getHealthTrend(repoId: string, limit = 20): Promise<HealthTrendResponse> {- return apiGet<HealthTrendResponse>(`/api/repos/${repoId}/health/trend`, { limit });-}--export async function updateFindingStatus(- repoId: string,- findingId: string,- status: "open" | "acknowledged" | "resolved" | "false_positive",-): Promise<HealthFinding> {- return apiPatch<HealthFinding>(- `/api/repos/${repoId}/health/findings/${findingId}`,- { status },- );-}--export async function getHealthCoverage(- repoId: string,- opts?: { file_path?: string; limit?: number },-): Promise<HealthCoverageResponse> {- return apiGet<HealthCoverageResponse>(- `/api/repos/${repoId}/health/coverage`,- opts,- );-}--export async function getRefactoringTargets(- repoId: string,- opts?: RefactoringQuery,-): Promise<RefactoringTargetsResponse> {- return apiGet<RefactoringTargetsResponse>(- `/api/repos/${repoId}/health/refactoring-targets`,- opts as Record<string, string | number | boolean | undefined>,- );-}--export async function getChurnComplexity(- repoId: string,- opts?: { limit?: number },-): Promise<ChurnComplexityResponse> {- return apiGet<ChurnComplexityResponse>(- `/api/repos/${repoId}/health/churn-complexity`,- opts,- );-}+export * from "@repowise-dev/api-client/code-health";diff --git a/packages/web/src/lib/api/costs.ts b/packages/web/src/lib/api/costs.tsindex b301bc874..f08549d0e 100644--- a/packages/web/src/lib/api/costs.ts+++ b/packages/web/src/lib/api/costs.ts@@ -1,94 +1,3 @@-import { apiGet } from "./client";+import "./client";-// ----------------------------------------------------------------------------// Types-// -----------------------------------------------------------------------------export interface CostGroup {- group: string;- calls: number;- input_tokens: number;- output_tokens: number;- cost_usd: number;-}--export interface CostSummary {- total_cost_usd: number;- total_calls: number;- total_input_tokens: number;- total_output_tokens: number;- since: string | null;-}--export interface DistillSavingsGroup {- group: string;- events: number;- raw_tokens: number;- distilled_tokens: number;- saved_tokens: number;-}--export interface McpDropGroup {- tool: string;- events: number;- tokens: number;- /** "counterfactual" (answer replaced raw exploration) or "truncation" (budget drop). */- kind?: string;-}--export interface DistillSavings {- available: boolean;- events: number;- raw_tokens: number;- distilled_tokens: number;- saved_tokens: number;- estimated_usd_saved: number;- pricing_model: string;- /** How the pricing model was resolved (Phase 1 model-aware pricing). */- pricing_agent: string;- pricing_source: string;- per_filter: DistillSavingsGroup[];- per_day: DistillSavingsGroup[];- /** Unified MCP savings — counterfactual ledger + truncation drops. */- mcp_events: number;- mcp_tokens: number;- /** Count of counterfactual MCP queries answered ("N MCP queries answered"). */- mcp_queries: number;- mcp_per_tool: McpDropGroup[];- /** Raw (non-distilled) agent commands a filter would have caught. */- missed_events: number;- missed_tokens_est: number;- missed_window_days: number;-}--// ----------------------------------------------------------------------------// API functions-// -----------------------------------------------------------------------------export async function listCosts(- repoId: string,- opts: { since?: string; by?: "operation" | "model" | "day" } = {},-): Promise<CostGroup[]> {- return apiGet<CostGroup[]>(`/api/repos/${repoId}/costs`, {- since: opts.since,- by: opts.by ?? "day",- });-}--export async function getCostSummary(- repoId: string,- since?: string,-): Promise<CostSummary> {- return apiGet<CostSummary>(`/api/repos/${repoId}/costs/summary`, {- since,- });-}--export async function getDistillSavings(- repoId: string,- since?: string,-): Promise<DistillSavings> {- return apiGet<DistillSavings>(`/api/repos/${repoId}/distill-savings`, {- since,- });-}+export * from "@repowise-dev/api-client/costs";diff --git a/packages/web/src/lib/api/coupling.ts b/packages/web/src/lib/api/coupling.tsindex 2c6bf1861..5944c046e 100644--- a/packages/web/src/lib/api/coupling.ts+++ b/packages/web/src/lib/api/coupling.ts@@ -1,20 +1,3 @@-/**- * Change-coupling API client. The response types live in the shared- * `@repowise-dev/types/coupling` contract; this module re-exports them and- * keeps only the fetch function.- */-import type { CouplingGraphResponse } from "@repowise-dev/types/coupling";-import { apiGet } from "./client";+import "./client";-export type {- CouplingEdge,- CouplingGraphResponse,- CouplingNode,-} from "@repowise-dev/types/coupling";--export async function getCoupling(- repoId: string,- opts?: { limit?: number },-): Promise<CouplingGraphResponse> {- return apiGet<CouplingGraphResponse>(`/api/repos/${repoId}/coupling`, opts);-}+export * from "@repowise-dev/api-client/coupling";diff --git a/packages/web/src/lib/api/dead-code.ts b/packages/web/src/lib/api/dead-code.tsindex 4990e927d..4e0928eec 100644--- a/packages/web/src/lib/api/dead-code.ts+++ b/packages/web/src/lib/api/dead-code.ts@@ -1,34 +1,3 @@-import { apiGet, apiPost, apiPatch } from "./client";-import type {- DeadCodeFindingResponse,- DeadCodePatchRequest,- DeadCodeSummaryResponse,-} from "./types";+import "./client";-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);-}+export * from "@repowise-dev/api-client/dead-code";diff --git a/packages/web/src/lib/api/decisions.ts b/packages/web/src/lib/api/decisions.tsindex a214969ab..542136cbd 100644--- a/packages/web/src/lib/api/decisions.ts+++ b/packages/web/src/lib/api/decisions.ts@@ -1,76 +1,3 @@-import { apiGet, apiPost, apiPatch } from "./client";-import type {- DecisionCreate,- DecisionEvidence,- DecisionEvidenceResponse,- DecisionGraph,- DecisionLineageEntry,- DecisionLineageResponse,- DecisionRecordResponse,- DecisionStatusUpdate,-} from "./types";+import "./client";-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 getDecisionEvidence(- repoId: string,- decisionId: string,-): Promise<DecisionEvidence[]> {- const res = await apiGet<DecisionEvidenceResponse>(- `/api/repos/${repoId}/decisions/${decisionId}/evidence`,- );- return res.evidence;-}--export async function getDecisionLineage(- repoId: string,- decisionId: string,-): Promise<DecisionLineageEntry[]> {- const res = await apiGet<DecisionLineageResponse>(- `/api/repos/${repoId}/decisions/${decisionId}/lineage`,- );- return res.lineage;-}--export async function getDecisionGraph(repoId: string): Promise<DecisionGraph> {- return apiGet<DecisionGraph>(`/api/repos/${repoId}/decisions/graph`);-}+export * from "@repowise-dev/api-client/decisions";diff --git a/packages/web/src/lib/api/external-systems.ts b/packages/web/src/lib/api/external-systems.tsindex 2adf37d54..324dc87e6 100644--- a/packages/web/src/lib/api/external-systems.ts+++ b/packages/web/src/lib/api/external-systems.ts@@ -1,12 +1,3 @@-import type { ExternalSystemsRegistry } from "@repowise-dev/types/external-systems";+import "./client";-import { apiGet } from "./client";--/** Full dependency registry (one row per name + manifest, undeduplicated). */-export async function getExternalSystems(- repoId: string,-): Promise<ExternalSystemsRegistry> {- return apiGet<ExternalSystemsRegistry>(- `/api/repos/${repoId}/external-systems`,- );-}+export * from "@repowise-dev/api-client/external-systems";diff --git a/packages/web/src/lib/api/files.ts b/packages/web/src/lib/api/files.tsindex d1e621ed1..8eec930e6 100644--- a/packages/web/src/lib/api/files.ts+++ b/packages/web/src/lib/api/files.ts@@ -1,30 +1,3 @@-import type { FileDetailResponse, FilesIndexResponse } from "@repowise-dev/types/files";-import { apiGet, BASE_URL, buildHeaders } from "./client";+import "./client";-/** Slim per-file rows for the browsable Files index + treemap. */-export async function getFilesIndex(repoId: string): Promise<FilesIndexResponse> {- return apiGet<FilesIndexResponse>(`/api/repos/${repoId}/files`);-}--/** Canonical file-detail aggregate for the file entity page. */-export async function getFileDetail(- repoId: string,- filePath: string,-): Promise<FileDetailResponse> {- // Encode each segment but keep the slashes — the server route uses a- // catch-all path converter.- const encoded = filePath.split("/").map(encodeURIComponent).join("/");- return apiGet<FileDetailResponse>(`/api/repos/${repoId}/files/${encoded}`);-}--/** Raw file content from the repo checkout (plain text, not JSON). */-export async function getFileContent(repoId: string, filePath: string): Promise<string> {- const url = new URL(- `${BASE_URL}/api/repos/${repoId}/file-content`,- typeof window !== "undefined" ? window.location.href : "http://localhost",- );- url.searchParams.set("file_path", filePath);- const res = await fetch(url.toString(), { headers: buildHeaders() });- if (!res.ok) throw new Error(`Failed to fetch file content (${res.status})`);- return res.text();-}+export * from "@repowise-dev/api-client/files";diff --git a/packages/web/src/lib/api/git.ts b/packages/web/src/lib/api/git.tsindex d8430d052..00c15d9bc 100644--- a/packages/web/src/lib/api/git.ts+++ b/packages/web/src/lib/api/git.ts@@ -1,160 +1,3 @@-import { apiGet } from "./client";-import type {- AgentTrend,- CommitEvolution,- CommitStats,- CommitDetailResponse,- CommitResponse,- GitMetadataResponse,- GitSummaryResponse,- HotspotResponse,- OwnershipEntry,- Paginated,- ReviewerSuggestionsResponse,-} from "./types";+import "./client";-export async function getGitMetadata(- repoId: string,- filePath: string,-): Promise<GitMetadataResponse> {- return apiGet<GitMetadataResponse>(`/api/repos/${repoId}/git-metadata`, {- file_path: filePath,- });-}--/**- * Paginated hotspot fetch — returns the full envelope so the UI can render- * "Showing N of M / Load more". New callers should prefer this over- * {@link getHotspots}, which is kept for back-compat (returns just the- * items list, but no longer hides the long tail since the server cap is- * 500 rather than the old 100).- */-export async function getHotspotsPage(- repoId: string,- options: { limit?: number; offset?: number } = {},-): Promise<Paginated<HotspotResponse>> {- const { limit = 50, offset = 0 } = options;- return apiGet<Paginated<HotspotResponse>>(`/api/repos/${repoId}/hotspots`, {- limit,- offset,- });-}--/**- * Back-compat helper — keeps the legacy `(repoId, limit) → list` signature- * used by widgets that don't (yet) render a "load more" affordance.- */-export async function getHotspots(- repoId: string,- limit = 50,-): Promise<HotspotResponse[]> {- const page = await getHotspotsPage(repoId, { limit });- return page.items;-}--export async function getOwnershipPage(- repoId: string,- granularity: "file" | "module" = "module",- options: { limit?: number; offset?: number } = {},-): Promise<Paginated<OwnershipEntry>> {- const { limit = 500, offset = 0 } = options;- return apiGet<Paginated<OwnershipEntry>>(`/api/repos/${repoId}/ownership`, {- granularity,- limit,- offset,- });-}--export async function getOwnership(- repoId: string,- granularity: "file" | "module" = "module",-): Promise<OwnershipEntry[]> {- const page = await getOwnershipPage(repoId, granularity, { limit: 5000 });- return page.items;-}--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 }>;- total?: number;-}> {- return apiGet(`/api/repos/${repoId}/co-changes`, {- file_path: filePath,- min_count: minCount,- });-}--export async function getReviewerSuggestions(- repoId: string,- paths: string[],- limit = 10,-): Promise<ReviewerSuggestionsResponse> {- // FastAPI repeats `?paths=` per entry; URLSearchParams handles that for- // us when we hand it tuples.- const sp = new URLSearchParams();- for (const p of paths) sp.append("paths", p);- sp.append("limit", String(limit));- return apiGet<ReviewerSuggestionsResponse>(- `/api/repos/${repoId}/reviewer-suggestions?${sp.toString()}`,- );-}--export async function getGitSummary(- repoId: string,- topOwnersLimit?: number,-): Promise<GitSummaryResponse> {- const params = topOwnersLimit ? { top_owners_limit: topOwnersLimit } : undefined;- return apiGet<GitSummaryResponse>(`/api/repos/${repoId}/git-summary`, params);-}--/**- * Paginated per-commit change-risk feed — the review-priority queue. `sort`- * defaults to `risk` (review-priority order); `date` orders by recency. Each- * commit carries a repo-relative `risk_percentile` + `review_priority`.- */-export async function getCommitsPage(- repoId: string,- options: {- sort?: "risk" | "date";- authorship?: "all" | "agent" | "human";- limit?: number;- offset?: number;- } = {},-): Promise<Paginated<CommitResponse>> {- const { sort = "risk", authorship = "all", limit = 50, offset = 0 } = options;- return apiGet<Paginated<CommitResponse>>(`/api/repos/${repoId}/commits`, {- sort,- authorship,- limit,- offset,- });-}--/** Monthly agent-vs-human commit volume across the indexed window. */-export async function getAgentTrend(repoId: string): Promise<AgentTrend> {- return apiGet<AgentTrend>(`/api/repos/${repoId}/commits/agent-trend`);-}--export async function getCommitEvolution(- repoId: string,- granularity: "auto" | "month" | "week" = "auto",-): Promise<CommitEvolution> {- return apiGet<CommitEvolution>(- `/api/repos/${repoId}/commits/evolution?granularity=${granularity}`,- );-}--export async function getCommitStats(repoId: string): Promise<CommitStats> {- return apiGet<CommitStats>(`/api/repos/${repoId}/commits/stats`);-}--export async function getCommit(- repoId: string,- sha: string,-): Promise<CommitDetailResponse> {- return apiGet<CommitDetailResponse>(`/api/repos/${repoId}/commits/${sha}`);-}+export * from "@repowise-dev/api-client/git";diff --git a/packages/web/src/lib/api/graph.ts b/packages/web/src/lib/api/graph.tsindex 8beac3618..f793b23a0 100644--- a/packages/web/src/lib/api/graph.ts+++ b/packages/web/src/lib/api/graph.ts@@ -1,156 +1,3 @@-import { apiGet } from "./client";-import type {- ArchitectureGraphResponse,- CallersCalleesResponse,- CommunityDetailResponse,- CommunitySliceResponse,- CommunitySummaryItem,- DeadCodeGraphResponse,- EgoGraphResponse,- ExecutionFlowsResponse,- GraphExportResponse,- GraphMetricsResponse,- GraphPathResponse,- HotFilesGraphResponse,- ModuleGraphResponse,- NodeSearchResult,-} from "./types";+import "./client";-export async function getGraph(- repoId: string,- limit?: number,-): Promise<GraphExportResponse> {- return apiGet<GraphExportResponse>(- `/api/graph/${repoId}`,- limit != null ? { limit } : undefined,- );-}--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`);-}--/**- * Community super-node view: one node per detected community, with- * cross-community edges. Endpoint introduced in Phase A of the graph- * UX overhaul; rendering surface is incremental and the legacy- * entry-point view above remains the default until adapter support lands.- */-export async function getArchitectureCommunityGraph(- repoId: string,- minMembers = 2,-): Promise<ArchitectureGraphResponse> {- return apiGet<ArchitectureGraphResponse>(`/api/graph/${repoId}/architecture`, {- min_members: minMembers,- });-}--/**- * Constellation (radial Knowledge Graph) data source — the community- * super-graph. Thin alias over {@link getArchitectureCommunityGraph} so the- * G3 wiring reads cleanly.- */-export async function getArchitecture(- repoId: string,- minMembers = 2,-): Promise<ArchitectureGraphResponse> {- return getArchitectureCommunityGraph(repoId, minMembers);-}--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 });-}--// ----------------------------------------------------------------------------// Graph Intelligence-// -----------------------------------------------------------------------------export async function getCommunities(repoId: string): Promise<CommunitySummaryItem[]> {- return apiGet<CommunitySummaryItem[]>(`/api/graph/${repoId}/communities`);-}--export async function getCommunityDetail(- repoId: string,- communityId: number,- params?: { include_members?: boolean; member_limit?: number },-): Promise<CommunityDetailResponse> {- return apiGet<CommunityDetailResponse>(- `/api/graph/${repoId}/communities/${communityId}`,- params,- );-}--/**- * Constellation blossom slice: a single community's member file nodes, the- * edges among them, and one-hop boundary stubs (neighbor nodes flagged- * `is_boundary`) so cross-cluster edges render. Fetched on hub expand.- */-export async function getCommunitySlice(- repoId: string,- communityId: number,-): Promise<CommunitySliceResponse> {- return apiGet<CommunitySliceResponse>(- `/api/graph/${repoId}/communities/${communityId}/slice`,- );-}--export async function getGraphMetrics(- repoId: string,- nodeId: string,-): Promise<GraphMetricsResponse> {- return apiGet<GraphMetricsResponse>(`/api/graph/${repoId}/metrics`, { node_id: nodeId });-}--export async function getCallersCallees(- repoId: string,- symbolId: string,- params?: { direction?: string; edge_types?: string; limit?: number },-): Promise<CallersCalleesResponse> {- return apiGet<CallersCalleesResponse>(`/api/graph/${repoId}/callers-callees`, {- symbol_id: symbolId,- ...params,- });-}--export async function getExecutionFlows(- repoId: string,- params?: { top_n?: number; max_depth?: number; entry_point?: string },-): Promise<ExecutionFlowsResponse> {- return apiGet<ExecutionFlowsResponse>(`/api/graph/${repoId}/execution-flows`, params);-}+export * from "@repowise-dev/api-client/graph";diff --git a/packages/web/src/lib/api/health.ts b/packages/web/src/lib/api/health.tsindex ff97c20d0..7fe1940db 100644--- a/packages/web/src/lib/api/health.ts+++ b/packages/web/src/lib/api/health.ts@@ -1,24 +1,3 @@-import { apiGet } from "./client";-import type { HealthResponse } from "./types";+import "./client";-export async function getHealth(): Promise<HealthResponse> {- return apiGet<HealthResponse>("/health");-}--export interface CoordinatorHealth {- sql_pages: number | null;- sql_decisions: number | null;- vector_count: number | null;- vector_page_count: number | null;- vector_decision_count: number | null;- graph_nodes: number | null;- drift_pct: number | null;- page_drift_pct: number | null;- decision_drift_pct: number | null;- status: "ok" | "warning" | "critical";- detail: string | null;-}--export async function getCoordinatorHealth(repoId: string): Promise<CoordinatorHealth> {- return apiGet<CoordinatorHealth>(`/api/repos/${repoId}/health/coordinator`);-}+export * from "@repowise-dev/api-client/health";diff --git a/packages/web/src/lib/api/jobs.ts b/packages/web/src/lib/api/jobs.tsindex 8cee93a6b..b383e3f83 100644--- a/packages/web/src/lib/api/jobs.ts+++ b/packages/web/src/lib/api/jobs.ts@@ -1,27 +1,3 @@-import { apiGet, apiPost } from "./client";-import type { JobResponse } from "./types";+import "./client";-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}`);-}--/** Cancel a pending or running job. Marks it failed so the active-job- * guard releases and a new sync can be started. */-export async function cancelJob(jobId: string): Promise<JobResponse> {- return apiPost<JobResponse>(`/api/jobs/${jobId}/cancel`);-}--/** 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`;-}+export * from "@repowise-dev/api-client/jobs";diff --git a/packages/web/src/lib/api/knowledge-map.ts b/packages/web/src/lib/api/knowledge-map.tsindex 900aff9bc..b6d765062 100644--- a/packages/web/src/lib/api/knowledge-map.ts+++ b/packages/web/src/lib/api/knowledge-map.ts@@ -1,38 +1,3 @@-import { apiGet } from "./client";+import "./client";-// ----------------------------------------------------------------------------// Types-// -----------------------------------------------------------------------------export interface KnowledgeMapOwner {- email: string;- name: string;- files_owned: number;- percentage: number;-}--export interface KnowledgeMapSilo {- file_path: string;- owner_email: string;- owner_pct: number;-}--export interface KnowledgeMapTarget {- path: string;- pagerank: number;- doc_words: number;-}--export interface KnowledgeMapResponse {- top_owners: KnowledgeMapOwner[];- knowledge_silos: KnowledgeMapSilo[];- onboarding_targets: KnowledgeMapTarget[];-}--// ----------------------------------------------------------------------------// API call-// -----------------------------------------------------------------------------export async function getKnowledgeMap(repoId: string): Promise<KnowledgeMapResponse> {- return apiGet<KnowledgeMapResponse>(`/api/repos/${repoId}/knowledge-map`);-}+export * from "@repowise-dev/api-client/knowledge-map";diff --git a/packages/web/src/lib/api/mcp-tools.ts b/packages/web/src/lib/api/mcp-tools.tsindex 18c35e82e..36194aa63 100644--- a/packages/web/src/lib/api/mcp-tools.ts+++ b/packages/web/src/lib/api/mcp-tools.ts@@ -1,17 +1,3 @@-import { apiGet, apiPatch } from "./client";-import type { McpToolSurface, UpdateMcpToolsRequest } from "./types";+import "./client";-/** Fetch the configurable MCP tool surface for a repo. */-export async function getMcpToolSurface(repoId?: string): Promise<McpToolSurface> {- return apiGet<McpToolSurface>(- "/api/mcp/tools",- repoId ? { repo_id: repoId } : undefined,- );-}--/** Persist a new `mcp.tools` override for a repo and return the updated surface. */-export async function updateMcpTools(- body: UpdateMcpToolsRequest,-): Promise<McpToolSurface> {- return apiPatch<McpToolSurface>("/api/mcp/tools", body);-}+export * from "@repowise-dev/api-client/mcp-tools";diff --git a/packages/web/src/lib/api/meta.ts b/packages/web/src/lib/api/meta.tsindex 6e8c3d5b7..942c85375 100644--- a/packages/web/src/lib/api/meta.ts+++ b/packages/web/src/lib/api/meta.ts@@ -1,44 +1,3 @@-/**- * Meta endpoints: repowise version freshness + release changelog.- * Powers the upgrade banner, what's-new view, and version footer.- */+import "./client";-import { apiGet } from "./client";--export interface MetaVersion {- server_version: string;- latest_version: string | null;- /** null when PyPI could not be reached (distinct from "up to date"). */- update_available: boolean | null;- upgrade_command: string;- store_format_version: number | null;- store_compatible: boolean | null;- reindex_recommended: boolean;- reindex_command: string | null;-}--export interface ChangelogSection {- name: string;- items: string[];-}--export interface ChangelogEntry {- version: string;- label: string | null;- sections: ChangelogSection[];-}--export interface ChangelogData {- entries: ChangelogEntry[];-}--export async function getMetaVersion(repoId?: string): Promise<MetaVersion> {- return apiGet<MetaVersion>(- "/api/meta/version",- repoId ? { repo_id: repoId } : undefined,- );-}--export async function getChangelog(limit = 20): Promise<ChangelogData> {- return apiGet<ChangelogData>("/api/meta/changelog", { limit });-}+export * from "@repowise-dev/api-client/meta";diff --git a/packages/web/src/lib/api/modules.ts b/packages/web/src/lib/api/modules.tsindex ca2d9bebb..3a745f57a 100644--- a/packages/web/src/lib/api/modules.ts+++ b/packages/web/src/lib/api/modules.ts@@ -1,31 +1,3 @@-import { apiGet } from "./client";-import type {- ModuleHealthDetail,- ModuleHealthSummary,- Paginated,-} from "./types";+import "./client";-export type ModuleHealthSortKey =- | "health_score"- | "hotspot_count"- | "dead_code_lines"- | "file_count";--export async function listModuleHealth(- repoId: string,- options: { sort?: ModuleHealthSortKey; limit?: number; offset?: number } = {},-): Promise<Paginated<ModuleHealthSummary>> {- return apiGet<Paginated<ModuleHealthSummary>>(- `/api/repos/${repoId}/modules/health`,- options,- );-}--export async function getModuleHealth(- repoId: string,- modulePath: string,-): Promise<ModuleHealthDetail> {- return apiGet<ModuleHealthDetail>(- `/api/repos/${repoId}/modules/health/${encodeURIComponent(modulePath)}`,- );-}+export * from "@repowise-dev/api-client/modules";diff --git a/packages/web/src/lib/api/overview.ts b/packages/web/src/lib/api/overview.tsindex 9427c893d..2f3fc7a5a 100644--- a/packages/web/src/lib/api/overview.ts+++ b/packages/web/src/lib/api/overview.ts@@ -1,7 +1,3 @@-import type { OverviewSummaryResponse } from "@repowise-dev/types/overview";-import { apiGet } from "./client";+import "./client";-/** One-call Overview payload — replaces the old N-call waterfall. */-export async function getOverviewSummary(repoId: string): Promise<OverviewSummaryResponse> {- return apiGet<OverviewSummaryResponse>(`/api/repos/${repoId}/overview-summary`);-}+export * from "@repowise-dev/api-client/overview";diff --git a/packages/web/src/lib/api/owners.ts b/packages/web/src/lib/api/owners.tsindex f570a944f..11b21d473 100644--- a/packages/web/src/lib/api/owners.ts+++ b/packages/web/src/lib/api/owners.ts@@ -1,37 +1,3 @@-import { apiGet } from "./client";-import type {- OwnerListEntry,- OwnerProfileResponse,- Paginated,-} from "./types";+import "./client";-export type OwnerSortKey =- | "files_owned"- | "hotspots_owned"- | "commit_count_90d"- | "dead_code_lines_owned"- | "bus_factor_risk_files";--export interface ListOwnersParams {- repoId: string;- q?: string;- sort?: OwnerSortKey;- limit?: number;- offset?: number;-}--export async function listOwnersPage(- params: ListOwnersParams,-): Promise<Paginated<OwnerListEntry>> {- const { repoId, ...rest } = params;- return apiGet<Paginated<OwnerListEntry>>(`/api/repos/${repoId}/owners`, rest);-}--export async function getOwnerProfile(- repoId: string,- ownerKey: string,-): Promise<OwnerProfileResponse> {- return apiGet<OwnerProfileResponse>(- `/api/repos/${repoId}/owners/${encodeURIComponent(ownerKey)}`,- );-}+export * from "@repowise-dev/api-client/owners";diff --git a/packages/web/src/lib/api/pages.ts b/packages/web/src/lib/api/pages.tsindex b9094fb3b..9126e686d 100644--- a/packages/web/src/lib/api/pages.ts+++ b/packages/web/src/lib/api/pages.ts@@ -1,69 +1,3 @@-import { apiGet, apiPatch, apiPost } from "./client";-import type { PageResponse, PageVersionResponse } from "./types";+import "./client";-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,- });-}--/** Set or clear the human-curated note pinned above a page's generated content. */-export async function updatePageNotes(- pageId: string,- humanNotes: string | null,-): Promise<PageResponse> {- return apiPatch<PageResponse>(- `/api/pages/lookup/notes?page_id=${encodeURIComponent(pageId)}`,- { human_notes: humanNotes },- );-}--/**- * Force-regenerate a page by ID. Pass `style` to regenerate this page in a- * specific wiki style (per-page override); omit it to use the repo's style.- */-export async function regeneratePage(- pageId: string,- style?: string,-): Promise<{ job_id: string }> {- return apiPost<{ job_id: string }>("/api/pages/lookup/regenerate", undefined, undefined, {- page_id: pageId,- ...(style ? { style } : {}),- });-}+export * from "@repowise-dev/api-client/pages";diff --git a/packages/web/src/lib/api/providers.ts b/packages/web/src/lib/api/providers.tsindex 2bd3a6dee..54aa0fcf9 100644--- a/packages/web/src/lib/api/providers.ts+++ b/packages/web/src/lib/api/providers.ts@@ -1,36 +1,3 @@-/**- * Provider management API module.- */+import "./client";-import { apiGet, apiPatch, apiPost, apiDelete } from "./client";-import type { ProvidersResponse } from "./types";--export async function getProviders(- repoId?: string,-): Promise<ProvidersResponse> {- const qs = repoId ? `?repo_id=${encodeURIComponent(repoId)}` : "";- return apiGet<ProvidersResponse>(`/api/providers${qs}`);-}--export async function setActiveProvider(- provider: string,- model?: string,- repoId?: string,-): Promise<ProvidersResponse> {- return apiPatch<ProvidersResponse>("/api/providers/active", {- provider,- model: model ?? null,- repo_id: repoId ?? null,- });-}--export async function addProviderKey(- providerId: string,- apiKey: string,-): Promise<void> {- await apiPost(`/api/providers/${providerId}/key`, { api_key: apiKey });-}--export async function removeProviderKey(providerId: string): Promise<void> {- await apiDelete(`/api/providers/${providerId}/key`);-}+export * from "@repowise-dev/api-client/providers";diff --git a/packages/web/src/lib/api/refactoring.ts b/packages/web/src/lib/api/refactoring.tsindex d24db8317..f72111979 100644--- a/packages/web/src/lib/api/refactoring.ts+++ b/packages/web/src/lib/api/refactoring.ts@@ -1,63 +1,3 @@-/**- * REST client for the refactoring endpoints.- * Backend: packages/server/src/repowise/server/routers/refactoring.py- */+import "./client";-import { apiGet, apiPost, apiPut } from "./client";-import type { GeneratedCode, RefactoringPlan, RefactoringTargets } from "@repowise-dev/ui/refactoring";--export interface RefactoringSettings {- enabled: boolean;- provider: string | null;- model: string | null;-}--export interface GenerateCodeOverrides {- provider?: string;- model?: string;-}--export interface RefactoringTargetsParams {- refactoringType?: string;- minConfidence?: string;-}--export async function getRefactoringTargets(- repoId: string,- params: RefactoringTargetsParams = {},-): Promise<RefactoringTargets> {- return apiGet<RefactoringTargets>(`/api/repos/${repoId}/refactoring/targets`, {- refactoring_type: params.refactoringType,- min_confidence: params.minConfidence,- });-}--export async function getRefactoringPlan(- repoId: string,- suggestionId: string,-): Promise<RefactoringPlan> {- return apiGet<RefactoringPlan>(`/api/repos/${repoId}/refactoring/${suggestionId}`);-}--/** Opt-in: generate the refactored code + a diff for one plan (Phase-5 endpoint). */-export async function generateRefactoringCode(- repoId: string,- suggestionId: string,- overrides: GenerateCodeOverrides = {},-): Promise<GeneratedCode> {- return apiPost<GeneratedCode>(- `/api/repos/${repoId}/refactoring/${suggestionId}/generate-code`,- overrides,- );-}--export async function getRefactoringSettings(repoId: string): Promise<RefactoringSettings> {- return apiGet<RefactoringSettings>(`/api/repos/${repoId}/refactoring/settings`);-}--export async function updateRefactoringSettings(- repoId: string,- settings: RefactoringSettings,-): Promise<RefactoringSettings> {- return apiPut<RefactoringSettings>(`/api/repos/${repoId}/refactoring/settings`, settings);-}+export * from "@repowise-dev/api-client/refactoring";diff --git a/packages/web/src/lib/api/repos.ts b/packages/web/src/lib/api/repos.tsindex a0d3c0382..0b76857c1 100644--- a/packages/web/src/lib/api/repos.ts+++ b/packages/web/src/lib/api/repos.ts@@ -1,34 +1,3 @@-import { apiGet, apiPost, apiPatch, apiDelete } from "./client";-import type { RepoCreate, RepoUpdate, RepoResponse, JobResponse, RepoStatsResponse } from "./types";+import "./client";-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 deleteRepo(repoId: string): Promise<{ ok: boolean; deleted_pages: number }> {- return apiDelete<{ ok: boolean; deleted_pages: number }>(`/api/repos/${repoId}`);-}--export async function getRepoStats(repoId: string): Promise<RepoStatsResponse> {- return apiGet<RepoStatsResponse>(`/api/repos/${repoId}/stats`);-}+export * from "@repowise-dev/api-client/repos";diff --git a/packages/web/src/lib/api/search.ts b/packages/web/src/lib/api/search.tsindex d7c60afc4..e03f47a51 100644--- a/packages/web/src/lib/api/search.ts+++ b/packages/web/src/lib/api/search.ts@@ -1,21 +1,3 @@-import { apiGet } from "./client";-import type { SearchResultResponse } from "./types";+import "./client";-export async function search(- query: string,- opts?: {- search_type?: "semantic" | "fulltext";- limit?: number;- repo_id?: string;- },-): Promise<SearchResultResponse[]> {- const params: Record<string, string | number> = {- query,- search_type: opts?.search_type ?? "semantic",- limit: opts?.limit ?? 10,- };- if (opts?.repo_id) {- params.repo_id = opts.repo_id;- }- return apiGet<SearchResultResponse[]>("/api/search", params);-}+export * from "@repowise-dev/api-client/search";diff --git a/packages/web/src/lib/api/security.ts b/packages/web/src/lib/api/security.tsindex 768a59687..8681ba15d 100644--- a/packages/web/src/lib/api/security.ts+++ b/packages/web/src/lib/api/security.ts@@ -1,25 +1,3 @@-import { apiGet } from "./client";+import "./client";-export interface SecurityFinding {- id: number;- file_path: string;- kind: string;- severity: "high" | "med" | "low" | string;- snippet: string | null;- detected_at: string;-}--export async function listSecurityFindings(- repoId: string,- opts: {- file_path?: string;- severity?: string;- limit?: number;- } = {},-): Promise<SecurityFinding[]> {- return apiGet<SecurityFinding[]>(`/api/repos/${repoId}/security`, {- file_path: opts.file_path,- severity: opts.severity,- limit: opts.limit,- });-}+export * from "@repowise-dev/api-client/security";diff --git a/packages/web/src/lib/api/stats.ts b/packages/web/src/lib/api/stats.tsindex c8bca0fb0..660b32aab 100644--- a/packages/web/src/lib/api/stats.ts+++ b/packages/web/src/lib/api/stats.ts@@ -1,7 +1,3 @@-import type { StatsHighlights } from "@repowise-dev/types/stats";-import { apiGet } from "./client";+import "./client";-/** One-call payload for the repo Stats ("By the Numbers") page. */-export async function getStatsHighlights(repoId: string): Promise<StatsHighlights> {- return apiGet<StatsHighlights>(`/api/repos/${repoId}/stats/highlights`);-}+export * from "@repowise-dev/api-client/stats";diff --git a/packages/web/src/lib/api/symbols.ts b/packages/web/src/lib/api/symbols.tsindex b6bcc2b0a..8fa5a1695 100644--- a/packages/web/src/lib/api/symbols.ts+++ b/packages/web/src/lib/api/symbols.ts@@ -1,61 +1,3 @@-import type { SymbolDetailResponse } from "@repowise-dev/types/symbols";-import { apiGet } from "./client";-import type { Paginated, SymbolResponse } from "./types";+import "./client";-export type SymbolSortKey = "importance" | "name" | "complexity" | "kind";--export interface SymbolListParams {- repo_id: string;- q?: string;- kind?: string;- language?: string;- visibility?: string;- file_path?: string;- in_hot_files?: boolean;- in_entry_points?: boolean;- sort?: SymbolSortKey;- limit?: number;- offset?: number;-}--/** Paginated symbol search — preferred entry point. */-export async function listSymbolsPage(- params: SymbolListParams,-): Promise<Paginated<SymbolResponse>> {- const p: Record<string, string | number | boolean | undefined> = { ...params };- return apiGet<Paginated<SymbolResponse>>("/api/symbols", p);-}--/**- * Back-compat: returns just the items array. Existing callers that don't- * (yet) render pagination keep working but get importance-ranked output- * by default.- */-export async function listSymbols(params: SymbolListParams): Promise<SymbolResponse[]> {- const page = await listSymbolsPage(params);- return page.items;-}--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)}`);-}--/** Symbol entity-page aggregate: row + blame + callers/callees + decisions. */-export async function getSymbolDetail(- repoId: string,- symbolId: string,-): Promise<SymbolDetailResponse> {- return apiGet<SymbolDetailResponse>("/api/symbols/detail", {- repo_id: repoId,- symbol_id: symbolId,- });-}+export * from "@repowise-dev/api-client/symbols";diff --git a/packages/web/src/lib/api/types.ts b/packages/web/src/lib/api/types.tsindex 06f97d7c1..e508f42d0 100644--- a/packages/web/src/lib/api/types.ts+++ b/packages/web/src/lib/api/types.ts@@ -1,23 +1 @@-/**- * TypeScript types mirroring the backend Pydantic schemas.- * Source of truth: packages/server/src/repowise/server/schemas/- *- * This module was split into a per-domain `types/` package. It re-exports- * every type so existing `@/lib/api/types` imports keep working unchanged.- */--export * from "./types/pagination";-export * from "./types/repository";-export * from "./types/pages";-export * from "./types/search";-export * from "./types/symbols";-export * from "./types/graph";-export * from "./types/intelligence";-export * from "./types/git";-export * from "./types/dead-code";-export * from "./types/decisions";-export * from "./types/chat";-export * from "./types/workspace";-export * from "./types/ownership";-export * from "./types/mcp";-export * from "./types/misc";+export * from "@repowise-dev/api-client/types";diff --git a/packages/web/src/lib/api/workspace.ts b/packages/web/src/lib/api/workspace.tsindex 80e9e3780..fc50db40d 100644--- a/packages/web/src/lib/api/workspace.ts+++ b/packages/web/src/lib/api/workspace.ts@@ -1,134 +1,3 @@-import { apiGet, apiPost } from "./client";-import type {- WorkspaceResponse,- WorkspaceContractsResponse,- WorkspaceCoChangesResponse,- WorkspaceGraphResponse,- WorkspaceSyncResponse,- WorkspaceSystemGraphResponse,- WorkspaceBlastRadiusResponse,- WorkspaceBreakingChangesResponse,- WorkspaceConformanceResponse,- WorkspaceArchitectureResponse,-} from "./types";+import "./client";-export async function getWorkspace(- fetchOptions?: RequestInit,-): Promise<WorkspaceResponse> {- return apiGet<WorkspaceResponse>("/api/workspace", undefined, fetchOptions);-}--export async function getWorkspaceContracts(opts?: {- contract_type?: string;- repo?: string;- role?: string;- limit?: number;- offset?: number;-}): Promise<WorkspaceContractsResponse> {- const params: Record<string, string> = {};- if (opts?.contract_type) params.contract_type = opts.contract_type;- if (opts?.repo) params.repo = opts.repo;- if (opts?.role) params.role = opts.role;- if (opts?.limit != null) params.limit = String(opts.limit);- if (opts?.offset != null) params.offset = String(opts.offset);- return apiGet<WorkspaceContractsResponse>("/api/workspace/contracts", params);-}--export async function getWorkspaceCoChanges(opts?: {- repo?: string;- min_strength?: number;- limit?: number;-}): Promise<WorkspaceCoChangesResponse> {- const params: Record<string, string> = {};- if (opts?.repo) params.repo = opts.repo;- if (opts?.min_strength != null) params.min_strength = String(opts.min_strength);- if (opts?.limit != null) params.limit = String(opts.limit);- return apiGet<WorkspaceCoChangesResponse>("/api/workspace/co-changes", params);-}--export async function getWorkspaceGraph(): Promise<WorkspaceGraphResponse> {- return apiGet<WorkspaceGraphResponse>("/api/workspace/graph");-}--/**- * The service-granular system graph (nodes = services, typed directed edges)- * that the Live System Map renders. Thin pass-through over the persisted- * `system_graph.json` artifact.- */-export async function getWorkspaceSystemGraph(- fetchOptions?: RequestInit,-): Promise<WorkspaceSystemGraphResponse> {- return apiGet<WorkspaceSystemGraphResponse>(- "/api/workspace/system-graph",- undefined,- fetchOptions,- );-}--/**- * Cross-repo blast radius from a service node (or repo alias): the downstream- * services impacted if it changes, ranked by impact. Reads the same system- * graph the map renders.- */-export async function getWorkspaceBlastRadius(opts: {- target: string;- maxDepth?: number;- includeBehavioral?: boolean;-}): Promise<WorkspaceBlastRadiusResponse> {- const params: Record<string, string | number | boolean> = { target: opts.target };- if (opts.maxDepth != null) params.max_depth = opts.maxDepth;- if (opts.includeBehavioral != null) params.include_behavioral = opts.includeBehavioral;- return apiGet<WorkspaceBlastRadiusResponse>("/api/workspace/blast-radius", params);-}--/**- * Provider contract changes from the most recent update that break consumers- * across repos, with the impacted consumer files. Optionally filter by provider- * repo or severity.- */-export async function getWorkspaceBreakingChanges(opts?: {- repo?: string;- severity?: "breaking" | "warning";-}): Promise<WorkspaceBreakingChangesResponse> {- const params: Record<string, string> = {};- if (opts?.repo) params.repo = opts.repo;- if (opts?.severity) params.severity = opts.severity;- return apiGet<WorkspaceBreakingChangesResponse>("/api/workspace/breaking-changes", params);-}--/**- * Architecture conformance from the most recent update: dependency-rule- * violations + dependency cycles over the system graph. Optionally filter to- * findings involving one repo.- */-export async function getWorkspaceConformance(opts?: {- repo?: string;-}): Promise<WorkspaceConformanceResponse> {- const params: Record<string, string> = {};- if (opts?.repo) params.repo = opts.repo;- return apiGet<WorkspaceConformanceResponse>("/api/workspace/conformance", params);-}--export async function getWorkspaceArchitecture(): Promise<WorkspaceArchitectureResponse> {- return apiGet<WorkspaceArchitectureResponse>("/api/workspace/architecture");-}--/**- * Trigger a re-sync (re-index) of the workspace. Pass ``repoAlias`` to- * scope to one repo; otherwise the server fans out across every loaded- * workspace repo. Returns one result per repo (accepted / skipped / error).- */-export async function syncWorkspace(opts?: {- repoAlias?: string;- fullResync?: boolean;-}): Promise<WorkspaceSyncResponse> {- const params: Record<string, string> = {};- if (opts?.repoAlias) params.repo_alias = opts.repoAlias;- if (opts?.fullResync) params.full_resync = "true";- return apiPost<WorkspaceSyncResponse>(- "/api/workspace/sync",- undefined,- undefined,- params,- );-}+export * from "@repowise-dev/api-client/workspace";diff --git a/scripts/check-shared-imports.mjs b/scripts/check-shared-imports.mjsnew file mode 100644index 000000000..1c8fbbd27--- /dev/null+++ b/scripts/check-shared-imports.mjs@@ -0,0 +1,74 @@+#!/usr/bin/env node+/**+ * Fails if any file under packages/ui/src or packages/api-client/src imports+ * "next" (or a "next/..." subpath). Those packages are shared with consumers+ * that are not Next.js apps, so they must stay framework-free. "next-themes"+ * is a different package and must not be flagged.+ */++import { readdirSync, readFileSync, statSync } from "node:fs";+import { join, relative } from "node:path";++const ROOT = process.cwd();+const SCAN_DIRS = ["packages/ui/src", "packages/api-client/src"];+const FILE_EXTENSIONS = [".ts", ".tsx"];++// Matches import/export "next", "next/x", require("next"), require("next/x"),+// and dynamic import("next"...). Captures the specifier's leading segment so+// "next-themes" (a distinct package name) never matches.+const NEXT_IMPORT_PATTERN =+ /(?:from\s+|require\(\s*|import\(\s*)["']next(?:\/[^"']*)?["']/g;++function walk(dir, files = []) {+ for (const entry of readdirSync(dir)) {+ const fullPath = join(dir, entry);+ const stat = statSync(fullPath);+ if (stat.isDirectory()) {+ walk(fullPath, files);+ } else if (FILE_EXTENSIONS.some((ext) => entry.endsWith(ext))) {+ files.push(fullPath);+ }+ }+ return files;+}++const offenses = [];++for (const scanDir of SCAN_DIRS) {+ const absDir = join(ROOT, scanDir);+ let files;+ try {+ files = walk(absDir);+ } catch {+ continue; // directory doesn't exist, nothing to scan+ }++ for (const file of files) {+ const content = readFileSync(file, "utf8");+ const lines = content.split("\n");+ lines.forEach((line, index) => {+ NEXT_IMPORT_PATTERN.lastIndex = 0;+ if (NEXT_IMPORT_PATTERN.test(line)) {+ offenses.push({+ file: relative(ROOT, file),+ line: index + 1,+ text: line.trim(),+ });+ }+ });+ }+}++if (offenses.length > 0) {+ console.error("Found forbidden \"next\" imports in shared packages:\n");+ for (const offense of offenses) {+ console.error(` ${offense.file}:${offense.line} ${offense.text}`);+ }+ console.error(+ `\n${offenses.length} offense(s). packages/ui and packages/api-client must stay framework-free; remove the Next.js dependency.`,+ );+ process.exit(1);+}++console.log("No forbidden \"next\" imports found in shared packages.");+process.exit(0);diff --git a/tests/unit/cli/test_doctor_json.py b/tests/unit/cli/test_doctor_json.pynew file mode 100644index 000000000..45167d914--- /dev/null+++ b/tests/unit/cli/test_doctor_json.py@@ -0,0 +1,63 @@+"""Tests for ``repowise doctor --format json``."""++from __future__ import annotations++import json+import subprocess+from pathlib import Path++from click.testing import CliRunner++from repowise.cli.commands.doctor_cmd import DoctorCheck, _check, doctor_command+++def _git_init(p: Path) -> None:+ p.mkdir(parents=True, exist_ok=True)+ subprocess.run(["git", "init"], cwd=str(p), capture_output=True)+++class TestCheckCarriesOk:+ def test_check_returns_named_tuple_with_ok(self) -> None:+ c = _check("Some check", True, "all good")+ assert isinstance(c, DoctorCheck)+ assert c.name == "Some check"+ assert c.ok is True+ assert c.detail == "all good"++ def test_check_failure(self) -> None:+ c = _check("Some check", False, "broken")+ assert c.ok is False+++class TestDoctorFormatJson:+ def test_json_output_on_unindexed_repo(self, tmp_path: Path) -> None:+ _git_init(tmp_path)++ result = CliRunner().invoke(+ doctor_command, [str(tmp_path), "--no-workspace", "--format", "json"]+ )++ # Doctor should still report cleanly even though checks fail.+ assert result.exit_code == 1, result.output+ payload = json.loads(result.output[result.output.index("{") :])+ assert payload["ok"] is False+ names = {c["name"] for c in payload["checks"]}+ assert ".repowise/ directory" in names+ failing = [c for c in payload["checks"] if c["name"] == ".repowise/ directory"]+ assert failing[0]["ok"] is False+ # Detail strings must be plain text: no Rich markup leaking through.+ for c in payload["checks"]:+ assert "[green]" not in c["detail"]+ assert "[red]" not in c["detail"]++ def test_repair_with_json_is_a_usage_error(self, tmp_path: Path) -> None:+ _git_init(tmp_path)++ result = CliRunner().invoke(+ doctor_command,+ [str(tmp_path), "--no-workspace", "--format", "json", "--repair"],+ )++ assert result.exit_code != 0+ assert "--repair" in result.output+ assert "json" in result.output.lower()diff --git a/tests/unit/cli/test_serve_lock.py b/tests/unit/cli/test_serve_lock.pynew file mode 100644index 000000000..80c846880--- /dev/null+++ b/tests/unit/cli/test_serve_lock.py@@ -0,0 +1,73 @@+"""Tests for the serve discovery lockfile helpers."""++from __future__ import annotations++import json+import os++from repowise.cli.commands.serve_cmd import (+ _remove_serve_lock,+ _serve_lock_path,+ _write_serve_lock,+)+++class TestServeLockPath:+ def test_no_index_dir_returns_none(self, tmp_path):+ assert _serve_lock_path(tmp_path) is None++ def test_repo_index_dir(self, tmp_path):+ (tmp_path / ".repowise").mkdir()+ path = _serve_lock_path(tmp_path)+ assert path == tmp_path / ".repowise" / "serve.lock.json"++ def test_workspace_dir(self, tmp_path):+ (tmp_path / ".repowise-workspace").mkdir()+ path = _serve_lock_path(tmp_path)+ assert path == tmp_path / ".repowise-workspace" / "serve.lock.json"++ def test_repo_dir_preferred_over_workspace(self, tmp_path):+ (tmp_path / ".repowise").mkdir()+ (tmp_path / ".repowise-workspace").mkdir()+ path = _serve_lock_path(tmp_path)+ assert path is not None+ assert path.parent.name == ".repowise"+++class TestServeLockLifecycle:+ def test_write_then_remove(self, tmp_path):+ (tmp_path / ".repowise").mkdir()+ lock = _serve_lock_path(tmp_path)+ assert lock is not None++ _write_serve_lock(lock, host="127.0.0.1", port=7337, ui_port=3000)+ data = json.loads(lock.read_text(encoding="utf-8"))+ assert data["pid"] == os.getpid()+ assert data["port"] == 7337+ assert data["host"] == "127.0.0.1"+ assert data["url"] == "http://127.0.0.1:7337"+ assert data["ui_port"] == 3000+ assert data["server_version"]+ assert data["started_at"]++ _remove_serve_lock(lock)+ assert not lock.exists()++ def test_write_without_ui(self, tmp_path):+ (tmp_path / ".repowise").mkdir()+ lock = _serve_lock_path(tmp_path)+ _write_serve_lock(lock, host="127.0.0.1", port=7440, ui_port=None)+ data = json.loads(lock.read_text(encoding="utf-8"))+ assert data["ui_port"] is None++ def test_remove_leaves_foreign_lock(self, tmp_path):+ (tmp_path / ".repowise").mkdir()+ lock = _serve_lock_path(tmp_path)+ lock.write_text(json.dumps({"pid": os.getpid() + 99999, "port": 7337}))+ _remove_serve_lock(lock)+ assert lock.exists()++ def test_remove_missing_lock_is_noop(self, tmp_path):+ (tmp_path / ".repowise").mkdir()+ lock = _serve_lock_path(tmp_path)+ _remove_serve_lock(lock) # must not raisediff --git a/tests/unit/cli/test_update_progress_json.py b/tests/unit/cli/test_update_progress_json.pynew file mode 100644index 000000000..55b263fdf--- /dev/null+++ b/tests/unit/cli/test_update_progress_json.py@@ -0,0 +1,155 @@+"""Tests for `repowise update --progress json`.++Covers the ``JsonProgressEmitter`` in isolation (each event serializes to one+valid JSON line) and a ``CliRunner`` smoke test of the wiring: stdout carries+only the event stream, informational Rich output moves to stderr, and the+stream is well-formed on both the "nothing to do" and "no prior sync" paths+(the only ones cheaply reachable without a real provider/LLM call).+"""++from __future__ import annotations++import json+import os+import tempfile++from click.testing import CliRunner++from repowise.cli.commands.update_cmd.reporting import JsonProgressEmitter+from repowise.cli.main import cli+++class TestJsonProgressEmitter:+ def _lines(self, capsys) -> list[dict]:+ out = capsys.readouterr().out+ lines = [line for line in out.splitlines() if line.strip()]+ return [json.loads(line) for line in lines]++ def test_start(self, capsys):+ JsonProgressEmitter().start(repo="myrepo", since="abc123")+ (event,) = self._lines(capsys)+ assert event == {"event": "start", "repo": "myrepo", "since": "abc123"}++ def test_stage(self, capsys):+ JsonProgressEmitter().stage("rebuild_graph")+ (event,) = self._lines(capsys)+ assert event == {"event": "stage", "name": "rebuild_graph"}++ def test_total_known(self, capsys):+ JsonProgressEmitter().total_known(42)+ (event,) = self._lines(capsys)+ assert event == {"event": "total_known", "total": 42}++ def test_page_done(self, capsys):+ JsonProgressEmitter().page_done(completed=3, total=42, cost_usd=0.015)+ (event,) = self._lines(capsys)+ assert event == {"event": "page_done", "completed": 3, "total": 42, "cost_usd": 0.015}++ def test_page_done_total_unknown(self, capsys):+ JsonProgressEmitter().page_done(completed=1, total=None, cost_usd=0.0)+ (event,) = self._lines(capsys)+ assert event["total"] is None++ def test_done(self, capsys):+ JsonProgressEmitter().done(ok=True, pages_generated=5, cost_usd=0.42, duration_s=12.3)+ (event,) = self._lines(capsys)+ assert event == {+ "event": "done",+ "ok": True,+ "pages_generated": 5,+ "cost_usd": 0.42,+ "duration_s": 12.3,+ }++ def test_error(self, capsys):+ JsonProgressEmitter().error("boom")+ (event,) = self._lines(capsys)+ assert event == {"event": "error", "message": "boom"}++ def test_multiple_events_are_one_json_object_per_line(self, capsys):+ emitter = JsonProgressEmitter()+ emitter.start(repo="r", since=None)+ emitter.stage("generate")+ emitter.total_known(2)+ emitter.page_done(completed=1, total=2, cost_usd=0.01)+ emitter.page_done(completed=2, total=2, cost_usd=0.02)+ emitter.done(ok=True, pages_generated=2, cost_usd=0.02, duration_s=1.0)++ events = self._lines(capsys)+ assert [e["event"] for e in events] == [+ "start",+ "stage",+ "total_known",+ "page_done",+ "page_done",+ "done",+ ]+++def _split_output_runner() -> CliRunner:+ """CliRunner with stdout and stderr separated, across click versions.++ click < 8.2 mixes the streams unless ``mix_stderr=False``; click 8.2+ removed the parameter and separates them by default.+ """+ try:+ return CliRunner(mix_stderr=False) # type: ignore[call-arg]+ except TypeError:+ return CliRunner()+++class TestUpdateProgressJsonCli:+ """CliRunner smoke tests against the cheap no-provider/no-LLM early-exit paths."""++ def test_no_prior_sync_emits_start_then_error(self):+ runner = _split_output_runner()+ with tempfile.TemporaryDirectory() as td:+ os.makedirs(os.path.join(td, ".repowise"))+ result = runner.invoke(cli, ["update", td, "--progress", "json"])++ assert result.exit_code != 0+ lines = [line for line in result.stdout.splitlines() if line.strip()]+ events = [json.loads(line) for line in lines]+ assert [e["event"] for e in events] == ["start", "error"]+ assert "No previous sync found" in events[1]["message"]+ # stdout carries nothing but the two JSON lines.+ for line in lines:+ json.loads(line) # would raise if any non-JSON line leaked through++ def test_up_to_date_emits_start_stage_done(self):+ runner = _split_output_runner()+ with tempfile.TemporaryDirectory() as td:+ os.makedirs(os.path.join(td, ".repowise"))+ state_path = os.path.join(td, ".repowise", "state.json")+ with open(state_path, "w") as f:+ json.dump({"last_sync_commit": "deadbeef"}, f)++ result = runner.invoke(cli, ["update", td, "--since", "deadbeef", "--progress", "json"])++ assert result.exit_code == 0+ lines = [line for line in result.stdout.splitlines() if line.strip()]+ events = [json.loads(line) for line in lines]+ assert events[0]["event"] == "start"+ assert events[-1] == {+ "event": "done",+ "ok": True,+ "pages_generated": 0,+ "cost_usd": 0.0,+ "duration_s": events[-1]["duration_s"],+ }+ # Informational Rich output (repo header, "No changed files detected.")+ # went to stderr, not stdout.+ assert "No changed files detected" not in result.stdout+ assert "No changed files detected" in result.stderr++ def test_rich_mode_is_unaffected_default(self):+ """Default --progress rich must not emit any JSON lines."""+ runner = _split_output_runner()+ with tempfile.TemporaryDirectory() as td:+ os.makedirs(os.path.join(td, ".repowise"))+ result = runner.invoke(cli, ["update", td])++ assert result.exit_code != 0+ for line in result.stdout.splitlines():+ if line.strip():+ assert not line.strip().startswith("{")diff --git a/tests/unit/dead_code/test_reachability.py b/tests/unit/dead_code/test_reachability.pyindex d40256c0e..9bbf465b7 100644--- a/tests/unit/dead_code/test_reachability.py+++ b/tests/unit/dead_code/test_reachability.py@@ -38,6 +38,10 @@ def test_unreachable_file_detected():paths = [f.file_path for f in unreachable]assert "pkg/orphan.py" in paths+ finding = next(f for f in unreachable if f.file_path == "pkg/orphan.py")+ assert finding.start_line is None+ assert finding.end_line is None+def test_entry_point_not_flagged():"""A file marked as is_entry_point=True should NOT be flagged even with in_degree=0."""diff --git a/tests/unit/dead_code/test_unused_exports.py b/tests/unit/dead_code/test_unused_exports.pyindex d1803737d..c74edd5d7 100644--- a/tests/unit/dead_code/test_unused_exports.py+++ b/tests/unit/dead_code/test_unused_exports.py@@ -54,6 +54,10 @@ def test_unused_export_detected():sym_names = [f.symbol_name for f in unused]assert "helper_func" in sym_names+ finding = next(f for f in unused if f.symbol_name == "helper_func")+ assert finding.start_line == 1+ assert finding.end_line == 10+def test_unused_export_skipped_when_symbol_has_incoming_calls():"""A public symbol with no file-level importers but at least onediff --git a/tests/unit/distill/test_config_and_doctor.py b/tests/unit/distill/test_config_and_doctor.pyindex 49d41472a..582066213 100644--- a/tests/unit/distill/test_config_and_doctor.py+++ b/tests/unit/distill/test_config_and_doctor.py@@ -149,17 +149,17 @@ def no_real_hook(monkeypatch):monkeypatch.setattr(ClaudeCodeAdapter, "rewrite_hook_installed", lambda self: False)-def _rows(repo: Path) -> dict[str, tuple[str, str]]:- return {name: (status, detail) for name, status, detail in _distill_checks(repo)}+def _rows(repo: Path) -> dict[str, tuple[bool, str]]:+ return {check.name: (check.ok, check.detail) for check in _distill_checks(repo)}def test_doctor_defaults_all_ok(repo: Path, no_real_hook) -> None:rows = _rows(repo)- assert "OK" in rows["Distill config"][0]+ assert rows["Distill config"][0] is Trueassert rows["Distill config"][1] == "defaults (no block)"- assert "OK" in rows["Omission store"][0]+ assert rows["Omission store"][0] is Trueassert rows["Omission store"][1] == "not created yet"- assert "OK" in rows["Distill rewrite hook"][0]+ assert rows["Distill rewrite hook"][0] is Trueassert "not installed" in rows["Distill rewrite hook"][1]@@ -168,7 +168,7 @@ def test_doctor_flags_invalid_config(repo: Path, no_real_hook) -> None:"distill:\n commands:\n permission: always\n", encoding="utf-8")rows = _rows(repo)- assert "FAIL" in rows["Distill config"][0]+ assert rows["Distill config"][0] is Falseassert "permission" in rows["Distill config"][1]@@ -177,7 +177,7 @@ def test_doctor_store_within_cap(repo: Path, no_real_hook) -> None:store.put("some content", source="cli:logs", original_tokens=10, kept_tokens=2)store.close()rows = _rows(repo)- assert "OK" in rows["Omission store"][0]+ assert rows["Omission store"][0] is Trueassert "cap" in rows["Omission store"][1]@@ -191,7 +191,7 @@ def test_doctor_store_over_cap_fails(repo: Path, no_real_hook) -> None:store.put("x" * 200_000, source="cli:logs", original_tokens=10, kept_tokens=2)store.close()rows = _rows(repo)- assert "FAIL" in rows["Omission store"][0]+ assert rows["Omission store"][0] is Falseassert "over cap" in rows["Omission store"][1]diff --git a/tests/unit/server/test_dead_code.py b/tests/unit/server/test_dead_code.pyindex ea3e70c5e..60c7239ee 100644--- a/tests/unit/server/test_dead_code.py+++ b/tests/unit/server/test_dead_code.py@@ -37,6 +37,8 @@ async def _insert_dead_code(session_factory, repo_id: str) -> str:"confidence": 0.5,"reason": "No callers","lines": 10,+ "start_line": 42,+ "end_line": 51,"safe_to_delete": False,"primary_owner": "Bob","age_days": 90,@@ -69,6 +71,24 @@ async def test_list_dead_code_with_data(client: AsyncClient, app) -> None:assert len(data) == 2+async def test_list_dead_code_line_spans(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _insert_dead_code(app.state.session_factory, repo["id"])++ resp = await client.get(f"/api/repos/{repo['id']}/dead-code")+ assert resp.status_code == 200+ data = resp.json()++ unreachable = next(f for f in data if f["kind"] == "unreachable_file")+ assert unreachable["start_line"] is None+ assert unreachable["end_line"] is None++ unused_export = next(f for f in data if f["kind"] == "unused_export")+ assert unused_export["start_line"] == 42+ assert unused_export["end_line"] == 51++@pytest.mark.asyncioasync def test_list_dead_code_filter_by_kind(client: AsyncClient, app) -> None:repo = await create_test_repo(client)diff --git a/tests/unit/server/test_risk_range.py b/tests/unit/server/test_risk_range.pynew file mode 100644index 000000000..a08528a98--- /dev/null+++ b/tests/unit/server/test_risk_range.py@@ -0,0 +1,124 @@+"""Tests for the live base..head change-risk endpoint."""++from __future__ import annotations++import subprocess+from pathlib import Path++import pytest+from httpx import AsyncClient++from repowise.core.analysis.change_risk import baseline_scores+from tests.unit.server.conftest import create_test_repo+++def _git(args: list[str], cwd: Path) -> None:+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True)+++def _commit(repo: Path, files: dict[str, str], message: str, author: str = "Dev") -> str:+ for rel, content in files.items():+ p = repo / rel+ p.parent.mkdir(parents=True, exist_ok=True)+ p.write_text(content, encoding="utf-8")+ _git(["add", rel], repo)+ _git(["-c", f"user.name={author}", "-c", "[email protected]", "commit", "-m", message], repo)+ return subprocess.run(+ ["git", "rev-parse", "HEAD"], cwd=repo, check=True, capture_output=True, text=True+ ).stdout.strip()+++def git_repo(tmp_path: Path) -> Path:+ """A real, tiny git repo at ``tmp_path/test-repo`` (the name expected by+ :func:`create_test_repo`), with a few commits scored to a base..head+ range."""+ repo = tmp_path / "test-repo"+ repo.mkdir()+ _git(["init", "-q"], repo)+ _git(["config", "user.name", "Seed"], repo)+ _git(["config", "user.email", "[email protected]"], repo)+ _commit(repo, {"README.md": "# seed\n"}, "chore: seed", author="Seed")+ return repo+++async def _register(client: AsyncClient, tmp_path: Path) -> dict:+ return await create_test_repo(client, tmp_path)+++async def test_risk_range_happy_path(client: AsyncClient, git_repo: Path, tmp_path: Path) -> None:+ base = subprocess.run(+ ["git", "rev-parse", "HEAD"], cwd=git_repo, check=True, capture_output=True, text=True+ ).stdout.strip()+ _commit(git_repo, {"src/a.py": "x = 1\ny = 2\n"}, "feat: add a")+ _commit(git_repo, {"src/b.py": "z = 3\n"}, "fix: handle null crash")++ repo = await _register(client, tmp_path)+ resp = await client.get(+ f"/api/repos/{repo['id']}/risk/range",+ params={"base": base, "head": "HEAD"},+ )+ assert resp.status_code == 200+ data = resp.json()++ assert data["base"] == base+ assert data["head"] == "HEAD"+ assert 0.0 <= data["score"] <= 10.0+ assert 0.0 <= data["probability"] <= 1.0+ assert data["level"] in {"low", "moderate", "high"}+ assert data["is_fix"] is True+ assert data["features"]["nf"] == 2+ assert data["features"]["la"] == 3+ assert isinstance(data["drivers"], list) and len(data["drivers"]) > 0+ # Only two commits sampled, below _MIN_BASELINE, so no percentile.+ assert data["risk_percentile"] is None+ assert data["review_priority"] is None+++async def test_risk_range_unknown_repo(client: AsyncClient) -> None:+ resp = await client.get(+ "/api/repos/does-not-exist/risk/range",+ params={"base": "HEAD~1", "head": "HEAD"},+ )+ assert resp.status_code == 404+++async def test_risk_range_bad_revspec(client: AsyncClient, git_repo: Path, tmp_path: Path) -> None:+ repo = await _register(client, tmp_path)+ resp = await client.get(+ f"/api/repos/{repo['id']}/risk/range",+ params={"base": "totally-bogus-rev", "head": "HEAD"},+ )+ assert resp.status_code == 400+++async def test_risk_range_baseline_zero_skips_percentile(+ client: AsyncClient, git_repo: Path, tmp_path: Path+) -> None:+ base = subprocess.run(+ ["git", "rev-parse", "HEAD"], cwd=git_repo, check=True, capture_output=True, text=True+ ).stdout.strip()+ _commit(git_repo, {"src/c.py": "a = 1\n"}, "feat: add c")++ repo = await _register(client, tmp_path)+ resp = await client.get(+ f"/api/repos/{repo['id']}/risk/range",+ params={"base": base, "head": "HEAD", "baseline": 0},+ )+ assert resp.status_code == 200+ data = resp.json()+ assert data["risk_percentile"] is None+ assert data["review_priority"] is None+++def test_baseline_scores_returns_floats(git_repo: Path) -> None:+ _commit(git_repo, {"src/d.py": "a = 1\nb = 2\n"}, "feat: add d")+ _commit(git_repo, {"src/e.py": "c = 3\n"}, "fix: crash on null")++ scores = baseline_scores(str(git_repo), "HEAD", 200, (), "")+ assert len(scores) >= 1+ assert all(isinstance(s, float) for s in scores)