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(server): zoom-map builder for the continuous-zoom architecture view (#626)
Raghav Chamadiyabf9ccbbc9ebd
diff --git a/packages/server/src/repowise/server/routers/c4.py b/packages/server/src/repowise/server/routers/c4.pyindex 4ad5962b4..b39ef42fb 100644--- a/packages/server/src/repowise/server/routers/c4.py+++ b/packages/server/src/repowise/server/routers/c4.py@@ -27,8 +27,14 @@ from repowise.server.schemas import (C4PersonResponse,C4RelationResponse,C4SystemResponse,+ ZoomMapResponse,+ ZoomMetricsResponse,+ ZoomNodeResponse,+ ZoomRectResponse,+ ZoomRelationResponse,)from repowise.server.services import c4_builder+from repowise.server.services.zoom_builder import ZoomMap, build_zoom_mapfrom repowise.server.services.c4_builder.mermaid import (to_mermaid_l1,to_mermaid_l2,@@ -194,3 +200,85 @@ async def get_architecture_view(return await build_architecture_view_response(session, repo_id, include_symbols=include_symbols)++[email protected]("/{repo_id}/zoom-map", response_model=ZoomMapResponse)+async def get_zoom_map(+ repo_id: str,+ max_depth: int | None = Query(+ None, ge=1, description="Cap levels served below the (focus) root; omit for full"+ ),+ focus: str | None = Query(+ None, description="Node id to scope the served subtree to (lazy drill-down)"+ ),+ session: AsyncSession = Depends(get_db_session),+) -> ZoomMapResponse:+ """The continuous-zoom containment tree (system -> layer -> ... -> file).++ Derived on demand from the persisted graph, like the C4 views. ``focus`` ++ ``max_depth`` let the canvas fetch deeper subtrees lazily for large repos.+ """+ zoom = await build_zoom_map(session, repo_id, max_depth=max_depth, focus=focus)+ return _zoom_response(zoom)+++def _zoom_response(zoom: ZoomMap) -> ZoomMapResponse:+ return ZoomMapResponse(+ root_id=zoom.root_id,+ project_name=zoom.project_name,+ total_files=zoom.total_files,+ max_depth=zoom.max_depth,+ truncated=zoom.truncated,+ nodes=[+ ZoomNodeResponse(+ id=n.id,+ parent_id=n.parent_id,+ level=n.level,+ kind=n.kind,+ name=n.name,+ path=n.path,+ children=list(n.children),+ importance=round(n.importance, 4),+ sibling_rank=n.sibling_rank,+ metrics=ZoomMetricsResponse(+ file_count=n.metrics.file_count,+ descendant_count=n.metrics.descendant_count,+ hotspot_count=n.metrics.hotspot_count,+ dead_count=n.metrics.dead_count,+ entry_point_count=n.metrics.entry_point_count,+ on_flow_count=n.metrics.on_flow_count,+ ),+ layout=(+ ZoomRectResponse(+ x=round(n.layout.x, 6),+ y=round(n.layout.y, 6),+ w=round(n.layout.w, 6),+ h=round(n.layout.h, 6),+ )+ if n.layout is not None+ else None+ ),+ summary=n.summary,+ language=n.language,+ is_entry_point=n.is_entry_point,+ is_hotspot=n.is_hotspot,+ is_dead=n.is_dead,+ is_test=n.is_test,+ on_flow=n.on_flow,+ )+ # Stable order so the response is deterministic regardless of the+ # builder's internal insertion order.+ for n in sorted(zoom.nodes.values(), key=lambda node: node.id)+ ],+ relations=[+ ZoomRelationResponse(+ parent_id=r.parent_id,+ source_id=r.source_id,+ target_id=r.target_id,+ label=r.label,+ edge_count=r.edge_count,+ coupling=r.coupling,+ )+ for r in zoom.relations+ ],+ )diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.pyindex 8698fc006..d6ea8db88 100644--- a/packages/server/src/repowise/server/schemas/__init__.py+++ b/packages/server/src/repowise/server/schemas/__init__.py@@ -34,6 +34,13 @@ from .c4 import (C4RelationResponse,C4SystemResponse,)+from .zoom import (+ ZoomMapResponse,+ ZoomMetricsResponse,+ ZoomNodeResponse,+ ZoomRectResponse,+ ZoomRelationResponse,+)from .chat import (ChatMessageResponse,ChatRequest,@@ -355,4 +362,9 @@ __all__ = ["WorkspaceSystemGraphResponse","WorkspaceSystemNode","WorkspaceUnmatchedConsumer",+ "ZoomMapResponse",+ "ZoomMetricsResponse",+ "ZoomNodeResponse",+ "ZoomRectResponse",+ "ZoomRelationResponse",]diff --git a/packages/server/src/repowise/server/schemas/zoom.py b/packages/server/src/repowise/server/schemas/zoom.pynew file mode 100644index 000000000..a4cd2c6a1--- /dev/null+++ b/packages/server/src/repowise/server/schemas/zoom.py@@ -0,0 +1,69 @@+"""Zoom-map response models.++One nested containment tree (system -> layer -> group -> folder -> file) served+as a flat list of nodes (each carrying its own id), plus parent-relative+relations. The canvas renderer indexes the list by id and reconstructs the tree+from ``parent_id`` / ``children``, then uses ``layout`` (parent ``[0,1]`` space)+for clip-and-scale and ``importance`` / ``sibling_rank`` for density caps. The+list is emitted in a stable order (sorted by id).+"""++from __future__ import annotations++from pydantic import BaseModel, Field+++class ZoomRectResponse(BaseModel):+ x: float+ y: float+ w: float+ h: float+++class ZoomMetricsResponse(BaseModel):+ file_count: int = 0+ descendant_count: int = 0+ hotspot_count: int = 0+ dead_count: int = 0+ entry_point_count: int = 0+ on_flow_count: int = 0+++class ZoomNodeResponse(BaseModel):+ id: str+ parent_id: str | None = None+ level: int+ kind: str # system | layer | group | folder | file+ name: str+ path: str = ""+ children: list[str] = Field(default_factory=list)+ importance: float = 0.0+ sibling_rank: int = 0+ metrics: ZoomMetricsResponse = Field(default_factory=ZoomMetricsResponse)+ layout: ZoomRectResponse | None = None+ summary: str = ""+ language: str | None = None+ is_entry_point: bool = False+ is_hotspot: bool = False+ is_dead: bool = False+ is_test: bool = False+ on_flow: bool = False+++class ZoomRelationResponse(BaseModel):+ parent_id: str+ source_id: str+ target_id: str+ label: str = ""+ edge_count: int = 1+ coupling: str = "" # loose | moderate | tight+++class ZoomMapResponse(BaseModel):+ root_id: str+ project_name: str+ total_files: int+ max_depth: int+ truncated: bool = False+ nodes: list[ZoomNodeResponse]+ relations: list[ZoomRelationResponse]diff --git a/packages/server/src/repowise/server/services/zoom_builder/__init__.py b/packages/server/src/repowise/server/services/zoom_builder/__init__.pynew file mode 100644index 000000000..39b382248--- /dev/null+++ b/packages/server/src/repowise/server/services/zoom_builder/__init__.py@@ -0,0 +1,218 @@+"""Zoom-map builder service.++Public API+----------+``build_zoom_map(session, repo, *, max_depth=None, focus=None)`` returns the+nested containment tree (system -> layer -> group -> folder -> file) with+execution-aware importance, rolled-up metrics, parent-relative relations, and a+deterministic treemap layout.++Like :mod:`c4_builder`, the map is derived ON DEMAND from the persisted graph+(it reuses ``c4_builder.build_architecture_view`` for the heavy load), so it+works on hosted backends with no checkout and never goes stale. Everything below+the load is pure functions (tree / scoring / metrics / relations / layout) that+unit-test without a session.+"""++from __future__ import annotations++from sqlalchemy.ext.asyncio import AsyncSession++from repowise.server.services.c4_builder.architecture import build_architecture_view+from repowise.server.services.c4_builder.models import ArchitectureView++from .layout import lay_out+from .metrics import rollup_metrics+from .models import ZoomMap, ZoomNode, ZoomRelation+from .relations import aggregate_relations+from .scoring import FileStat, compute_file_signals, score_tree+from .tree import GroupSpec, LayerSpec, LeafInfo, build_tree++__all__ = [+ "ZoomMap",+ "ZoomNode",+ "ZoomRelation",+ "assemble_zoom_map",+ "build_zoom_map",+]+++def _tour_paths(view: ArchitectureView) -> set[str]:+ paths: set[str] = set()+ for step in view.tour:+ if step.target_path:+ paths.add(step.target_path)+ paths.update(step.node_ids)+ return paths+++def assemble_zoom_map(+ view: ArchitectureView,+ *,+ max_depth: int | None = None,+ focus: str | None = None,+) -> ZoomMap:+ """Pure assembly: ``ArchitectureView`` -> ``ZoomMap``. No DB."""+ # The view is loaded file-only, but the curated node_type can be+ # config/document/service rather than "file"; a file node is reliably the+ # one whose id equals its own path and carries no symbol line range.+ file_nodes = [n for n in view.nodes if n.line_range is None and n.id == n.file_path]++ # Use the curated, cleaned entry-point list (Phase-1 ranking) rather than the+ # raw ingestion ``is_entry_point`` flag, which still tags barrels, configs+ # (server.json), and leaf resolvers (dotnet/index.py). Driving both the+ # execution bonus and the displayed leaf flag off the curated set keeps the+ # "how it runs" signal honest.+ curated_entries = set(view.entry_points)++ file_stats = [+ FileStat(+ path=n.id,+ pagerank_pct=n.pagerank_percentile,+ betweenness=n.betweenness,+ degree=n.in_degree + n.out_degree,+ complexity=n.complexity,+ is_entry_point=n.id in curated_entries,+ is_test=n.is_test,+ is_hotspot=n.is_hotspot,+ is_dead=n.is_dead,+ )+ for n in file_nodes+ ]+ edges = [(e.source, e.target, e.edge_type) for e in view.edges]++ signals = compute_file_signals(+ file_stats,+ edges,+ entry_points=list(view.entry_points),+ tour_paths=_tour_paths(view),+ )++ leaf_info: dict[str, LeafInfo] = {}+ for n in file_nodes:+ sig = signals.get(n.id)+ leaf_info[n.id] = LeafInfo(+ summary=n.summary,+ language=n.language,+ is_entry_point=n.id in curated_entries,+ is_hotspot=n.is_hotspot,+ is_dead=n.is_dead,+ is_test=n.is_test,+ on_flow=bool(sig and sig.on_flow),+ )++ layers = [+ LayerSpec(+ id=layer.id,+ name=layer.name,+ display_order=layer.display_order,+ node_ids=list(layer.node_ids),+ sub_groups=[+ GroupSpec(id=sg.id, name=sg.name, node_ids=list(sg.node_ids))+ for sg in layer.sub_groups+ ],+ )+ for layer in view.layers+ ]++ root_id, nodes = build_tree(view.project_name, layers, leaf_info)+ nodes = rollup_metrics(root_id, nodes)+ nodes = score_tree(root_id, nodes, signals)+ nodes = lay_out(root_id, nodes)+ relations = aggregate_relations(nodes, edges)++ # Honest count of files actually placed in the tree (a file the view knows+ # about but that curation assigned to no layer is not in the tree, so+ # counting file_stats would over-report). Taken before depth/focus pruning.+ total_files = sum(1 for n in nodes.values() if n.kind == "file")++ root_id, nodes, relations, truncated = _prune(+ root_id, nodes, relations, max_depth=max_depth, focus=focus+ )++ present_depth = max((n.level for n in nodes.values()), default=0)+ return ZoomMap(+ root_id=root_id,+ nodes=nodes,+ relations=relations,+ project_name=view.project_name,+ total_files=total_files,+ max_depth=present_depth,+ truncated=truncated,+ )+++def _prune(+ root_id: str,+ nodes: dict[str, ZoomNode],+ relations: tuple[ZoomRelation, ...],+ *,+ max_depth: int | None,+ focus: str | None,+) -> tuple[str, dict[str, ZoomNode], tuple[ZoomRelation, ...], bool]:+ """Scope to ``focus`` subtree and/or cap to ``max_depth`` levels below it.++ Returns the (possibly new) root, the kept nodes, kept relations, and whether+ anything was dropped (so the renderer knows it can lazy-fetch deeper).+ """+ if focus is not None and focus not in nodes:+ # Unknown focus: serve an empty map rooted at the original system node.+ focus = None++ new_root = focus or root_id+ base_level = nodes[new_root].level+ keep: dict[str, ZoomNode] = {}+ truncated = False++ # Walk the subtree from the new root (order is irrelevant — depth is gated on+ # absolute level, not hop count — so a simple stack is fine).+ stack = [new_root]+ while stack:+ nid = stack.pop()+ node = nodes[nid]+ depth_from_root = node.level - base_level+ if max_depth is not None and depth_from_root >= max_depth:+ # Keep this node but drop its children (frontier of the served map).+ if node.children:+ truncated = True+ node = _without_children(node)+ keep[nid] = node+ continue+ keep[nid] = node+ stack.extend(node.children)++ # Re-root: the focus node becomes a parentless root in the served map.+ if new_root != root_id:+ keep[new_root] = _as_root(keep[new_root])++ kept_ids = set(keep)+ rels = tuple(+ r+ for r in relations+ if r.parent_id in kept_ids and r.source_id in kept_ids and r.target_id in kept_ids+ )+ return new_root, keep, rels, truncated+++def _without_children(node: ZoomNode) -> ZoomNode:+ from dataclasses import replace++ return replace(node, children=())+++def _as_root(node: ZoomNode) -> ZoomNode:+ from dataclasses import replace++ return replace(node, parent_id=None)+++async def build_zoom_map(+ session: AsyncSession,+ repo_id: str,+ *,+ max_depth: int | None = None,+ focus: str | None = None,+) -> ZoomMap:+ """Derive the zoom map for ``repo_id`` from the persisted graph."""+ view = await build_architecture_view(session, repo_id, include_symbols=False)+ return assemble_zoom_map(view, max_depth=max_depth, focus=focus)diff --git a/packages/server/src/repowise/server/services/zoom_builder/layout.py b/packages/server/src/repowise/server/services/zoom_builder/layout.pynew file mode 100644index 000000000..ef936f553--- /dev/null+++ b/packages/server/src/repowise/server/services/zoom_builder/layout.py@@ -0,0 +1,111 @@+"""Deterministic squarified-treemap layout for the zoom map.++Each parent's children are packed into the parent's unit ``[0,1]`` rectangle,+with area proportional to ``importance`` (so the execution-relevant nodes the+scorer surfaced are also the biggest boxes). Rectangles are emitted in parent+space; the renderer maps a child straight to screen by scaling content by+``(w, h)`` and translating by ``(x, y)`` (clip-and-scale recursion).++Squarified treemap (Bruls, Huizing, van Wijk) keeps boxes close to square so+labels stay readable. The squarify pass itself is iterative so a single flat+folder with thousands of files cannot blow the recursion limit; the tree walk+(``place_children``) recurses one frame per *level*, which the single-child+chain compression in ``tree.py`` keeps shallow. Pure, deterministic, no DB.+"""++from __future__ import annotations++from dataclasses import replace++from .models import ZoomNode, ZoomRect++_EPS = 1e-9+++def _worst(row: list[float], length: float) -> float:+ """Worst aspect ratio of a row of areas laid along a side of ``length``."""+ if length <= 0:+ return float("inf")+ total = sum(row)+ if total <= 0:+ return float("inf")+ side = total / length+ worst = 0.0+ for area in row:+ other = area / side if side > 0 else 0.0+ if other <= 0:+ return float("inf")+ ratio = max(side / other, other / side)+ worst = max(worst, ratio)+ return worst+++def _emit_row(+ row: list[float], x: float, y: float, dx: float, dy: float+) -> tuple[list[tuple[float, float, float, float]], tuple[float, float, float, float]]:+ """Place ``row`` along the shorter side; return its rects + the leftover."""+ total = sum(row)+ rects: list[tuple[float, float, float, float]] = []+ if dx >= dy: # lay the row as a vertical column of fixed width+ width = total / dy if dy > 0 else 0.0+ yy = y+ for area in row:+ h = area / width if width > 0 else 0.0+ rects.append((x, yy, width, h))+ yy += h+ return rects, (x + width, y, dx - width, dy)+ # lay the row as a horizontal strip of fixed height+ height = total / dx if dx > 0 else 0.0+ xx = x+ for area in row:+ w = area / height if height > 0 else 0.0+ rects.append((xx, y, w, height))+ xx += w+ return rects, (x, y + height, dx, dy - height)+++def _squarify(areas: list[float], x: float, y: float, dx: float, dy: float) -> list[tuple]:+ """Lay out ``areas`` (summing to ``dx*dy``, sorted desc) into rectangles."""+ rects: list[tuple] = []+ remaining = list(areas)+ while remaining:+ if dx <= 0 or dy <= 0:+ # Degenerate strip: stack the rest with zero area (keeps positions).+ for _ in remaining:+ rects.append((x, y, 0.0, 0.0))+ break+ shorter = min(dx, dy)+ row: list[float] = [remaining[0]]+ i = 1+ while i < len(remaining):+ if _worst(row, shorter) < _worst([*row, remaining[i]], shorter):+ break+ row.append(remaining[i])+ i += 1+ placed, (x, y, dx, dy) = _emit_row(row, x, y, dx, dy)+ rects.extend(placed)+ remaining = remaining[i:]+ return rects+++def lay_out(root_id: str, nodes: dict[str, ZoomNode]) -> dict[str, ZoomNode]:+ """Return ``nodes`` with a ``layout`` rect on every node (parent space)."""+ updated: dict[str, ZoomNode] = dict(nodes)+ updated[root_id] = replace(updated[root_id], layout=ZoomRect(0.0, 0.0, 1.0, 1.0))++ def place_children(node_id: str) -> None:+ node = updated[node_id]+ children = list(node.children)+ if children:+ ordered = sorted(children, key=lambda c: (-updated[c].importance, updated[c].name))+ weights = [updated[c].importance + _EPS for c in ordered]+ total = sum(weights)+ areas = [w / total for w in weights] # sum to 1 == unit-square area+ rects = _squarify(areas, 0.0, 0.0, 1.0, 1.0)+ for cid, (rx, ry, rw, rh) in zip(ordered, rects, strict=True):+ updated[cid] = replace(updated[cid], layout=ZoomRect(rx, ry, rw, rh))+ for cid in children:+ place_children(cid)++ place_children(root_id)+ return updateddiff --git a/packages/server/src/repowise/server/services/zoom_builder/metrics.py b/packages/server/src/repowise/server/services/zoom_builder/metrics.pynew file mode 100644index 000000000..8842fa6c9--- /dev/null+++ b/packages/server/src/repowise/server/services/zoom_builder/metrics.py@@ -0,0 +1,59 @@+"""Roll per-file flags up the containment tree into per-node counts.++A file leaf contributes its own flags; every ancestor sums its subtree. The+renderer shows these as chips (``12 files``, ``3 hotspots``) at any zoom depth+without walking the tree itself. Pure post-order aggregation, no DB.+"""++from __future__ import annotations++from dataclasses import replace++from .models import ZoomMetrics, ZoomNode+++def rollup_metrics(root_id: str, nodes: dict[str, ZoomNode]) -> dict[str, ZoomNode]:+ """Return ``nodes`` with ``metrics`` filled on every node.++ Recurses one frame per tree *level*; single-child folder-chain compression+ (``tree.py``) keeps the tree shallow (branching levels only), so this stays+ far below the recursion limit even on deeply-nested package layouts.+ """+ updated: dict[str, ZoomNode] = dict(nodes)++ def visit(node_id: str) -> ZoomMetrics:+ node = updated[node_id]+ if node.kind == "file":+ m = ZoomMetrics(+ file_count=1,+ descendant_count=0,+ hotspot_count=1 if node.is_hotspot else 0,+ dead_count=1 if node.is_dead else 0,+ entry_point_count=1 if node.is_entry_point else 0,+ on_flow_count=1 if node.on_flow else 0,+ )+ updated[node_id] = replace(node, metrics=m)+ return m++ files = hot = dead = entry = flow = descendants = 0+ for cid in node.children:+ cm = visit(cid)+ files += cm.file_count+ hot += cm.hotspot_count+ dead += cm.dead_count+ entry += cm.entry_point_count+ flow += cm.on_flow_count+ descendants += cm.descendant_count + 1 # the child itself + its subtree+ m = ZoomMetrics(+ file_count=files,+ descendant_count=descendants,+ hotspot_count=hot,+ dead_count=dead,+ entry_point_count=entry,+ on_flow_count=flow,+ )+ updated[node_id] = replace(node, metrics=m)+ return m++ visit(root_id)+ return updateddiff --git a/packages/server/src/repowise/server/services/zoom_builder/models.py b/packages/server/src/repowise/server/services/zoom_builder/models.pynew file mode 100644index 000000000..fdbe5b6eb--- /dev/null+++ b/packages/server/src/repowise/server/services/zoom_builder/models.py@@ -0,0 +1,103 @@+"""Plain dataclasses produced by the zoom-map builder.++Framework-agnostic (no Pydantic, no SQLAlchemy) so the pure tree / scoring /+layout / relation functions unit-test without a session, mirroring+``c4_builder.models``. The router wraps these into Pydantic response models.++The zoom map is one nested containment tree:++ system -> layer -> sub-group -> folder(s) -> file++Every node carries an execution-aware ``importance`` (0..1) and a+``sibling_rank`` so the renderer can cap how many children it draws at each+zoom depth, plus a deterministic ``layout`` rect (parent ``[0,1]`` space) for+the clip-and-scale canvas.+"""++from __future__ import annotations++from dataclasses import dataclass, field++# Node kinds, coarsest to finest. A leaf is always ``file``.+NODE_KINDS = ("system", "layer", "group", "folder", "file")+++@dataclass(frozen=True)+class ZoomRect:+ """A child's allocation inside its parent, in parent ``[0,1]`` space.++ The renderer maps this straight to screen space: scale child content by+ ``(w, h)`` and translate by ``(x, y)`` (clip-and-scale recursion).+ """++ x: float+ y: float+ w: float+ h: float+++@dataclass(frozen=True)+class ZoomMetrics:+ """Counts rolled up over a node's subtree (a file is its own subtree)."""++ file_count: int = 0+ descendant_count: int = 0+ hotspot_count: int = 0+ dead_count: int = 0+ entry_point_count: int = 0+ on_flow_count: int = 0+++@dataclass(frozen=True)+class ZoomNode:+ """One node in the containment tree."""++ id: str # "zm:sys" | "zm:layer:<id>" | "zm:<path>" ...+ parent_id: str | None # None only for the system root+ level: int # 0 system, 1 layer, 2 group, 3+ folder, leaf file+ kind: str # one of NODE_KINDS+ name: str # display label (may be "a/b" for compressed dirs)+ path: str = "" # repo-relative path for folder/file nodes; "" otherwise+ children: tuple[str, ...] = field(default_factory=tuple)+ importance: float = 0.0 # 0..1, execution-aware, normalized within siblings+ sibling_rank: int = 0 # 1 = most important among siblings+ metrics: ZoomMetrics = field(default_factory=ZoomMetrics)+ layout: ZoomRect | None = None+ summary: str = ""+ language: str | None = None+ # File-leaf flags (False / defaults on non-file nodes).+ is_entry_point: bool = False+ is_hotspot: bool = False+ is_dead: bool = False+ is_test: bool = False+ on_flow: bool = False # reachable from an entry point along import edges+++@dataclass(frozen=True)+class ZoomRelation:+ """An aggregated edge between two sibling subtrees under a shared parent.++ The renderer draws these when the viewer is zoomed into ``parent_id``: a+ relation from ``source_id`` to ``target_id`` (both direct children of the+ parent), labelled and coupling-tiered like the C4 relations.+ """++ parent_id: str+ source_id: str+ target_id: str+ label: str = ""+ edge_count: int = 1+ coupling: str = "" # loose | moderate | tight+++@dataclass(frozen=True)+class ZoomMap:+ """The complete zoom map for one repository at a given depth/focus."""++ root_id: str+ nodes: dict[str, ZoomNode]+ relations: tuple[ZoomRelation, ...]+ project_name: str+ total_files: int+ max_depth: int # deepest level present in this (possibly pruned) map+ truncated: bool = False # True when depth/focus pruning dropped deeper nodesdiff --git a/packages/server/src/repowise/server/services/zoom_builder/relations.py b/packages/server/src/repowise/server/services/zoom_builder/relations.pynew file mode 100644index 000000000..5ccbd3399--- /dev/null+++ b/packages/server/src/repowise/server/services/zoom_builder/relations.py@@ -0,0 +1,98 @@+"""Aggregate file->file edges into parent-relative sibling relations.++The canvas draws relations between the children of whatever node you are zoomed+into. So an edge between two files is attributed to the *lowest common ancestor*+(LCA) of the two file leaves: under that parent, it becomes an edge between the+two children whose subtrees the files live in. Counts are summed per directed+sibling pair and labelled / coupling-tiered with the same helpers the C4 view+uses, so the vocabulary stays consistent.++Pure: operates on the in-memory tree + edge list, no DB.+"""++from __future__ import annotations++from collections import defaultdict++from repowise.server.services.c4_builder.labels import coupling_strength, relation_label++from .models import ZoomNode, ZoomRelation+from .tree import file_id+++def _chain(node_id: str, nodes: dict[str, ZoomNode]) -> list[str]:+ """Root-to-node id path."""+ out: list[str] = []+ cur: str | None = node_id+ while cur is not None:+ out.append(cur)+ nxt = nodes.get(cur)+ if nxt is None: # defensive: never happens from the builder+ break+ cur = nxt.parent_id+ out.reverse()+ return out+++def aggregate_relations(+ nodes: dict[str, ZoomNode],+ edges: list[tuple[str, str, str]],+) -> tuple[ZoomRelation, ...]:+ """Roll file->file edges up to ``(parent, childA, childB)`` sibling edges."""+ chains: dict[str, list[str]] = {}++ def chain_for(path: str) -> list[str] | None:+ fid = file_id(path)+ if fid not in nodes:+ return None+ cached = chains.get(fid)+ if cached is None:+ cached = _chain(fid, nodes)+ chains[fid] = cached+ return cached++ counts: dict[tuple[str, str, str], int] = defaultdict(int)+ types: dict[tuple[str, str, str], set[str]] = defaultdict(set)++ for src, tgt, etype in edges:+ if src == tgt:+ continue+ ca = chain_for(src)+ cb = chain_for(tgt)+ if ca is None or cb is None:+ continue+ # Lowest common ancestor = last shared prefix index.+ lca_idx = -1+ for i in range(min(len(ca), len(cb))):+ if ca[i] == cb[i]:+ lca_idx = i+ else:+ break+ # The child of the LCA on each path (the LCA itself is shared, so both+ # files have a next node below it that differs).+ if lca_idx < 0 or lca_idx + 1 >= len(ca) or lca_idx + 1 >= len(cb):+ continue+ parent = ca[lca_idx]+ child_a = ca[lca_idx + 1]+ child_b = cb[lca_idx + 1]+ if child_a == child_b:+ continue+ key = (parent, child_a, child_b)+ counts[key] += 1+ types[key].add(etype or "imports")++ relations: list[ZoomRelation] = []+ for (parent, child_a, child_b), count in counts.items():+ etypes = tuple(sorted(types[(parent, child_a, child_b)]))+ relations.append(+ ZoomRelation(+ parent_id=parent,+ source_id=child_a,+ target_id=child_b,+ label=relation_label(etypes),+ edge_count=count,+ coupling=coupling_strength(count),+ )+ )+ relations.sort(key=lambda r: (r.parent_id, -r.edge_count, r.source_id, r.target_id))+ return tuple(relations)diff --git a/packages/server/src/repowise/server/services/zoom_builder/scoring.py b/packages/server/src/repowise/server/services/zoom_builder/scoring.pynew file mode 100644index 000000000..fed49e103--- /dev/null+++ b/packages/server/src/repowise/server/services/zoom_builder/scoring.py@@ -0,0 +1,209 @@+"""Execution-aware importance scoring for the zoom map ("how it runs").++A purely structural tree (biggest folder first) reads like a dependency graph.+The differentiator here is that a file's importance folds in *execution* signal:+whether it is an entry point, how close it sits to one along the import graph,+and whether the guided tour visits it. That is blended with centrality and a+light size term, with test/dead files down-weighted. The renderer's density+caps then surface execution-relevant nodes first at every zoom depth.++Two stages:+ 1. ``compute_file_signals`` — per-file signals, incl. BFS distance from the+ entry points over import edges (``on_flow`` = reachable).+ 2. ``score_tree`` — per-file raw importance, rolled up to parents, then+ normalized within each sibling set into ``importance`` (0..1) ++ ``sibling_rank`` (1 = most important sibling).++Pure: no DB, no session.+"""++from __future__ import annotations++from collections import deque+from dataclasses import dataclass, replace++from .models import ZoomNode++# Edge types that represent "uses at runtime" for reachability. Symbol-level+# containment edges are already excluded upstream (file-only architecture view).+_FLOW_EDGE_TYPES = frozenset({"imports", "depends_on"})++_SIZE_WEIGHT = {"simple": 0.0, "moderate": 0.5, "complex": 1.0}+++@dataclass(frozen=True)+class FileStat:+ """Raw per-file metrics pulled from the architecture view."""++ path: str+ pagerank_pct: float = 0.0 # 0..100+ betweenness: float = 0.0+ degree: int = 0 # in + out+ complexity: str = "simple"+ is_entry_point: bool = False+ is_test: bool = False+ is_hotspot: bool = False+ is_dead: bool = False+++@dataclass(frozen=True)+class FileSignal:+ """Derived per-file signals consumed by the tree (leaf flags) + scorer."""++ pagerank_pct: float+ betweenness: float+ degree: int+ complexity: str+ is_entry_point: bool+ is_test: bool+ is_hotspot: bool+ is_dead: bool+ on_tour: bool+ entry_dist: int | None # BFS hops from nearest entry point; None = unreachable+ on_flow: bool # entry_dist is not None+++def _bfs_distances(+ seeds: list[str],+ adjacency: dict[str, list[str]],+ known: set[str],+) -> dict[str, int]:+ """Shortest hop count from any seed to each reachable file."""+ dist: dict[str, int] = {}+ queue: deque[str] = deque()+ for s in seeds:+ if s in known and s not in dist:+ dist[s] = 0+ queue.append(s)+ while queue:+ cur = queue.popleft()+ for nxt in adjacency.get(cur, ()):+ if nxt in known and nxt not in dist:+ dist[nxt] = dist[cur] + 1+ queue.append(nxt)+ return dist+++def compute_file_signals(+ file_stats: list[FileStat],+ edges: list[tuple[str, str, str]],+ entry_points: list[str],+ tour_paths: set[str],+) -> dict[str, FileSignal]:+ """Build per-file signals, including reachability from the entry points."""+ known = {fs.path for fs in file_stats}+ adjacency: dict[str, list[str]] = {}+ for src, tgt, etype in edges:+ if etype in _FLOW_EDGE_TYPES and src in known and tgt in known:+ adjacency.setdefault(src, []).append(tgt)++ dist = _bfs_distances(entry_points, adjacency, known)++ signals: dict[str, FileSignal] = {}+ for fs in file_stats:+ d = dist.get(fs.path)+ signals[fs.path] = FileSignal(+ pagerank_pct=fs.pagerank_pct,+ betweenness=fs.betweenness,+ degree=fs.degree,+ complexity=fs.complexity,+ is_entry_point=fs.is_entry_point,+ is_test=fs.is_test,+ is_hotspot=fs.is_hotspot,+ is_dead=fs.is_dead,+ on_tour=fs.path in tour_paths,+ entry_dist=d,+ on_flow=d is not None,+ )+ return signals+++def _minmax(values: list[float]) -> tuple[float, float]:+ if not values:+ return 0.0, 1.0+ lo, hi = min(values), max(values)+ return lo, (hi if hi > lo else lo + 1.0)+++def _file_raw(sig: FileSignal, deg_lo: float, deg_span: float, bet_lo: float, bet_span: float) -> float:+ pr = sig.pagerank_pct / 100.0+ deg_n = (sig.degree - deg_lo) / deg_span+ bet_n = (sig.betweenness - bet_lo) / bet_span+ centrality = 0.5 * pr + 0.3 * deg_n + 0.2 * bet_n++ entry = 1.0 if sig.is_entry_point else 0.0+ proximity = 1.0 / (1.0 + sig.entry_dist) if sig.entry_dist is not None else 0.0+ on_tour = 1.0 if sig.on_tour else 0.0+ execution = 0.5 * entry + 0.35 * proximity + 0.15 * on_tour++ hotspot = 1.0 if sig.is_hotspot else 0.0+ size = _SIZE_WEIGHT.get(sig.complexity, 0.0)++ raw = 0.30 * centrality + 0.45 * execution + 0.15 * hotspot + 0.10 * size+ if sig.is_test:+ raw *= 0.4+ if sig.is_dead:+ raw *= 0.3+ return max(raw, 0.0)+++def score_tree(+ root_id: str,+ nodes: dict[str, ZoomNode],+ signals: dict[str, FileSignal],+) -> dict[str, ZoomNode]:+ """Return ``nodes`` with ``importance`` (0..1) + ``sibling_rank`` filled.++ File raw scores come from ``signals``; a parent's raw score blends the max+ and mean of its children (so one critical file lifts its folder without a+ large inert folder dominating by sheer count). Importance is then normalized+ within each sibling set, so it is directly comparable to the density caps+ and treemap areas the renderer uses per parent.+ """+ deg_vals = [float(s.degree) for s in signals.values()]+ bet_vals = [s.betweenness for s in signals.values()]+ deg_lo, deg_hi = _minmax(deg_vals)+ bet_lo, bet_hi = _minmax(bet_vals)+ deg_span = deg_hi - deg_lo+ bet_span = bet_hi - bet_lo++ raw: dict[str, float] = {}++ def compute_raw(node_id: str) -> float:+ node = nodes[node_id]+ if node.kind == "file":+ sig = signals.get(node.path)+ value = _file_raw(sig, deg_lo, deg_span, bet_lo, bet_span) if sig else 0.0+ raw[node_id] = value+ return value+ child_raws = [compute_raw(c) for c in node.children]+ if child_raws:+ value = 0.6 * max(child_raws) + 0.4 * (sum(child_raws) / len(child_raws))+ else:+ value = 0.0+ raw[node_id] = value+ return value++ compute_raw(root_id)++ updated: dict[str, ZoomNode] = dict(nodes)++ def normalize_children(node_id: str) -> None:+ node = updated[node_id]+ children = list(node.children)+ if children:+ ranked = sorted(children, key=lambda c: (-raw[c], updated[c].name))+ top = raw[ranked[0]] or 1.0+ for rank, cid in enumerate(ranked, start=1):+ updated[cid] = replace(+ updated[cid],+ importance=raw[cid] / top,+ sibling_rank=rank,+ )+ for cid in children:+ normalize_children(cid)++ # The root has no siblings; pin it to full importance.+ updated[root_id] = replace(updated[root_id], importance=1.0, sibling_rank=1)+ normalize_children(root_id)+ return updateddiff --git a/packages/server/src/repowise/server/services/zoom_builder/tree.py b/packages/server/src/repowise/server/services/zoom_builder/tree.pynew file mode 100644index 000000000..44c0cc405--- /dev/null+++ b/packages/server/src/repowise/server/services/zoom_builder/tree.py@@ -0,0 +1,279 @@+"""Assemble the nested containment tree for the zoom map.++ system -> layer -> sub-group -> folder(s) -> file++Layers and their curated sub-groups come from the architecture view; the+folder tier is a directory trie built here from the file paths, with+single-child folder chains compressed (``a -> a/b -> a/b/c`` collapses to one+``a/b/c`` node) so the zoom does not waste a level on pass-through directories.++This is deliberately NOT ``derive_modules`` (which right-sizes wiki modules to+8-120 files): the zoom tree wants the true directory nesting so a viewer can+zoom folder by folder.++Pure and framework-agnostic: inputs are plain specs, output is a dict of frozen+``ZoomNode``. Importance, metrics, and layout are filled by later passes.+"""++from __future__ import annotations++from dataclasses import dataclass, field++from .models import ZoomNode+++@dataclass(frozen=True)+class GroupSpec:+ """A curated sub-group inside a layer."""++ id: str+ name: str+ node_ids: list[str] # repo-relative file paths+++@dataclass(frozen=True)+class LayerSpec:+ """A curated architectural layer, with its files and optional sub-groups."""++ id: str+ name: str+ display_order: int+ node_ids: list[str] # repo-relative file paths (every file in the layer)+ sub_groups: list[GroupSpec] = field(default_factory=list)+++@dataclass(frozen=True)+class LeafInfo:+ """Per-file presentation + signal flags carried onto the file leaf node."""++ summary: str = ""+ language: str | None = None+ is_entry_point: bool = False+ is_hotspot: bool = False+ is_dead: bool = False+ is_test: bool = False+ on_flow: bool = False+++SYSTEM_ID = "zm:sys"+++def layer_id(raw: str) -> str:+ return f"zm:L:{raw}"+++def group_id(raw: str) -> str:+ return f"zm:G:{raw}"+++def folder_id(scope: str, path: str) -> str:+ """Folder ids are scoped by their owning layer/group.++ A directory path is NOT globally unique in this tree: the same dir can hold+ files assigned to different layers, and can appear under both a sub-group and+ its layer's ungrouped bucket. Qualifying the id with the owning scope keeps+ every folder node id unique (within one scope the trie paths are unique).+ """+ return f"zm:D:{scope}:{path}"+++def file_id(path: str) -> str:+ # Files partition across the whole tree (each file is in exactly one layer+ # and one sub-group), so a path-based id is globally unique and stable for+ # deep-linking / focus.+ return f"zm:F:{path}"+++# ---------------------------------------------------------------------------+# Directory trie (mutable during construction)+# ---------------------------------------------------------------------------+++class _Dir:+ __slots__ = ("files", "name", "path", "subdirs")++ def __init__(self, name: str, path: str) -> None:+ self.name = name+ self.path = path+ self.subdirs: dict[str, _Dir] = {}+ self.files: list[str] = []+++def _insert(root: _Dir, path: str) -> None:+ parts = path.split("/")+ *dirs, _fname = parts+ if not _fname:+ # Malformed (empty or trailing-slash) path: skip rather than mint a+ # blank-named leaf. The architecture view never emits these.+ return+ cur = root+ acc: list[str] = []+ for d in dirs:+ acc.append(d)+ key = "/".join(acc)+ nxt = cur.subdirs.get(d)+ if nxt is None:+ nxt = _Dir(name=d, path=key)+ cur.subdirs[d] = nxt+ cur = nxt+ 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``."""+ name = node.name+ while len(node.subdirs) == 1 and not node.files:+ (only,) = node.subdirs.values()+ name = f"{name}/{only.name}"+ node = only+ return name, node+++# ---------------------------------------------------------------------------+# Builder+# ---------------------------------------------------------------------------+++class _Builder:+ def __init__(self, leaf_info: dict[str, LeafInfo]) -> None:+ self.leaf_info = leaf_info+ self.nodes: dict[str, ZoomNode] = {}++ def add(self, node: ZoomNode) -> str:+ self.nodes[node.id] = node+ return node.id++ def emit_file(self, path: str, parent_id: str, level: int) -> str:+ info = self.leaf_info.get(path, LeafInfo())+ name = path.rsplit("/", 1)[-1]+ return self.add(+ ZoomNode(+ id=file_id(path),+ parent_id=parent_id,+ level=level,+ kind="file",+ name=name,+ path=path,+ summary=info.summary,+ language=info.language,+ is_entry_point=info.is_entry_point,+ is_hotspot=info.is_hotspot,+ is_dead=info.is_dead,+ is_test=info.is_test,+ on_flow=info.on_flow,+ )+ )++ def emit_dir(self, dnode: _Dir, parent_id: str, level: int, scope: str) -> str:+ name, node = _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))+ self.add(+ ZoomNode(+ id=fid,+ parent_id=parent_id,+ level=level,+ kind="folder",+ name=name,+ path=node.path,+ children=tuple(children),+ )+ )+ return fid++ def attach_files(+ self, file_paths: list[str], parent_id: str, child_level: int, scope: str+ ) -> list[str]:+ """Build a folder trie from ``file_paths`` and attach it under ``parent_id``.++ ``scope`` (the owning layer/group id) qualifies folder node ids so the+ same directory path under two different parents cannot collide. Files at+ the parent's own level attach as file leaves; everything else nests under+ compressed folder nodes.+ """+ root = _Dir(name="", path="")+ for path in file_paths:+ _insert(root, path)+ children: list[str] = []+ for sub in sorted(root.subdirs.values(), key=lambda d: d.name):+ children.append(self.emit_dir(sub, parent_id, child_level, scope))+ for path in sorted(root.files):+ children.append(self.emit_file(path, parent_id, child_level))+ return children+++def build_tree(+ project_name: str,+ layers: list[LayerSpec],+ leaf_info: dict[str, LeafInfo],+) -> 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 under+ their layer so the file partition is preserved (every file appears once).+ """+ b = _Builder(leaf_info)+ layer_ids: list[str] = []++ for layer in sorted(layers, key=lambda layer_: layer_.display_order):+ lid = layer_id(layer.id)+ layer_children: list[str] = []+ layer_node_set = set(layer.node_ids)+ grouped: set[str] = set()++ for grp in layer.sub_groups:+ # Keep only files that belong to this layer AND have not already been+ # claimed by an earlier sub-group, so an overlapping membership can+ # never emit the same file leaf under two parents (which would+ # corrupt the tree into a non-partition).+ group_files = [p for p in grp.node_ids if p in layer_node_set and p not in grouped]+ if not group_files:+ continue+ grouped.update(group_files)+ gid = group_id(grp.id)+ group_children = b.attach_files(group_files, gid, child_level=3, scope=gid)+ b.add(+ ZoomNode(+ id=gid,+ parent_id=lid,+ level=2,+ kind="group",+ name=grp.name,+ children=tuple(group_children),+ )+ )+ layer_children.append(gid)++ # Files not claimed by any sub-group hang directly off the layer.+ ungrouped = [p for p in layer.node_ids if p not in grouped]+ layer_children.extend(b.attach_files(ungrouped, lid, child_level=2, scope=lid))++ b.add(+ ZoomNode(+ id=lid,+ parent_id=SYSTEM_ID,+ level=1,+ kind="layer",+ name=layer.name,+ children=tuple(layer_children),+ )+ )+ layer_ids.append(lid)++ b.add(+ ZoomNode(+ id=SYSTEM_ID,+ parent_id=None,+ level=0,+ kind="system",+ name=project_name,+ children=tuple(layer_ids),+ )+ )+ return SYSTEM_ID, b.nodesdiff --git a/tests/unit/server/services/test_zoom_builder.py b/tests/unit/server/services/test_zoom_builder.pynew file mode 100644index 000000000..c26cda56e--- /dev/null+++ b/tests/unit/server/services/test_zoom_builder.py@@ -0,0 +1,479 @@+"""Unit tests for the zoom-map builder (pure functions, no DB)."""++from __future__ import annotations++from repowise.server.services.c4_builder.models import (+ ArchEdge,+ ArchitectureView,+ ArchLayer,+ ArchNode,+ ArchSubGroup,+ ArchTourStep,+)+from repowise.server.services.zoom_builder import assemble_zoom_map+from repowise.server.services.zoom_builder.layout import lay_out+from repowise.server.services.zoom_builder.metrics import rollup_metrics+from repowise.server.services.zoom_builder.models import ZoomNode+from repowise.server.services.zoom_builder.relations import aggregate_relations+from repowise.server.services.zoom_builder.scoring import (+ FileStat,+ compute_file_signals,+ score_tree,+)+from repowise.server.services.zoom_builder.tree import (+ GroupSpec,+ LayerSpec,+ LeafInfo,+ build_tree,+ file_id,+ folder_id,+)++# ---------------------------------------------------------------------------+# tree+# ---------------------------------------------------------------------------+++def test_build_tree_partitions_every_file_once():+ layers = [+ LayerSpec(+ id="layer:service",+ name="Service",+ display_order=0,+ node_ids=["a/b/c/f1.py", "a/b/c/f2.py", "a/d/g1.py"],+ ),+ LayerSpec(+ id="layer:test",+ name="Test",+ display_order=1,+ node_ids=["tests/t1.py"],+ ),+ ]+ root_id, nodes = build_tree("proj", layers, {})++ files = [n for n in nodes.values() if n.kind == "file"]+ paths = sorted(n.path for n in files)+ assert paths == ["a/b/c/f1.py", "a/b/c/f2.py", "a/d/g1.py", "tests/t1.py"]+ # exactly one leaf per file+ assert len(files) == 4+ # root is the system, with the two layers as children+ assert nodes[root_id].kind == "system"+ assert len(nodes[root_id].children) == 2+++def test_build_tree_compresses_single_child_folder_chains():+ layers = [+ LayerSpec(+ id="layer:service",+ name="Service",+ display_order=0,+ node_ids=["a/b/c/f1.py", "a/b/c/f2.py"],+ ),+ ]+ _root, nodes = build_tree("proj", layers, {})+ # a -> b -> c collapses to a single folder "a/b/c"+ folders = [n for n in nodes.values() if n.kind == "folder"]+ assert len(folders) == 1+ assert folders[0].name == "a/b/c"+ assert folders[0].path == "a/b/c"+ assert len(folders[0].children) == 2+++def test_build_tree_subgroups_and_ungrouped_files():+ layers = [+ LayerSpec(+ id="layer:service",+ name="Service",+ display_order=0,+ node_ids=["svc/ingest/a.py", "svc/ingest/b.py", "svc/loose.py"],+ sub_groups=[+ GroupSpec(+ id="layer:service:ingest",+ name="ingest",+ node_ids=["svc/ingest/a.py", "svc/ingest/b.py"],+ ),+ ],+ ),+ ]+ _root, nodes = build_tree("proj", layers, {})+ groups = [n for n in nodes.values() if n.kind == "group"]+ assert len(groups) == 1+ grp = groups[0]+ # the grouped files live under the group+ grouped_files = {nodes[c].path for cid in grp.children for c in _descend_files(nodes, cid)}+ assert grouped_files == {"svc/ingest/a.py", "svc/ingest/b.py"}+ # the ungrouped file attaches under the layer directly, not the group+ lid = grp.parent_id+ layer_file_paths = {+ nodes[fid_].path+ for cid in nodes[lid].children+ for fid_ in _descend_files(nodes, cid)+ }+ assert "svc/loose.py" in layer_file_paths+++def test_build_tree_overlapping_subgroups_keep_partition():+ # Two sub-groups both claim "svc/shared.py"; the file must appear exactly+ # once (under the first group), never duplicated into a non-tree.+ layers = [+ LayerSpec(+ id="layer:service",+ name="Service",+ display_order=0,+ node_ids=["svc/a.py", "svc/b.py", "svc/shared.py"],+ sub_groups=[+ GroupSpec(id="g1", name="g1", node_ids=["svc/a.py", "svc/shared.py"]),+ GroupSpec(id="g2", name="g2", node_ids=["svc/b.py", "svc/shared.py"]),+ ],+ ),+ ]+ _root, nodes = build_tree("proj", layers, {})+ leaves = [n for n in nodes.values() if n.kind == "file"]+ # every file appears exactly once+ assert sorted(n.path for n in leaves) == ["svc/a.py", "svc/b.py", "svc/shared.py"]+ shared = [n for n in leaves if n.path == "svc/shared.py"]+ assert len(shared) == 1+ # and it is referenced by exactly one parent's children list+ parents = [n for n in nodes.values() if shared[0].id in n.children]+ assert len(parents) == 1+ assert parents[0].id == shared[0].parent_id+++def test_build_tree_skips_trailing_slash_paths():+ layers = [+ LayerSpec(+ id="layer:service",+ name="Service",+ display_order=0,+ node_ids=["svc/real.py", "svc/bogus/"],+ ),+ ]+ _root, nodes = build_tree("proj", layers, {})+ leaves = [n.path for n in nodes.values() if n.kind == "file"]+ assert leaves == ["svc/real.py"]+ assert all(n.name for n in nodes.values()) # no blank-named node+++def _descend_files(nodes: dict[str, ZoomNode], node_id: str) -> list[str]:+ node = nodes[node_id]+ if node.kind == "file":+ return [node_id]+ out: list[str] = []+ for c in node.children:+ out.extend(_descend_files(nodes, c))+ return out+++# ---------------------------------------------------------------------------+# scoring+# ---------------------------------------------------------------------------+++def test_compute_file_signals_bfs_reachability():+ stats = [FileStat(path="main.py"), FileStat(path="util.py"), FileStat(path="orphan.py")]+ edges = [("main.py", "util.py", "imports")]+ signals = compute_file_signals(stats, edges, entry_points=["main.py"], tour_paths=set())++ assert signals["main.py"].entry_dist == 0+ assert signals["main.py"].on_flow is True+ assert signals["util.py"].entry_dist == 1+ assert signals["util.py"].on_flow is True+ assert signals["orphan.py"].entry_dist is None+ assert signals["orphan.py"].on_flow is False+++def test_score_tree_ranks_entry_point_above_inert_sibling():+ layers = [+ LayerSpec(+ id="layer:service",+ name="Service",+ display_order=0,+ node_ids=["pkg/main.py", "pkg/dead.py"],+ ),+ ]+ stats = [+ FileStat(path="pkg/main.py", is_entry_point=True, pagerank_pct=90.0, degree=10),+ FileStat(path="pkg/dead.py", is_dead=True, pagerank_pct=1.0, degree=0),+ ]+ signals = compute_file_signals(stats, [], entry_points=["pkg/main.py"], tour_paths=set())+ leaf_info = {+ "pkg/main.py": LeafInfo(is_entry_point=True, on_flow=True),+ "pkg/dead.py": LeafInfo(is_dead=True),+ }+ root_id, nodes = build_tree("proj", layers, leaf_info)+ nodes = score_tree(root_id, nodes, signals)++ main_node = nodes[file_id("pkg/main.py")]+ dead_node = nodes[file_id("pkg/dead.py")]+ assert main_node.sibling_rank == 1+ assert dead_node.sibling_rank == 2+ assert main_node.importance > dead_node.importance+ # top sibling normalizes to 1.0+ assert main_node.importance == 1.0+++# ---------------------------------------------------------------------------+# metrics+# ---------------------------------------------------------------------------+++def test_rollup_metrics_counts_subtree():+ layers = [+ LayerSpec(+ id="layer:service",+ name="Service",+ display_order=0,+ node_ids=["pkg/a.py", "pkg/b.py", "pkg/sub/c.py"],+ ),+ ]+ leaf_info = {+ "pkg/a.py": LeafInfo(is_entry_point=True, on_flow=True),+ "pkg/b.py": LeafInfo(is_hotspot=True),+ "pkg/sub/c.py": LeafInfo(is_dead=True),+ }+ root_id, nodes = build_tree("proj", layers, leaf_info)+ nodes = rollup_metrics(root_id, nodes)++ root = nodes[root_id]+ assert root.metrics.file_count == 3+ assert root.metrics.hotspot_count == 1+ assert root.metrics.dead_count == 1+ assert root.metrics.entry_point_count == 1+ assert root.metrics.on_flow_count == 1+++# ---------------------------------------------------------------------------+# layout+# ---------------------------------------------------------------------------+++def test_layout_is_deterministic_and_within_unit_box():+ layers = [+ LayerSpec(+ id="layer:service",+ name="Service",+ display_order=0,+ node_ids=[f"pkg/f{i}.py" for i in range(6)],+ ),+ ]+ leaf_info = {f"pkg/f{i}.py": LeafInfo() for i in range(6)}+ root_id, nodes = build_tree("proj", layers, leaf_info)+ nodes = score_tree(root_id, nodes, compute_file_signals(+ [FileStat(path=f"pkg/f{i}.py", degree=i) for i in range(6)], [], [], set()+ ))+ a = lay_out(root_id, nodes)+ b = lay_out(root_id, nodes)++ for nid, node in a.items():+ assert node.layout == b[nid].layout # deterministic+ rect = node.layout+ assert rect is not None+ assert -1e-6 <= rect.x <= 1.0 + 1e-6+ assert -1e-6 <= rect.y <= 1.0 + 1e-6+ assert rect.x + rect.w <= 1.0 + 1e-6+ assert rect.y + rect.h <= 1.0 + 1e-6++ # children of a parent tile its unit box (areas sum ~ 1)+ folder = next(n for n in a.values() if n.children and n.kind != "system")+ total = sum(a[c].layout.w * a[c].layout.h for c in folder.children)+ assert abs(total - 1.0) < 1e-3+++# ---------------------------------------------------------------------------+# relations+# ---------------------------------------------------------------------------+++def test_aggregate_relations_attributes_edge_to_lca():+ layers = [+ LayerSpec(+ id="layer:service",+ name="Service",+ display_order=0,+ node_ids=["svc/api/a.py", "svc/db/b.py"],+ ),+ ]+ root_id, nodes = build_tree("proj", layers, {})+ nodes = rollup_metrics(root_id, nodes)+ edges = [("svc/api/a.py", "svc/db/b.py", "imports")]+ rels = aggregate_relations(nodes, edges)++ assert len(rels) == 1+ rel = rels[0]+ # both files share the "svc" prefix (a single intermediate folder), so the+ # LCA is that folder and the relation is between its "api" and "db" children.+ # Folder ids are scoped by the owning layer.+ scope = "zm:L:layer:service"+ assert rel.parent_id == folder_id(scope, "svc")+ assert rel.source_id == folder_id(scope, "svc/api")+ assert rel.target_id == folder_id(scope, "svc/db")+ assert rel.edge_count == 1+ assert rel.label # readable label set+++def test_build_tree_same_dir_across_layers_no_id_collision():+ # A single directory "shared/" holds files assigned to two different layers.+ # The folder nodes must get distinct (scoped) ids, so neither overwrites the+ # other and both files survive under the right layer.+ layers = [+ LayerSpec(+ id="layer:service",+ name="Service",+ display_order=0,+ node_ids=["shared/svc.py"],+ ),+ LayerSpec(+ id="layer:util",+ name="Utility",+ display_order=1,+ node_ids=["shared/util.py"],+ ),+ ]+ _root, nodes = build_tree("proj", layers, {})+ leaves = sorted(n.path for n in nodes.values() if n.kind == "file")+ assert leaves == ["shared/svc.py", "shared/util.py"]+ shared_folders = [n for n in nodes.values() if n.kind == "folder" and n.path == "shared"]+ assert len(shared_folders) == 2 # one per layer, distinct ids+ assert len({f.id for f in shared_folders}) == 2+ # each shared folder is under a different layer+ assert {nodes[f.parent_id].kind for f in shared_folders} == {"layer"}+ assert len({f.parent_id for f in shared_folders}) == 2+++# ---------------------------------------------------------------------------+# assemble + prune (end-to-end over a synthetic ArchitectureView)+# ---------------------------------------------------------------------------+++def _node(path: str, **over) -> ArchNode:+ base = dict(+ id=path,+ node_type="file",+ name=path.rsplit("/", 1)[-1],+ file_path=path,+ line_range=None,+ summary="",+ complexity="simple",+ tags=[],+ language="python",+ pagerank=0.0,+ pagerank_percentile=0.0,+ betweenness=0.0,+ in_degree=0,+ out_degree=0,+ community_id=None,+ is_entry_point=False,+ is_test=False,+ is_hotspot=False,+ is_dead=False,+ has_doc=False,+ primary_owner=None,+ primary_owner_pct=None,+ bus_factor=None,+ )+ base.update(over)+ return ArchNode(**base)+++def _view() -> ArchitectureView:+ nodes = [+ _node("pkg/main.py", is_entry_point=True, pagerank_percentile=95.0, in_degree=1, out_degree=2),+ _node("pkg/core/engine.py", pagerank_percentile=80.0, in_degree=2),+ _node("pkg/core/util.py", pagerank_percentile=10.0),+ ]+ layers = [+ ArchLayer(+ id="layer:service",+ name="Service",+ description="",+ node_ids=["pkg/main.py", "pkg/core/engine.py", "pkg/core/util.py"],+ file_count=3,+ complexity_distribution={"simple": 3, "moderate": 0, "complex": 0},+ health_score=None,+ sub_groups=[+ ArchSubGroup(+ id="layer:service:core",+ name="core",+ node_ids=["pkg/core/engine.py", "pkg/core/util.py"],+ ),+ ],+ display_order=0,+ ),+ ]+ edges = [+ ArchEdge("pkg/main.py", "pkg/core/engine.py", "imports", "forward", 1.0, 1.0),+ ArchEdge("pkg/core/engine.py", "pkg/core/util.py", "imports", "forward", 1.0, 1.0),+ ]+ tour = [+ ArchTourStep(order=0, title="Start", description="", node_ids=["pkg/main.py"]),+ ]+ return ArchitectureView(+ project_name="proj",+ project_description="",+ layers=layers,+ nodes=nodes,+ edges=edges,+ tour=tour,+ total_files=3,+ total_symbols=0,+ total_edges=2,+ languages=["python"],+ frameworks=[],+ external_systems=[],+ entry_points=["pkg/main.py"],+ )+++def test_assemble_zoom_map_full():+ zoom = assemble_zoom_map(_view())+ assert zoom.root_id == "zm:sys"+ assert zoom.total_files == 3+ assert zoom.nodes[zoom.root_id].kind == "system"+ # every file became a leaf with on_flow set (all reachable from main.py)+ files = [n for n in zoom.nodes.values() if n.kind == "file"]+ assert {n.path for n in files} == {"pkg/main.py", "pkg/core/engine.py", "pkg/core/util.py"}+ assert all(n.on_flow for n in files)+ # the entry-point file is the top-ranked sibling under its parent+ main = zoom.nodes[file_id("pkg/main.py")]+ assert main.is_entry_point and main.sibling_rank == 1+ # layout assigned everywhere+ assert all(n.layout is not None for n in zoom.nodes.values())+ assert not zoom.truncated+++def test_assemble_zoom_map_max_depth_prunes_and_flags_truncated():+ zoom = assemble_zoom_map(_view(), max_depth=1)+ # only system (level 0) + layers (level 1) survive+ levels = {n.level for n in zoom.nodes.values()}+ assert levels == {0, 1}+ assert zoom.truncated is True+ # the layer's children were dropped at the frontier+ layer = next(n for n in zoom.nodes.values() if n.kind == "layer")+ assert layer.children == ()+++def test_assemble_zoom_map_focus_reroots_subtree():+ full = assemble_zoom_map(_view())+ group = next(n for n in full.nodes.values() if n.kind == "group")+ focused = assemble_zoom_map(_view(), focus=group.id)+ assert focused.root_id == group.id+ assert focused.nodes[group.id].parent_id is None+ # only the group subtree is served+ assert all(+ n.id == group.id or _has_ancestor(focused.nodes, n.id, group.id)+ for n in focused.nodes.values()+ )+++def test_assemble_zoom_map_unknown_focus_falls_back_to_system():+ zoom = assemble_zoom_map(_view(), focus="zm:F:does/not/exist")+ assert zoom.root_id == "zm:sys"+++def _has_ancestor(nodes: dict[str, ZoomNode], node_id: str, ancestor_id: str) -> bool:+ cur = nodes[node_id].parent_id+ while cur is not None:+ if cur == ancestor_id:+ return True+ cur = nodes[cur].parent_id+ return False