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(ui): label dashboard figures for what they measure (#4368)
Raghav Chamadiya323923a12471
diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.mdindex 6cfdfcf45..021afc7bd 100644--- a/docs/scale/WORKSPACES.md+++ b/docs/scale/WORKSPACES.md@@ -344,7 +344,7 @@ repowise serveIn workspace mode, the web UI adds:-- **Workspace Dashboard** (`/workspace`), aggregate stats across all repos, repo cards with file/symbol/coverage counts, and cross-repo intelligence summary+- **Workspace Dashboard** (`/workspace`), aggregate stats across all repos, repo rows with code health, file, hotspot and doc freshness counts, and cross-repo intelligence summary. Doc freshness is fresh pages over all pages.- **System Map** (`/workspace/system-map`), the [Live System Map](#live-system-map): a code-derived diagram of services and their typed relationships- **Contracts View** (`/workspace/contracts`), all detected API contracts with provider/consumer matching, filterable by type and repo- **Co-Changes View** (`/workspace/co-changes`), cross-repo file pairs ranked by co-change strength@@ -355,7 +355,7 @@ The sidebar shows all workspace repos under **Repositories**. Click any repo toThe System Map renders the [system graph](#system-graph) as an always-current diagram. It is the visual counterpart to the REST endpoint, the same nodes and edges, laid out and explorable, never a hand-drawn picture.-- **Service nodes**, coloured by category (service, frontend, worker, library, external), with a health ring rolled up from the owning repo and small flags for orphan or isolated services.+- **Service nodes**, coloured by category (service, frontend, worker, library, external), with the owning repo's code health score ("No health score" when health has not scored that repo) and small flags for orphan or isolated services.- **Typed edges** distinguished by `kind` (colour + glyph) and by `match_type` (solid for exact/manual, dashed for candidate, dotted for inferred co-change). Behavioral co-change edges read differently from structural contract/dependency edges.- **Filters** to toggle each edge kind on or off, and a **service / repo** switch that collapses a monorepo's services into one node per repository.- **Drill-down**: click a service to inspect its providers/consumers and connected services; click an edge to see its match type, confidence, weight, and the underlying contract evidence, with a jump to the Contracts view.diff --git a/packages/api-client/src/types/workspace.ts b/packages/api-client/src/types/workspace.tsindex 65da44a5b..52552a9ba 100644--- a/packages/api-client/src/types/workspace.ts+++ b/packages/api-client/src/types/workspace.ts@@ -13,6 +13,9 @@ export interface WorkspaceRepoEntry {file_count: number;symbol_count: number;page_count: number;+ // Pages whose freshness status is fresh, out of `page_count`.+ fresh_page_count: number;+ // Mean wiki page confidence, 0-100. Not a share of files documented.doc_coverage_pct: number;hotspot_count: number;// Canonical 0-100 health score. Optional so a frontend ahead of its server@@ -202,9 +205,10 @@ export interface WorkspaceGraphNode {repo_id: string;name: string;file_count: number;+ /** Mean wiki page confidence, 0-100. */coverage_pct: number;- health_score: number;- health_score_source: "canonical" | "derived";+ /** Code health, 0-100; null when health has not scored the repo. */+ health_score: number | null;top_language: string;}diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.pyindex f488c2a3b..fdc477d97 100644--- a/packages/server/src/repowise/server/routers/workspace.py+++ b/packages/server/src/repowise/server/routers/workspace.py@@ -91,47 +91,23 @@ def _query_top_language(db_path: Path) -> str:return "unknown"-def _compute_health_score(file_count: int, doc_coverage_pct: float, hotspot_count: int) -> int:- """Derive a 0-100 health score from available repo metrics."""- if file_count == 0:- return 0- coverage_component = doc_coverage_pct * 0.6- hotspot_ratio = min(hotspot_count / max(file_count, 1), 1.0)- hotspot_component = (1.0 - hotspot_ratio) * 100 * 0.4- return max(0, min(100, round(coverage_component + hotspot_component)))---def _resolve_graph_health_score(stats: dict) -> tuple[float, str]:- canonical = stats.get("health_score")- 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.Returns a dict with repo_id, file_count, symbol_count, page_count,- doc_coverage_pct, hotspot_count, health_score, status, docs_enabled,- docs_skip_reason, and (when the row is read) indexed_at. All values default to sensible neutrals on error.+ fresh_page_count, doc_coverage_pct, hotspot_count, health_score, status,+ docs_enabled, docs_skip_reason, and (when the row is read) indexed_at.+ All values default to sensible neutrals on error.- ``health_score`` is None when the repo carries no health metrics; callers- decide whether to fall back to a derived score or to render nothing.+ ``health_score`` is None when the repo carries no health metrics, and+ stays None: no other figure here measures code health."""result: dict = {"repo_id": None,"file_count": 0,"symbol_count": 0,"page_count": 0,+ "fresh_page_count": 0,"doc_coverage_pct": 0.0,"hotspot_count": 0,"health_score": None,@@ -174,13 +150,14 @@ def _query_repo_stats(db_path: Path) -> dict:row = c.execute("SELECT COUNT(*) FROM wiki_symbols").fetchone()result["symbol_count"] = int(row[0]) if row else 0- # page count- row = c.execute("SELECT COUNT(*) FROM wiki_pages").fetchone()- result["page_count"] = row[0] if row else 0-- # doc coverage (avg confidence * 100)- row = c.execute("SELECT AVG(confidence) FROM wiki_pages").fetchone()- result["doc_coverage_pct"] = round(float(row[0] or 0.0) * 100, 1)+ # Pages, fresh pages, and mean page confidence * 100. The last is named+ # doc_coverage_pct on the wire; it is not a share of files documented.+ pages, fresh, confidence = c.execute(+ "SELECT COUNT(*), SUM(freshness_status = 'fresh'), AVG(confidence) FROM wiki_pages"+ ).fetchone()+ result["page_count"] = pages+ result["fresh_page_count"] = int(fresh or 0)+ result["doc_coverage_pct"] = round(float(confidence or 0.0) * 100, 1)# hotspot count — use the canonical is_hotspot flag, matching the rest# of the codebase (module_health, extract-demo-data). The earlier@@ -460,10 +437,6 @@ 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(stats)- else:- health_score = 0.0- health_score_source = "derived"rid = stats.get("repo_id") or r.aliasrepo_id_map[r.alias] = ridnodes.append(@@ -472,8 +445,7 @@ 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=health_score,- health_score_source=health_score_source,+ health_score=stats.get("health_score"),top_language=top_language,))diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.pyindex a19ac8154..c31d62593 100644--- a/packages/server/src/repowise/server/schemas/workspace.py+++ b/packages/server/src/repowise/server/schemas/workspace.py@@ -26,6 +26,9 @@ class WorkspaceRepoEntry(BaseModel):file_count: int = 0symbol_count: int = 0page_count: int = 0+ # Pages whose freshness status is fresh, out of ``page_count``.+ fresh_page_count: int = 0+ # Mean wiki page confidence, 0-100. Not a share of files documented.doc_coverage_pct: float = 0.0hotspot_count: int = 0# Canonical 0-100 health score, or None when the repo carries no health@@ -212,9 +215,10 @@ class WorkspaceGraphNode(BaseModel):repo_id: strname: strfile_count: int = 0+ #: Mean wiki page confidence, 0-100, like the entry's ``doc_coverage_pct``.coverage_pct: float = 0.0- health_score: float = 0.0- health_score_source: str = "derived"+ #: The repo's code health, 0-100; None when health has not scored it.+ health_score: float | None = Nonetop_language: str = "unknown"diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 850b87e79..52aba6f45 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -4671,8 +4671,7 @@ export interface WorkspaceGraphNode {name: string;file_count?: number;coverage_pct?: number;- health_score?: number;- health_score_source?: string;+ health_score?: number | null;top_language?: string;}@@ -4761,6 +4760,7 @@ export interface WorkspaceRepoEntry {file_count?: number;symbol_count?: number;page_count?: number;+ fresh_page_count?: number;doc_coverage_pct?: number;hotspot_count?: number;health_score?: number | null;diff --git a/packages/ui/COMPONENT_CONTRACTS.md b/packages/ui/COMPONENT_CONTRACTS.mdindex 7a2b8693c..1503e8df9 100644--- a/packages/ui/COMPONENT_CONTRACTS.md+++ b/packages/ui/COMPONENT_CONTRACTS.md@@ -794,7 +794,7 @@ role (`provider` / `consumer`).### `workspace/repo-card` — `RepoCard`-Tile linking to `/repos/{id}/overview` with file count, doc-coverage,+Tile linking to `/repos/{id}/overview` with file count, doc confidence,hotspot count, and a primary indicator.| Prop | Type | Required |diff --git a/packages/ui/__tests__/overview/overview-body.test.tsx b/packages/ui/__tests__/overview/overview-body.test.tsxindex eb5d8ca3a..f638446a9 100644--- a/packages/ui/__tests__/overview/overview-body.test.tsx+++ b/packages/ui/__tests__/overview/overview-body.test.tsx@@ -5,7 +5,7 @@ import type { OverviewSummaryResponse } from "@repowise-dev/types/overview";import { AttentionAreas } from "../../src/overview/attention-areas.js";import { HealthLede } from "../../src/overview/health-lede.js";import { OverviewBody } from "../../src/overview/overview-body.js";-import { buildReads, inventoryRows } from "../../src/overview/overview-model.js";+import { buildExplore, buildReads, inventoryRows } from "../../src/overview/overview-model.js";function summary(): OverviewSummaryResponse {return {@@ -225,7 +225,8 @@ describe("inventoryRows", () => {it("counts each area on the same basis as its card and page", () => {const rows = inventoryRows({...summary(),- health: { ...summary().health, finding_counts: { inventory: 321 } },+ // The queue inventory is lower; the row prints the open_findings headline.+ health: { ...summary().health, open_findings: 321, finding_counts: { inventory: 200 } },attention_summary: {total: 99,by_source: {},@@ -256,6 +257,17 @@ describe("inventoryRows", () => {});});+describe("buildExplore", () => {+ it("names the open_findings headline on the code health door, not the queue inventory", () => {+ const s = summary();+ const entries = buildExplore(+ { ...s, health: { ...s.health, open_findings: 13563, finding_counts: { inventory: 11371 } } } as unknown as OverviewSummaryResponse,+ { base: "/r" },+ );+ expect(entries.find((e) => e.key === "code-health")?.description).toContain("13,563 open findings");+ });+});+describe("AttentionAreas", () => {it("shows the worst item's severity once, as a dot and a word, with no hidden copy", () => {render(diff --git a/packages/ui/__tests__/workspace/repo-card.test.tsx b/packages/ui/__tests__/workspace/repo-card.test.tsxnew file mode 100644index 000000000..cdbccdc5d--- /dev/null+++ b/packages/ui/__tests__/workspace/repo-card.test.tsx@@ -0,0 +1,56 @@+import { describe, expect, it } from "vitest";+import { render, screen } from "@testing-library/react";+import { ReactFlowProvider } from "@xyflow/react";+import type { NodeProps } from "@xyflow/react";++import { RepoCard } from "../../src/workspace/repo-card.js";+import { WorkspaceGraphNode } from "../../src/workspace/workspace-graph-node.js";++describe("RepoCard", () => {+ it("names the figure as doc confidence, floored", () => {+ render(+ <RepoCard+ repoId="r1"+ alias="api"+ name="api"+ path="./api"+ isPrimary={false}+ stats={{ file_count: 12, doc_coverage_pct: 99.8 }}+ gitSummary={{ hotspot_count: 3 }}+ />,+ );+ expect(screen.getByText("99% doc confidence")).toBeInTheDocument();+ expect(screen.queryByText(/% docs$/)).toBeNull();+ });+});++function renderNode(healthScore: number | null) {+ const data = {+ repoId: "r1",+ name: "api",+ fileCount: 12,+ coveragePct: 99.8,+ healthScore,+ topLanguage: "python",+ };+ return render(+ <ReactFlowProvider>+ <WorkspaceGraphNode {...({ data } as unknown as NodeProps)} />+ </ReactFlowProvider>,+ );+}++describe("WorkspaceGraphNode", () => {+ it("labels mean page confidence as doc confidence, not coverage", () => {+ renderNode(72);+ expect(screen.getByText("99% doc conf.")).toBeInTheDocument();+ expect(screen.queryByText(/% cov$/)).toBeNull();+ expect(screen.getByLabelText("Health score: 72")).toBeInTheDocument();+ });++ it("shows no score for a repo health has not scored", () => {+ renderNode(null);+ expect(screen.getByText("no score")).toBeInTheDocument();+ expect(screen.queryByLabelText(/Health score/)).toBeNull();+ });+});diff --git a/packages/ui/src/overview/overview-model.ts b/packages/ui/src/overview/overview-model.tsindex e0e2855ce..b49fc8075 100644--- a/packages/ui/src/overview/overview-model.ts+++ b/packages/ui/src/overview/overview-model.ts@@ -386,7 +386,7 @@ export function buildExplore(key: "code-health",label: "Code health",href: `${r.base}/code-health`,- description: `Per-file scores, ${formatNumber(health.finding_counts?.inventory ?? health.open_findings)} open findings, coverage and refactoring targets`,+ description: `Per-file scores, ${formatNumber(health.open_findings)} open findings, coverage and refactoring targets`,},{key: "knowledge-graph",@@ -456,11 +456,15 @@ export type InventoryRow = OverviewAttentionAreaRow & { unit?: string };* matches in shipped source for security, open opportunities for* refactoring, decisions to review, and sole-owned files for ownership. Rows* whose basis the payload does not carry keep the server's count.+ *+ * Open findings is `open_findings`, the total get_overview and `repowise+ * health` print. The queue's `finding_counts.inventory` leaves zero-impact+ * findings out, so it is not the number those surfaces call open findings.*/export function inventoryRows(summary: OverviewSummaryResponse): InventoryRow[] {const areas = summary.attention_summary?.areas ?? [];const explore = summary.explore;- const findings = summary.health.finding_counts?.inventory;+ const findings = summary.health.open_findings;return areas.map((area): InventoryRow => {switch (area.key) {case "health":diff --git a/packages/ui/src/workspace/repo-card.tsx b/packages/ui/src/workspace/repo-card.tsxindex 8594a0973..9b80d6941 100644--- a/packages/ui/src/workspace/repo-card.tsx+++ b/packages/ui/src/workspace/repo-card.tsx@@ -89,8 +89,12 @@ export function RepoCard({</div><div className="flex items-center gap-1.5"><BarChart3 className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />- <span className="text-xs text-[var(--color-text-secondary)]">- {stats ? `${Math.round(stats.doc_coverage_pct)}% docs` : "—"}+ {/* `doc_coverage_pct` is mean page confidence, not a share of files documented. */}+ <span+ className="text-xs text-[var(--color-text-secondary)]"+ title="Average confidence of the generated doc pages"+ >+ {stats ? `${Math.floor(stats.doc_coverage_pct)}% doc confidence` : "—"}</span></div><div className="flex items-center gap-1.5">diff --git a/packages/ui/src/workspace/system-map/types.ts b/packages/ui/src/workspace/system-map/types.tsindex dff9e6721..4750f173a 100644--- a/packages/ui/src/workspace/system-map/types.ts+++ b/packages/ui/src/workspace/system-map/types.ts@@ -9,10 +9,8 @@ import type { SystemEdge, SystemNode } from "@repowise-dev/types";/** Repo-level health, joined client-side onto service nodes by repo alias. */export interface RepoHealth {- /** 0-100 health score. */+ /** 0-100 code health score. */score: number;- /** Whether the score is canonical (computed) or derived (estimated). */- source: "canonical" | "derived";}/** React Flow node payload — the `SystemNode` plus its joined health, if any. */diff --git a/packages/ui/src/workspace/workspace-graph-node.tsx b/packages/ui/src/workspace/workspace-graph-node.tsxindex 635dca431..fb8c85529 100644--- a/packages/ui/src/workspace/workspace-graph-node.tsx+++ b/packages/ui/src/workspace/workspace-graph-node.tsx@@ -10,9 +10,10 @@ export interface WorkspaceGraphNodeData {repoId: string;name: string;fileCount: number;+ /** Mean wiki page confidence, 0-100. */coveragePct: number;- healthScore: number;- healthScoreSource: "canonical" | "derived";+ /** Code health, 0-100; null when health has not scored the repo. */+ healthScore: number | null;topLanguage: string;}@@ -20,20 +21,12 @@ export function healthColor(score: number): string {return healthInk100(score);}-export function HealthRing({- score,- source,- size = 36,-}: {- score: number;- source: "canonical" | "derived";- size?: number;-}) {+export function HealthRing({ score, size = 36 }: { score: number; 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";+ const label = "Health score";return (<svg@@ -78,6 +71,21 @@ export function HealthRing({);}+function HealthCell({ score }: { score: number | null }) {+ return (+ <div className="flex flex-col items-center gap-0.5">+ {score != null ? (+ <HealthRing score={score} />+ ) : (+ <span className="text-[10px] text-[var(--color-text-tertiary)]">—</span>+ )}+ <span className="text-[8px] font-medium uppercase tracking-wide text-[var(--color-text-tertiary)]">+ {score != null ? "health" : "no score"}+ </span>+ </div>+ );+}+function WorkspaceGraphNodeInner({ data }: NodeProps) {const d = data as unknown as WorkspaceGraphNodeData;const langColor = languageColor(d.topLanguage);@@ -105,12 +113,7 @@ function WorkspaceGraphNodeInner({ data }: NodeProps) {</div><div className="flex items-center gap-2.5">- <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>+ <HealthCell score={d.healthScore} /><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" />@@ -118,7 +121,9 @@ function WorkspaceGraphNodeInner({ data }: NodeProps) {</div><div className="flex items-center gap-1 text-[10px] text-[var(--color-text-secondary)]"><BarChart3 className="w-3 h-3 shrink-0" />- <span>{Math.round(d.coveragePct)}% cov</span>+ <span title="Average confidence of the generated doc pages">+ {Math.floor(d.coveragePct)}% doc conf.+ </span></div></div></div>diff --git a/packages/ui/src/workspace/workspace-graph.tsx b/packages/ui/src/workspace/workspace-graph.tsxindex 7dc6f8674..3fca974d7 100644--- a/packages/ui/src/workspace/workspace-graph.tsx+++ b/packages/ui/src/workspace/workspace-graph.tsx@@ -26,8 +26,7 @@ export interface WorkspaceGraphData {name: string;file_count: number;coverage_pct: number;- health_score: number;- health_score_source?: "canonical" | "derived";+ health_score: number | null;top_language: string;}>;edges: Array<{@@ -91,7 +90,6 @@ 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/messages/en.json b/packages/web/messages/en.jsonindex d5962237e..f877211ca 100644--- a/packages/web/messages/en.json+++ b/packages/web/messages/en.json@@ -925,7 +925,7 @@"symbolsSub": "functions, classes and methods","docFreshness": "Doc freshness","docFreshnessNoPages": "no documentation generated yet",- "docFreshnessSub": "weighted across {pages} pages",+ "docFreshnessSub": "{fresh} of {pages} pages fresh","hotspots": "Hotspots","hotspotsSub": "files by churn and prior fixes","contractLinks": "Contract links",diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.jsonindex a71f9fde0..93651c8e8 100644--- a/packages/web/messages/zh-CN.json+++ b/packages/web/messages/zh-CN.json@@ -925,7 +925,7 @@"symbolsSub": "函数、类与方法","docFreshness": "文档新鲜度","docFreshnessNoPages": "尚未生成文档",- "docFreshnessSub": "按 {pages} 页加权",+ "docFreshnessSub": "{fresh} / {pages} 页为最新","hotspots": "热点","hotspotsSub": "按改动频率与历史修复排序的文件","contractLinks": "契约链接",diff --git a/packages/web/src/app/workspace/doc-freshness.test.ts b/packages/web/src/app/workspace/doc-freshness.test.tsnew file mode 100644index 000000000..947deac3f--- /dev/null+++ b/packages/web/src/app/workspace/doc-freshness.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from "vitest";+import { createTranslator } from "next-intl";+import { workspaceDocFreshness } from "./doc-freshness";+import en from "../../../messages/en.json";+import zhCN from "../../../messages/zh-CN.json";++describe("workspaceDocFreshness", () => {+ it("is fresh pages over all pages, not mean page confidence", () => {+ const repos = [+ { page_count: 7253, fresh_page_count: 6263, doc_coverage_pct: 99.8 },+ { page_count: 0, fresh_page_count: 0, doc_coverage_pct: 0 },+ ];+ expect(workspaceDocFreshness(repos)).toEqual({ fresh: 6263, pages: 7253, pct: 86 });+ });++ it("floors, so a nearly fresh workspace never reads 100%", () => {+ expect(workspaceDocFreshness([{ page_count: 1000, fresh_page_count: 997 }]).pct).toBe(99);+ });++ it("has no figure without pages", () => {+ expect(workspaceDocFreshness([{ page_count: 0, fresh_page_count: 0 }]).pct).toBeNull();+ });++ it("names both counts in every locale", () => {+ for (const [locale, messages] of [["en", en], ["zh-CN", zhCN]] as const) {+ const t = createTranslator({ locale, messages, namespace: "views.workspace.ribbon" });+ const sub = t("docFreshnessSub", { fresh: "6,263", pages: "7,253" });+ expect(sub).toContain("6,263");+ expect(sub).toContain("7,253");+ }+ });+});diff --git a/packages/web/src/app/workspace/doc-freshness.ts b/packages/web/src/app/workspace/doc-freshness.tsnew file mode 100644index 000000000..f1c687361--- /dev/null+++ b/packages/web/src/app/workspace/doc-freshness.ts@@ -0,0 +1,28 @@+import type { WorkspaceRepoEntry } from "@repowise-dev/api-client/types";++export interface WorkspaceDocFreshness {+ fresh: number;+ pages: number;+ /** Fresh pages over all pages, 0-100; `null` with no pages. */+ pct: number | null;+}++/**+ * Doc freshness across the workspace: fresh pages over all pages.+ *+ * Not `doc_coverage_pct`: that is mean page confidence, which says how a page+ * was written, not whether it is current. Floored, not rounded: 99.7% rounds+ * to a perfect 100% and tells the reader every page is current when some are+ * not. Erring low never overclaims.+ */+export function workspaceDocFreshness(+ repos: Pick<WorkspaceRepoEntry, "page_count" | "fresh_page_count">[],+): WorkspaceDocFreshness {+ let fresh = 0;+ let pages = 0;+ for (const r of repos) {+ fresh += r.fresh_page_count;+ pages += r.page_count;+ }+ return { fresh, pages, pct: pages > 0 ? Math.floor((fresh / pages) * 100) : null };+}diff --git a/packages/web/src/app/workspace/page.tsx b/packages/web/src/app/workspace/page.tsxindex 71f846763..6b8c02403 100644--- a/packages/web/src/app/workspace/page.tsx+++ b/packages/web/src/app/workspace/page.tsx@@ -24,6 +24,7 @@ import { getWorkspaceActions } from "@/lib/api/actions";import { RemoveWorkspaceRepoButton, SyncButton } from "./sync-buttons";import { getTranslations } from "next-intl/server";import { WorkspaceNextActionsPanel } from "./workspace-next-actions-panel";+import { workspaceDocFreshness } from "./doc-freshness";const WORKSPACE_DOCS_HREF ="https://github.com/repowise-dev/repowise/blob/main/docs/start/QUICKSTART.md";@@ -51,8 +52,9 @@ const COCHANGE_PREVIEW = 8;* rebuilt rather than restyled:** - "Avg Coverage" averaged per-repo percentages unweighted, so a 50-file- * repo at 100% and a 5,000-file repo at 10% reported 55%. It is weighted by- * page count now, and named for what the rest of the app calls it.+ * repo at 100% and a 5,000-file repo at 10% reported 55%. Doc freshness+ * is fresh pages over all pages across the workspace, the share the+ * single-repo overview reports.* - The cross-repo force-directed graph drew seven nodes and thirteen edges* on a real workspace — a list wearing a canvas — and cost a third request* that swept every repo's sqlite a second time. The system map owns that@@ -101,16 +103,12 @@ export default async function WorkspaceDashboardPage() {files: acc.files + r.file_count,symbols: acc.symbols + r.symbol_count,pages: acc.pages + r.page_count,- // Page-weighted, so a small repo cannot pull the workspace average.- confidenceWeighted: acc.confidenceWeighted + r.doc_coverage_pct * r.page_count,hotspots: acc.hotspots + r.hotspot_count,}),- { files: 0, symbols: 0, pages: 0, confidenceWeighted: 0, hotspots: 0 },+ { files: 0, symbols: 0, pages: 0, hotspots: 0 },);- // Floored, not rounded: 99.7% rounds to a perfect 100% and tells the reader- // every page is current when some are not. Erring low never overclaims.- const docFreshness =- totals.pages > 0 ? Math.floor(totals.confidenceWeighted / totals.pages) : null;+ const docs = workspaceDocFreshness(repos);+ const docFreshness = docs.pct;const ribbon: RibbonStat[] = [{@@ -129,7 +127,10 @@ export default async function WorkspaceDashboardPage() {sub:docFreshness === null? t("ribbon.docFreshnessNoPages")- : t("ribbon.docFreshnessSub", { pages: formatNumber(totals.pages) }),+ : t("ribbon.docFreshnessSub", {+ fresh: formatNumber(docs.fresh),+ pages: formatNumber(docs.pages),+ }),},{label: t("ribbon.hotspots"),@@ -295,11 +296,10 @@ function toRow(repo: WorkspaceRepoEntry): RepoRow {health: repo.health_score == null ? null : repo.health_score / 10,fileCount: repo.file_count,hotspotCount: repo.hotspot_count,- // The workspace payload has no per-repo fresh-page or dead-export counts.- // Zero here means the row omits those clauses; it never prints "0% fresh",- // which would report a missing measurement as a bad one.- docPageCount: 0,- docFreshPageCount: 0,+ docPageCount: repo.page_count,+ docFreshPageCount: repo.fresh_page_count,+ // The workspace payload has no per-repo dead-export count; zero omits+ // that clause from the row.deadExportCount: 0,updatedAt: repo.indexed_at,indexBehind: null,diff --git a/packages/web/src/app/workspace/system-map/page.tsx b/packages/web/src/app/workspace/system-map/page.tsxindex 5b048301e..8f0b04cbe 100644--- a/packages/web/src/app/workspace/system-map/page.tsx+++ b/packages/web/src/app/workspace/system-map/page.tsx@@ -151,12 +151,14 @@ export default function SystemMapPage() {// Repo health by alias; the repo graph's node `name` is the alias.const { healthByRepo, repoIdByAlias } = useMemo(() => {- const health = new Map<string, RepoHealth>();- const ids = new Map<string, string>();- for (const n of repoGraph?.nodes ?? []) {- health.set(n.name, { score: n.health_score, source: n.health_score_source });- ids.set(n.name, n.repo_id);- }+ const nodes = repoGraph?.nodes ?? [];+ // An unscored repo has no entry, so its nodes read "No health score".+ const health = new Map<string, RepoHealth>(+ nodes.flatMap((n) =>+ n.health_score == null ? [] : [[n.name, { score: n.health_score }] as const],+ ),+ );+ const ids = new Map<string, string>(nodes.map((n) => [n.name, n.repo_id]));return { healthByRepo: health, repoIdByAlias: ids };}, [repoGraph]);diff --git a/tests/unit/server/test_workspace_router.py b/tests/unit/server/test_workspace_router.pyindex 74d982911..583babc5b 100644--- a/tests/unit/server/test_workspace_router.py+++ b/tests/unit/server/test_workspace_router.py@@ -246,7 +246,9 @@ def _create_workspace_repo_db(language TEXT,symbol_count INTEGER DEFAULT 0);- CREATE TABLE wiki_pages (id TEXT PRIMARY KEY, confidence REAL);+ CREATE TABLE wiki_pages (+ id TEXT PRIMARY KEY, confidence REAL, freshness_status TEXT+ );CREATE TABLE wiki_symbols (id TEXT PRIMARY KEY);CREATE TABLE git_metadata (id TEXT PRIMARY KEY,@@ -267,9 +269,9 @@ def _create_workspace_repo_db(('src/a.py::Foo.bar', 'symbol', 'python', 0),('src/b.py::baz', 'symbol', 'python', 0);INSERT INTO wiki_symbols (id) VALUES ('sym-foo'), ('sym-bar'), ('sym-baz');- INSERT INTO wiki_pages (id, confidence) VALUES- ('page-a', 0.8),- ('page-b', 0.6);+ INSERT INTO wiki_pages (id, confidence, freshness_status) VALUES+ ('page-a', 0.8, 'fresh'),+ ('page-b', 0.6, 'stale');INSERT INTO git_metadata (id, churn_percentile, is_hotspot) VALUES('src/a.py', 0.95, 1),('src/b.py', 0.10, 0);@@ -323,6 +325,18 @@ class TestGetWorkspace:assert data["default_repo"] == "backend"assert data["workspace_root"] == "/projects/myworkspace"+ @pytest.mark.asyncio+ async def test_repo_entry_counts_fresh_pages(self, tmp_path: Path) -> None:+ """Freshness comes from page status; doc_coverage_pct is mean confidence."""+ _create_workspace_repo_db(tmp_path, "backend")+ app = _make_workspace_app(ws_config=_make_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")+ backend = next(r for r in resp.json()["repos"] if r["alias"] == "backend")+ assert (backend["page_count"], backend["fresh_page_count"]) == (2, 1)+ assert backend["doc_coverage_pct"] == 70.0+@pytest.mark.asyncioasync def test_cross_repo_summary(self, tmp_path: Path) -> None:"""Enricher data populates cross_repo_summary."""@@ -862,13 +876,13 @@ class TestGetWorkspaceGraph:assert resp.status_code == 200backend = 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(+ async def test_no_health_score_when_repo_metrics_are_missing(self,tmp_path: Path,) -> None:+ """Doc confidence and hotspots are not code health, so no score stands in."""ws_config = _make_ws_config()_create_workspace_repo_db(tmp_path, "backend")app = _make_workspace_app(@@ -881,8 +895,8 @@ class TestGetWorkspaceGraph:assert resp.status_code == 200backend = next(n for n in resp.json()["nodes"] if n["name"] == "backend")- assert backend["health_score"] == 62.0- assert backend["health_score_source"] == "derived"+ assert backend["health_score"] is None+ assert "health_score_source" not in backend@pytest.mark.asyncioasync def test_weights_a_zero_nloc_file_as_one_line(self, tmp_path: Path) -> None:@@ -946,7 +960,9 @@ class TestQueryRepoStats:language TEXT,symbol_count INTEGER DEFAULT 0);- CREATE TABLE wiki_pages (id TEXT PRIMARY KEY, confidence REAL);+ CREATE TABLE wiki_pages (+ id TEXT PRIMARY KEY, confidence REAL, freshness_status TEXT+ );CREATE TABLE wiki_symbols (id TEXT PRIMARY KEY);CREATE TABLE git_metadata (id TEXT PRIMARY KEY,@@ -1507,7 +1523,7 @@ class TestRepoQueryBudget:sweep over the same databases."""- QUERIES_PER_REPO = 7+ QUERIES_PER_REPO = 6CONNECTIONS_PER_REPO = 2def _config_for(self, aliases: list[str]):