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
fix: use canonical workspace graph health score (#441)
joptimuse3b8d90d2c16
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.pyindex a31fbba27..b5dce0ea4 100644--- a/packages/server/src/repowise/server/routers/workspace.py+++ b/packages/server/src/repowise/server/routers/workspace.py@@ -7,7 +7,6 @@ startup from ``.repowise-workspace/`` JSON files) — no DB access needed.from __future__ import annotations-import asyncioimport loggingimport sqlite3from pathlib import Path@@ -16,7 +15,6 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Requestfrom repowise.server.deps import (get_cross_repo_enricher,- get_db_session,get_workspace_config,resolve_session_factory,verify_api_key,@@ -35,6 +33,7 @@ from repowise.server.schemas import (WorkspaceRepoEntry,WorkspaceResponse,)+from repowise.server.services.module_health import read_repo_health_scorerouter = APIRouter(prefix="/api/workspace",@@ -78,6 +77,22 @@ def _compute_health_score(file_count: int, doc_coverage_pct: float, hotspot_counreturn max(0, min(100, round(coverage_component + hotspot_component)))+def _resolve_graph_health_score(db_path: Path, stats: dict) -> tuple[float, str]:+ canonical = read_repo_health_score(db_path)+ if canonical is not None:+ return canonical, "canonical"+ return (+ float(+ _compute_health_score(+ stats.get("file_count", 0),+ stats.get("doc_coverage_pct", 0.0),+ stats.get("hotspot_count", 0),+ )+ ),+ "derived",+ )++def _query_repo_stats(db_path: Path) -> dict:"""Query basic stats from a repo's wiki.db using raw sqlite3.@@ -380,6 +395,10 @@ async def get_workspace_graph(db_path = repo_path / ".repowise" / "wiki.db"stats = _query_repo_stats(db_path)top_language = _query_top_language(db_path)+ health_score, health_score_source = _resolve_graph_health_score(db_path, stats)+ else:+ health_score = 0.0+ health_score_source = "derived"rid = stats.get("repo_id") or r.aliasrepo_id_map[r.alias] = ridnodes.append(@@ -388,11 +407,8 @@ async def get_workspace_graph(name=r.alias,file_count=stats.get("file_count", 0),coverage_pct=stats.get("doc_coverage_pct", 0.0),- health_score=_compute_health_score(- stats.get("file_count", 0),- stats.get("doc_coverage_pct", 0.0),- stats.get("hotspot_count", 0),- ),+ health_score=health_score,+ health_score_source=health_score_source,top_language=top_language,))@@ -489,11 +505,12 @@ async def sync_workspace(_require_workspace(ws_config)+ from sqlalchemy import select+from repowise.core.persistence import crudfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import GenerationJobfrom repowise.server.routers.repos import _launch_job_task- from sqlalchemy import selectws_root = getattr(request.app.state, "workspace_root", None)if ws_root is None:@@ -584,7 +601,7 @@ async def sync_workspace()await session.commit()return job.id, None- except Exception as exc: # noqa: BLE001+ except Exception as exc:return None, str(exc)job_id, err = await _create_job()diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.pyindex 895056a06..e8c47141f 100644--- a/packages/server/src/repowise/server/schemas/workspace.py+++ b/packages/server/src/repowise/server/schemas/workspace.py@@ -123,7 +123,8 @@ class WorkspaceGraphNode(BaseModel):name: strfile_count: int = 0coverage_pct: float = 0.0- health_score: int = 0+ health_score: float = 0.0+ health_score_source: str = "derived"top_language: str = "unknown"diff --git a/packages/server/src/repowise/server/services/module_health.py b/packages/server/src/repowise/server/services/module_health.pyindex 1a57a5bf5..e5f6f3d49 100644--- a/packages/server/src/repowise/server/services/module_health.py+++ b/packages/server/src/repowise/server/services/module_health.py@@ -12,15 +12,16 @@ arbitrarily deep.from __future__ import annotationsimport json+import sqlite3from collections import Counter, defaultdictfrom dataclasses import dataclass, field+from pathlib import Pathfrom statistics import median+from sqlalchemy import func as sa_funcfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession-from sqlalchemy import func as sa_func-from repowise.core.persistence.models import (DeadCodeFinding,DecisionRecord,@@ -99,7 +100,7 @@ def _score(acc: _ModuleAccumulator) -> dict:primary_owner = nameprimary_pct = cnt / file_count if file_count else 0.0- # Composite health (0–100). Higher is better. Weighted:+ # Composite health (0-100). Higher is better. Weighted:# -25 if siloed (>80% one owner)# -20 * (hotspot_count / file_count)# -25 * dead_pct@@ -252,6 +253,38 @@ def detail_extras(acc: _ModuleAccumulator) -> dict:}+def read_repo_health_score(db_path: Path) -> float | None:+ """Return the canonical repo health score from a repo-local wiki.db."""+ if not db_path.exists():+ return None+ try:+ with sqlite3.connect(str(db_path)) as conn:+ row = conn.execute(+ "SELECT score, COALESCE(nloc, 1) FROM health_file_metrics"+ ).fetchall()+ except sqlite3.OperationalError:+ return None+ except Exception:+ return None++ if not row:+ return None++ weights = [max(int(nloc or 0), 1) for _, nloc in row]+ total_weight = sum(weights)+ if total_weight:+ average = (+ sum(+ float(score) * weight+ for (score, _), weight in zip(row, weights, strict=True)+ )+ / total_weight+ )+ else:+ average = sum(float(score) for score, _ in row) / len(row)+ return max(0.0, min(100.0, round(average * 10.0, 1)))++async def build_single_file_health(session: AsyncSession, repo_id: str, file_path: str) -> dict | None:diff --git a/packages/ui/src/workspace/workspace-graph-node.tsx b/packages/ui/src/workspace/workspace-graph-node.tsxindex 1df6094ca..8b18ba5a7 100644--- a/packages/ui/src/workspace/workspace-graph-node.tsx+++ b/packages/ui/src/workspace/workspace-graph-node.tsx@@ -11,6 +11,7 @@ export interface WorkspaceGraphNodeData {fileCount: number;coveragePct: number;healthScore: number;+ healthScoreSource: "canonical" | "derived";topLanguage: string;}@@ -20,14 +21,29 @@ function healthColor(score: number): string {return "var(--color-risk-high)";}-function HealthRing({ score, size = 36 }: { score: number; size?: number }) {+function HealthRing({+ score,+ source,+ size = 36,+}: {+ score: number;+ source: "canonical" | "derived";+ size?: number;+}) {const r = (size - 4) / 2;const circ = 2 * Math.PI * r;const offset = circ * (1 - score / 100);const color = healthColor(score);+ const label = source === "derived" ? "Estimated health score" : "Health score";return (- <svg width={size} height={size} className="shrink-0">+ <svg+ width={size}+ height={size}+ className="shrink-0"+ aria-label={`${label}: ${Math.round(score)}`}+ >+ <title>{label}</title><circlecx={size / 2}cy={size / 2}@@ -57,7 +73,7 @@ function HealthRing({ score, size = 36 }: { score: number; size?: number }) {fontSize={10}fontWeight={700}>- {score}+ {Math.round(score)}</text></svg>);@@ -90,7 +106,12 @@ function WorkspaceGraphNodeInner({ data }: NodeProps) {</div><div className="flex items-center gap-2.5">- <HealthRing score={d.healthScore} />+ <div className="flex flex-col items-center gap-0.5">+ <HealthRing score={d.healthScore} source={d.healthScoreSource} />+ <span className="text-[8px] font-medium uppercase tracking-wide text-[var(--color-text-tertiary)]">+ {d.healthScoreSource === "derived" ? "est." : "health"}+ </span>+ </div><div className="flex-1 min-w-0 space-y-1"><div className="flex items-center gap-1 text-[10px] text-[var(--color-text-secondary)]"><FileText className="w-3 h-3 shrink-0" />diff --git a/packages/ui/src/workspace/workspace-graph.tsx b/packages/ui/src/workspace/workspace-graph.tsxindex 4a457bfe1..7dc6f8674 100644--- a/packages/ui/src/workspace/workspace-graph.tsx+++ b/packages/ui/src/workspace/workspace-graph.tsx@@ -27,6 +27,7 @@ export interface WorkspaceGraphData {file_count: number;coverage_pct: number;health_score: number;+ health_score_source?: "canonical" | "derived";top_language: string;}>;edges: Array<{@@ -90,6 +91,7 @@ function computeLayout(data: WorkspaceGraphData): { nodes: Node[]; edges: Edge[]fileCount: apiNode.file_count,coveragePct: apiNode.coverage_pct,healthScore: apiNode.health_score,+ healthScoreSource: apiNode.health_score_source ?? "derived",topLanguage: apiNode.top_language,} satisfies WorkspaceGraphNodeData,};diff --git a/packages/web/src/lib/api/types/workspace.ts b/packages/web/src/lib/api/types/workspace.tsindex 455ba9852..1b121eafb 100644--- a/packages/web/src/lib/api/types/workspace.ts+++ b/packages/web/src/lib/api/types/workspace.ts@@ -108,6 +108,7 @@ export interface WorkspaceGraphNode {file_count: number;coverage_pct: number;health_score: number;+ health_score_source: "canonical" | "derived";top_language: string;}diff --git a/tests/unit/server/test_workspace_router.py b/tests/unit/server/test_workspace_router.pyindex 887457ef0..502254cd7 100644--- a/tests/unit/server/test_workspace_router.py+++ b/tests/unit/server/test_workspace_router.py@@ -3,6 +3,7 @@from __future__ import annotationsimport json+import sqlite3from contextlib import asynccontextmanagerfrom pathlib import Pathfrom unittest.mock import MagicMock@@ -15,7 +16,6 @@ from httpx import ASGITransport, AsyncClientfrom repowise.server.mcp_server._enrichment import CrossRepoEnricherfrom repowise.server.routers import workspace-# ---------------------------------------------------------------------------# Fixtures# ---------------------------------------------------------------------------@@ -155,6 +155,50 @@ def _make_enricher(tmp_path: Path) -> CrossRepoEnricher:return CrossRepoEnricher(cross_repo_path, contracts_path=contracts_path)+def _create_workspace_repo_db(+ workspace_root: Path,+ repo_alias: str,+ *,+ health_rows: list[tuple[float, int]] | None = None,+) -> None:+ repo_dir = workspace_root / repo_alias / ".repowise"+ repo_dir.mkdir(parents=True)+ db_path = repo_dir / "wiki.db"+ with sqlite3.connect(str(db_path)) as conn:+ conn.executescript(+ """+ CREATE TABLE repositories (id TEXT PRIMARY KEY);+ CREATE TABLE graph_nodes (+ id TEXT PRIMARY KEY,+ language TEXT,+ symbol_count INTEGER DEFAULT 0+ );+ CREATE TABLE wiki_pages (id TEXT PRIMARY KEY, confidence REAL);+ CREATE TABLE git_metadata (id TEXT PRIMARY KEY, churn_percentile REAL);+ CREATE TABLE health_file_metrics (+ id TEXT PRIMARY KEY,+ score REAL NOT NULL,+ nloc INTEGER NOT NULL+ );+ INSERT INTO repositories (id) VALUES ('repo-backend');+ INSERT INTO graph_nodes (id, language, symbol_count) VALUES+ ('src/a.py', 'python', 2),+ ('src/b.py', 'python', 3);+ INSERT INTO wiki_pages (id, confidence) VALUES+ ('page-a', 0.8),+ ('page-b', 0.6);+ INSERT INTO git_metadata (id, churn_percentile) VALUES+ ('src/a.py', 95.0),+ ('src/b.py', 10.0);+ """+ )+ for idx, (score, nloc) in enumerate(health_rows or []):+ conn.execute(+ "INSERT INTO health_file_metrics (id, score, nloc) VALUES (?, ?, ?)",+ (f"metric-{idx}", score, nloc),+ )++# ---------------------------------------------------------------------------# Tests — GET /api/workspace# ---------------------------------------------------------------------------@@ -393,7 +437,7 @@ class TestGetCoChanges:@pytest.mark.asyncioasync def test_no_enricher(self) -> None:- """Workspace mode but no enricher → empty."""+ """Workspace mode but no enricher -> empty."""ws_config = _make_ws_config()app = _make_workspace_app(ws_config=ws_config)transport = ASGITransport(app=app)@@ -402,3 +446,51 @@ class TestGetCoChanges:assert resp.status_code == 200data = resp.json()assert data["total"] == 0+++# ---------------------------------------------------------------------------+# Tests — GET /api/workspace/graph+# ---------------------------------------------------------------------------+++class TestGetWorkspaceGraph:+ @pytest.mark.asyncio+ async def test_uses_canonical_health_score_from_repo_metrics(self, tmp_path: Path) -> None:+ ws_config = _make_ws_config()+ _create_workspace_repo_db(+ tmp_path,+ "backend",+ health_rows=[(2.0, 10), (9.0, 30)],+ )+ app = _make_workspace_app(+ ws_config=ws_config,+ workspace_root=str(tmp_path),+ )+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://test") as c:+ resp = await c.get("/api/workspace/graph")++ assert resp.status_code == 200+ backend = next(n for n in resp.json()["nodes"] if n["name"] == "backend")+ assert backend["health_score"] == 72.5+ assert backend["health_score_source"] == "canonical"++ @pytest.mark.asyncio+ async def test_marks_derived_health_score_when_repo_metrics_are_missing(+ self,+ tmp_path: Path,+ ) -> None:+ ws_config = _make_ws_config()+ _create_workspace_repo_db(tmp_path, "backend")+ app = _make_workspace_app(+ ws_config=ws_config,+ workspace_root=str(tmp_path),+ )+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://test") as c:+ resp = await c.get("/api/workspace/graph")++ assert resp.status_code == 200+ backend = next(n for n in resp.json()["nodes"] if n["name"] == "backend")+ assert backend["health_score"] == 62.0+ assert backend["health_score_source"] == "derived"