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(kg): name a folder card after the module page documenting it (#1828)
Raghav Chamadiyab2b9dc34cddb
diff --git a/packages/server/src/repowise/server/routers/c4.py b/packages/server/src/repowise/server/routers/c4.pyindex f3bd0f3b6..d66142186 100644--- a/packages/server/src/repowise/server/routers/c4.py+++ b/packages/server/src/repowise/server/routers/c4.py@@ -298,6 +298,7 @@ def _zoom_response(zoom: ZoomMap) -> ZoomMapResponse:),summary=n.summary,language=n.language,+ page_id=n.page_id,health_score=(round(n.health_score, 2) if n.health_score is not None else None),is_entry_point=n.is_entry_point,is_hotspot=n.is_hotspot,diff --git a/packages/server/src/repowise/server/schemas/zoom.py b/packages/server/src/repowise/server/schemas/zoom.pyindex 4d5dd2bb1..e3060cf1c 100644--- a/packages/server/src/repowise/server/schemas/zoom.py+++ b/packages/server/src/repowise/server/schemas/zoom.py@@ -35,6 +35,8 @@ class ZoomNodeResponse(BaseModel):metrics: ZoomMetricsResponse = Field(default_factory=ZoomMetricsResponse)summary: str = ""language: str | None = None+ # Id of the module page documenting this folder, when one does; "" otherwise.+ page_id: str = ""# Code-health score (0..10, higher = healthier), matching the /files treemap.# None when the file/subtree was unscored (health is sparse); the renderer# reads that as neutral.diff --git a/packages/server/src/repowise/server/services/zoom_builder/__init__.py b/packages/server/src/repowise/server/services/zoom_builder/__init__.pyindex d944558d8..8694b439a 100644--- a/packages/server/src/repowise/server/services/zoom_builder/__init__.py+++ b/packages/server/src/repowise/server/services/zoom_builder/__init__.py@@ -25,9 +25,12 @@ from .metrics import rollup_health, rollup_metricsfrom .models import ZoomMap, ZoomNode, ZoomRelationfrom .relations import aggregate_relationsfrom .scoring import FileStat, compute_file_signals, score_tree-from .tree import GroupSpec, LayerSpec, LeafInfo, build_tree+from .tree import GroupSpec, LayerSpec, LeafInfo, ModuleInfo, build_tree__all__ = [+ # ``ModuleInfo`` is part of the public surface because the hosted builder+ # calls ``assemble_zoom_map`` directly rather than porting it.+ "ModuleInfo","ZoomMap","ZoomNode","ZoomRelation",@@ -51,6 +54,7 @@ def assemble_zoom_map(max_depth: int | None = None,focus: str | None = None,health: dict[str, tuple[float, int]] | None = None,+ modules: dict[str, ModuleInfo] | None = None,) -> ZoomMap:"""Pure assembly: ``ArchitectureView`` -> ``ZoomMap``. No DB.@@ -58,6 +62,11 @@ def assemble_zoom_map(code-health score (higher = healthier) and ``loc`` is the rollup weight. It isoptional so the pure assembly still unit-tests without health data; files notpresent in the map read as unscored (neutral), exactly like the treemap.++ ``modules`` maps a directory path to the module page documenting it, so a+ folder card reads as the subsystem the docs name rather than as a path+ segment. Also optional: a repository indexed without a wiki has none, and+ the hosted builder does not have them in its artifacts yet."""health = health or {}# The view is loaded file-only, but the curated node_type can be@@ -128,7 +137,7 @@ def assemble_zoom_map(for layer in view.layers]- root_id, nodes = build_tree(view.project_name, layers, leaf_info)+ root_id, nodes = build_tree(view.project_name, layers, leaf_info, modules)nodes = rollup_metrics(root_id, nodes)nodes = rollup_health(root_id, nodes)nodes = score_tree(root_id, nodes, signals)@@ -230,6 +239,7 @@ async def build_zoom_map(from repowise.core.persistence import crudview = await build_architecture_view(session, repo_id, include_symbols=False)+ modules = await _load_module_names(session, repo_id)# One extra read: per-file health, keyed by path -> (effective score, loc).# Effective score prefers the split ``defect_score`` and falls back to the# overall ``score``, exactly like GET /api/repos/{id}/files, so the zoom card@@ -243,4 +253,38 @@ async def build_zoom_map()for m in metrics}- return assemble_zoom_map(view, max_depth=max_depth, focus=focus, health=health)+ return assemble_zoom_map(+ view, max_depth=max_depth, focus=focus, health=health, modules=modules+ )+++async def _load_module_names(session: AsyncSession, repo_id: str) -> dict[str, ModuleInfo]:+ """Directory path -> the module page documenting it.++ A module page's ``target_path`` is the directory it covers, which is the+ same key the folder trie is built on, so this is a join and not a second+ clustering. Tombstoned pages are excluded for the same reason the docs+ reader excludes them: the page is gone, so its name is not the repository's+ name for that directory any more.+ """+ from sqlalchemy import select++ from repowise.core.persistence.models import Page++ rows = await session.execute(+ select(Page.target_path, Page.title, Page.summary, Page.id).where(+ Page.repository_id == repo_id,+ Page.page_type == "module_page",+ Page.freshness_status != "tombstone",+ Page.target_path.isnot(None),+ )+ )+ modules: dict[str, ModuleInfo] = {}+ for target_path, title, summary, page_id in rows:+ # A module whose target is a clustering ordinal rather than a real+ # directory has nothing to join to; it simply never matches a folder.+ if target_path and title:+ modules[target_path] = ModuleInfo(+ title=title, summary=summary or "", page_id=page_id+ )+ return modulesdiff --git a/packages/server/src/repowise/server/services/zoom_builder/models.py b/packages/server/src/repowise/server/services/zoom_builder/models.pyindex 5eb4fa6bb..cc463ee2b 100644--- a/packages/server/src/repowise/server/services/zoom_builder/models.py+++ b/packages/server/src/repowise/server/services/zoom_builder/models.py@@ -50,6 +50,9 @@ class ZoomNode:metrics: ZoomMetrics = field(default_factory=ZoomMetrics)summary: str = ""language: str | None = None+ # The module page documenting this folder, when one does. Empty on every+ # other node, and on a folder no page covers.+ page_id: str = ""# Code-health score on the 0..10 scale (higher = healthier), matching the# /files treemap. A file carries its own defect score (falling back to the# overall score); a container carries the loc-weighted mean over its scoreddiff --git a/packages/server/src/repowise/server/services/zoom_builder/tree.py b/packages/server/src/repowise/server/services/zoom_builder/tree.pyindex 519bcbb9f..1f5c2e411 100644--- a/packages/server/src/repowise/server/services/zoom_builder/tree.py+++ b/packages/server/src/repowise/server/services/zoom_builder/tree.py@@ -11,6 +11,13 @@ This is deliberately NOT ``derive_modules`` (which right-sizes wiki modules to8-120 files): the zoom tree wants the true directory nesting so a viewer canzoom folder by folder.+A folder whose path is one a module page documents takes that page's title and+summary instead of its directory name. The nesting is unchanged; only the label+is. Below the layer rung every card used to read as a path segment (``core``,+``resolvers``, ``src``) while the docs reader, working off the same repository,+called those same directories "Repository Ingestion" and "Symbol Resolution".+Two names for one thing, on two pages of one product.+Pure and framework-agnostic: inputs are plain specs, output is a dict of frozen``ZoomNode``. Importance and metrics are filled by later passes."""@@ -42,6 +49,15 @@ class LayerSpec:sub_groups: list[GroupSpec] = field(default_factory=list)+@dataclass(frozen=True)+class ModuleInfo:+ """The documented identity of a directory, from its module page."""++ title: str+ summary: str = ""+ page_id: str = ""++@dataclass(frozen=True)class LeafInfo:"""Per-file presentation + signal flags carried onto the file leaf node."""@@ -123,15 +139,25 @@ def _insert(root: _Dir, path: str) -> None:cur.files.append(path)-def _compress(node: _Dir) -> tuple[str, _Dir]:- """Collapse single-child folder chains. Returns the (joined-name, deepest- folder) so ``a/(only)b/(only)c`` becomes one node named ``a/b/c``."""+def _compress(node: _Dir) -> tuple[str, _Dir, list[str]]:+ """Collapse single-child folder chains.++ Returns ``(joined-name, deepest folder, every path the chain swallowed)``+ so ``a/(only)b/(only)c`` becomes one node named ``a/b/c``. The path list is+ ordered shallowest-first and is what lets a caller ask whether *any* rung of+ the chain is a directory something knows about: the collapsed rungs are real+ directories that simply have no branch of their own, and a repository whose+ source sits under `packages/x/src/pkg/name` collapses most of its documented+ directories into exactly such a chain.+ """name = node.name+ covered = [node.path]while len(node.subdirs) == 1 and not node.files:(only,) = node.subdirs.values()name = f"{name}/{only.name}"node = only- return name, node+ covered.append(node.path)+ return name, node, covered# ---------------------------------------------------------------------------@@ -140,8 +166,11 @@ def _compress(node: _Dir) -> tuple[str, _Dir]:class _Builder:- def __init__(self, leaf_info: dict[str, LeafInfo]) -> None:+ def __init__(+ self, leaf_info: dict[str, LeafInfo], modules: dict[str, ModuleInfo]+ ) -> None:self.leaf_info = leaf_info+ self.modules = modulesself.nodes: dict[str, ZoomNode] = {}def add(self, node: ZoomNode) -> str:@@ -171,23 +200,38 @@ class _Builder:))+ def module_for(self, covered: list[str]) -> ModuleInfo | None:+ """The documented identity of a compressed chain, deepest rung first.++ Deepest wins because it is the most specific: on `a -> a/b`, a page for+ `a/b` describes this card more precisely than one for `a`.+ """+ for path in reversed(covered):+ module = self.modules.get(path)+ if module is not None:+ return module+ return None+def emit_dir(self, dnode: _Dir, parent_id: str, level: int, scope: str) -> str:- name, node = _compress(dnode)+ name, node, covered = _compress(dnode)fid = folder_id(scope, node.path)children: list[str] = []for sub in sorted(node.subdirs.values(), key=lambda d: d.name):children.append(self.emit_dir(sub, fid, level + 1, scope))for path in sorted(node.files):children.append(self.emit_file(path, fid, level + 1))+ module = self.module_for(covered)self.add(ZoomNode(id=fid,parent_id=parent_id,level=level,kind="folder",- name=name,+ name=module.title if module else name,path=node.path,children=tuple(children),+ summary=module.summary if module else "",+ page_id=module.page_id if module else "",))return fid@@ -217,14 +261,19 @@ def build_tree(project_name: str,layers: list[LayerSpec],leaf_info: dict[str, LeafInfo],+ modules: dict[str, ModuleInfo] | None = None,) -> tuple[str, dict[str, ZoomNode]]:"""Build the containment tree. Returns ``(root_id, nodes)``.``layers`` should already be ordered (the caller passes them by``display_order``); files not claimed by any sub-group attach directly undertheir layer so the file partition is preserved (every file appears once).++ ``modules`` maps a repo-relative directory path to the module page that+ documents it. Optional: without it every folder keeps its directory name,+ which is what a repository with no generated wiki has."""- b = _Builder(leaf_info)+ b = _Builder(leaf_info, modules or {})layer_ids: list[str] = []for layer in sorted(layers, key=lambda layer_: layer_.display_order):diff --git a/packages/ui/__tests__/zoom/cull.test.ts b/packages/ui/__tests__/zoom/cull.test.tsindex 1196bb9fa..3038281b6 100644--- a/packages/ui/__tests__/zoom/cull.test.ts+++ b/packages/ui/__tests__/zoom/cull.test.ts@@ -39,6 +39,7 @@ function leaf(id: string, rank: number): ZoomNode {entry_point_count: 0,on_flow_count: 0,},+ page_id: "",summary: "",language: null,is_entry_point: false,diff --git a/packages/ui/__tests__/zoom/focus-path.test.ts b/packages/ui/__tests__/zoom/focus-path.test.tsindex 7f5a933a2..72c8a69db 100644--- a/packages/ui/__tests__/zoom/focus-path.test.ts+++ b/packages/ui/__tests__/zoom/focus-path.test.ts@@ -23,6 +23,7 @@ function node(id: string, children: string[]): ZoomNode {entry_point_count: 0,on_flow_count: 0,},+ page_id: "",summary: "",language: null,is_entry_point: false,diff --git a/packages/ui/__tests__/zoom/geometry.test.ts b/packages/ui/__tests__/zoom/geometry.test.tsindex a6e5ecbfb..919babea5 100644--- a/packages/ui/__tests__/zoom/geometry.test.ts+++ b/packages/ui/__tests__/zoom/geometry.test.ts@@ -26,6 +26,7 @@ function node(id: string, parent: string | null, children: string[]): ZoomNode {entry_point_count: 0,on_flow_count: 0,},+ page_id: "",summary: "",language: null,is_entry_point: false,diff --git a/packages/ui/__tests__/zoom/node-signals.test.ts b/packages/ui/__tests__/zoom/node-signals.test.tsindex 54692a126..b99889c0d 100644--- a/packages/ui/__tests__/zoom/node-signals.test.ts+++ b/packages/ui/__tests__/zoom/node-signals.test.ts@@ -38,6 +38,7 @@ function node(children: [],importance: 0,sibling_rank: 0,+ page_id: "",summary: "",language: null,health_score: null,diff --git a/packages/ui/src/zoom/types.ts b/packages/ui/src/zoom/types.tsindex 85017f011..564b86ca6 100644--- a/packages/ui/src/zoom/types.ts+++ b/packages/ui/src/zoom/types.ts@@ -37,6 +37,8 @@ export interface ZoomNode {metrics: ZoomMetrics;summary: string;language: string | null;+ /** Id of the module page documenting this folder, or "" when none does. */+ page_id: string;/** Code-health score (0-10, higher = healthier), matching the /files treemap.* Null when the file/subtree was unscored (health is sparse) — read as neutral. */health_score: number | null;diff --git a/packages/web/src/components/zoom/zoom-detail-panel.tsx b/packages/web/src/components/zoom/zoom-detail-panel.tsxindex 7b7280e55..e6ce2d513 100644--- a/packages/web/src/components/zoom/zoom-detail-panel.tsx+++ b/packages/web/src/components/zoom/zoom-detail-panel.tsx@@ -18,7 +18,7 @@*/import Link from "next/link";-import { FileCode, ScanSearch, X } from "lucide-react";+import { BookOpen, FileCode, ScanSearch, X } from "lucide-react";import type { ZoomNode, ZoomRelation } from "@repowise-dev/ui/zoom";import {describeCap,@@ -30,6 +30,7 @@ import {} from "@repowise-dev/ui/zoom";import { bandForScore } from "@repowise-dev/types/health";import { fileEntityPath } from "@repowise-dev/ui/shared/entity";+import { pageHref } from "@/lib/utils/page-href";import { healthBandTextColor } from "@repowise-dev/ui/health";interface ZoomDetailPanelProps {@@ -218,7 +219,7 @@ export function ZoomDetailPanel({)}</div>- {(node.children.length > 0 || isFile) && (+ {(node.children.length > 0 || isFile || node.page_id) && (<footer className="flex flex-col gap-2 border-t border-[var(--color-border-default)] p-3">{node.children.length > 0 && (<button@@ -230,6 +231,17 @@ export function ZoomDetailPanel({Zoom in</button>)}+ {/* This card is named after a module page, so the page it is named+ after has to be reachable from it. */}+ {node.page_id && (+ <Link+ href={pageHref(repoId, node.page_id)}+ className="flex w-full items-center justify-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-3 py-2 text-[13px] font-medium text-[var(--color-text-primary)] hover:bg-[var(--color-bg-wash-hover)]"+ >+ <BookOpen className="h-3.5 w-3.5" />+ Read the module page+ </Link>+ )}{isFile && node.path && (<Linkhref={fileHref(repoId, node.path)}diff --git a/tests/unit/server/services/test_zoom_builder.py b/tests/unit/server/services/test_zoom_builder.pyindex 8dec61632..83d54ef34 100644--- a/tests/unit/server/services/test_zoom_builder.py+++ b/tests/unit/server/services/test_zoom_builder.py@@ -23,6 +23,7 @@ from repowise.server.services.zoom_builder.tree import (GroupSpec,LayerSpec,LeafInfo,+ ModuleInfo,build_tree,file_id,folder_id,@@ -78,6 +79,100 @@ def test_build_tree_compresses_single_child_folder_chains():assert len(folders[0].children) == 2+def test_build_tree_names_a_folder_after_the_module_page_documenting_it():+ layers = [+ LayerSpec(+ id="layer:core",+ name="Core",+ display_order=0,+ node_ids=["src/resolvers/a.py", "src/parsers/b.py"],+ ),+ ]+ modules = {+ "src/resolvers": ModuleInfo(+ title="Symbol Resolution", summary="Cross-language lookup.", page_id="pg1"+ ),+ }+ _root, nodes = build_tree("proj", layers, {}, modules)+ named = next(n for n in nodes.values() if n.path == "src/resolvers")+ assert named.name == "Symbol Resolution"+ assert named.summary == "Cross-language lookup."+ assert named.page_id == "pg1"+ # A directory no page documents keeps the name the filesystem gave it, and+ # says nothing it cannot back up.+ plain = next(n for n in nodes.values() if n.path == "src/parsers")+ assert plain.name == "parsers"+ assert plain.summary == ""+ assert plain.page_id == ""+++def test_build_tree_prefers_the_deepest_documented_rung_of_a_compressed_chain():+ layers = [+ LayerSpec(+ id="layer:core",+ name="Core",+ display_order=0,+ node_ids=["a/b/c/f1.py", "a/b/c/f2.py"],+ ),+ ]+ # The chain a -> a/b -> a/b/c is one card. Both ends are documented, and the+ # deeper page describes it more precisely.+ modules = {"a": ModuleInfo(title="Broad"), "a/b/c": ModuleInfo(title="Precise")}+ _root, nodes = build_tree("proj", layers, {}, modules)+ folders = [n for n in nodes.values() if n.kind == "folder"]+ assert len(folders) == 1+ assert folders[0].name == "Precise"+++def test_build_tree_names_a_chain_from_a_rung_compression_swallowed():+ layers = [+ LayerSpec(+ id="layer:core",+ name="Core",+ display_order=0,+ node_ids=["a/b/c/f1.py", "a/b/c/f2.py"],+ ),+ ]+ # Only the head of the chain is documented. It is still a real directory,+ # and it is the one this card stands for, so the name applies. A repository+ # laid out as packages/<x>/src/<pkg> collapses nearly every documented+ # directory into a chain like this, so matching the deepest rung alone would+ # name almost nothing.+ modules = {"a/b": ModuleInfo(title="Middle Rung")}+ _root, nodes = build_tree("proj", layers, {}, modules)+ folders = [n for n in nodes.values() if n.kind == "folder"]+ assert len(folders) == 1+ assert folders[0].name == "Middle Rung"+ # The path still describes what the card actually contains.+ assert folders[0].path == "a/b/c"+++def test_build_tree_module_names_do_not_move_any_file():+ layers = [+ LayerSpec(+ id="layer:core",+ name="Core",+ display_order=0,+ node_ids=["src/resolvers/a.py", "src/parsers/b.py"],+ ),+ ]+ modules = {"src/resolvers": ModuleInfo(title="Symbol Resolution")}+ _root, plain = build_tree("proj", layers, {})+ _root2, named = build_tree("proj", layers, {}, modules)+ # Naming is a label change: same ids, same parents, same children.+ assert set(plain) == set(named)+ assert {i: n.parent_id for i, n in plain.items()} == {+ i: n.parent_id for i, n in named.items()+ }+ assert {i: n.children for i, n in plain.items()} == {+ i: n.children for i, n in named.items()+ }+ # ...and only the documented folder reads differently.+ renamed = {i for i in plain if plain[i].name != named[i].name}+ assert renamed == {i for i, n in named.items() if n.path == "src/resolvers"}+ assert all(plain[i].path == named[i].path for i in plain)++def test_build_tree_subgroups_and_ungrouped_files():layers = [LayerSpec(