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): make the knowledge graph arrows mean execution (#1832)
Raghav Chamadiya4b79877dd28f
diff --git a/packages/server/src/repowise/server/services/zoom_builder/__init__.py b/packages/server/src/repowise/server/services/zoom_builder/__init__.pyindex 8694b439a..45e904976 100644--- a/packages/server/src/repowise/server/services/zoom_builder/__init__.py+++ b/packages/server/src/repowise/server/services/zoom_builder/__init__.py@@ -21,6 +21,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.server.services.c4_builder.architecture import build_architecture_viewfrom repowise.server.services.c4_builder.models import ArchitectureView+from .calls import load_projected_callsfrom .metrics import rollup_health, rollup_metricsfrom .models import ZoomMap, ZoomNode, ZoomRelationfrom .relations import aggregate_relations@@ -55,6 +56,7 @@ def assemble_zoom_map(focus: str | None = None,health: dict[str, tuple[float, int]] | None = None,modules: dict[str, ModuleInfo] | None = None,+ call_edges: list[tuple[str, str, str]] | None = None,) -> ZoomMap:"""Pure assembly: ``ArchitectureView`` -> ``ZoomMap``. No DB.@@ -67,6 +69,11 @@ def assemble_zoom_map(folder card reads as the subsystem the docs name rather than as a pathsegment. Also optional: a repository indexed without a wiki has none, andthe hosted builder does not have them in its artifacts yet.++ ``call_edges`` are symbol-level execution edges already projected onto file+ pairs by :mod:`.calls`. The view cannot carry them -- it is loaded file-only,+ so both endpoints of a symbol edge are filtered out before it arrives -- so+ they come in beside it. Optional for the same reasons as the two above."""health = health or {}# The view is loaded file-only, but the curated node_type can be@@ -99,6 +106,7 @@ def assemble_zoom_map(for n in file_nodes]edges = [(e.source, e.target, e.edge_type) for e in view.edges]+ edges.extend(call_edges or ())signals = compute_file_signals(file_stats,@@ -240,6 +248,15 @@ async def build_zoom_map(view = await build_architecture_view(session, repo_id, include_symbols=False)modules = await _load_module_names(session, repo_id)+ # The view is file-only, so the whole symbol-level execution graph was+ # filtered out of it. Read it back and project it onto file pairs.+ call_edges = await load_projected_calls(+ session,+ repo_id,+ # Same file-node test the assembly uses, so a projected edge can only+ # land on a file the tree will actually contain.+ {n.id for n in view.nodes if n.line_range is None and n.id == n.file_path},+ )# 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@@ -254,7 +271,12 @@ async def build_zoom_map(for m in metrics}return assemble_zoom_map(- view, max_depth=max_depth, focus=focus, health=health, modules=modules+ view,+ max_depth=max_depth,+ focus=focus,+ health=health,+ modules=modules,+ call_edges=call_edges,)diff --git a/packages/server/src/repowise/server/services/zoom_builder/calls.py b/packages/server/src/repowise/server/services/zoom_builder/calls.pynew file mode 100644index 000000000..6255a5807--- /dev/null+++ b/packages/server/src/repowise/server/services/zoom_builder/calls.py@@ -0,0 +1,98 @@+"""Project the symbol-level execution graph onto the files that declare it.++The zoom map loads its view with ``include_symbols=False``, which keeps only+``node_type == "file"`` nodes and then keeps only edges whose *both* endpoints+survive. Every ``calls`` / ``dispatches_to`` / ``extends`` / ``implements`` edge+is symbol-to-symbol, so all of them are dropped before the builder ever sees+them and the map can only ever draw imports, uses and co-changes.++Projecting a symbol edge onto ``(file of source, file of target)`` puts them+back. Measured on eight indexed repositories, that is mostly a *relabelling*+rather than new arrows -- a cross-file call almost always rides an import that+was already drawn -- and relabelling is the point: ``calls`` outranks+``imports`` in the verb priority, so a pair that genuinely invokes reads as+invocation instead of as a file-header fact.++Reliability is core's call, not ours: :func:`is_reliable_execution_edge` drops+the ``global_unique`` resolution origin, which is the same bar the coverage tab+and the health engine hold their execution claims to. The two guards below are+the ones projection itself creates.+"""++from __future__ import annotations++import os++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.analysis.execution_graph import file_of_symbol, is_reliable_execution_edge+from repowise.core.ingestion.models import EXECUTION_EDGE_TYPES+from repowise.core.persistence.models import GraphEdge+++def _ext(path: str) -> str:+ """Lower-case extension of *path* (``a/b/x.py`` -> ``py``), ``""`` if none."""+ base = os.path.basename(path)+ return base.rsplit(".", 1)[1].lower() if "." in base else ""+++def keep_projected_edge(src_file: str, tgt_file: str) -> bool:+ """Whether a symbol edge projected onto its two files is a real relation.++ Two guards, both artefacts of the projection rather than of the data:++ * a self-loop is what every intra-file call becomes, and those *outnumber*+ the cross-file ones (12,797 of 24,310 candidates on PowerToys). The canvas+ draws relations between siblings, so a self-loop has nowhere to go.+ * a cross-extension pair is more often a coincidence than a call -- a+ same-named module in two languages, a test naming both ends -- and keeping+ it lets the arrow stitch unrelated packages together.++ No confidence floor. The obvious third guard is inert: the persisted minimum+ confidence for an execution edge is exactly 0.5 on all eight repositories+ measured, so a 0.5 floor drops nothing that the origin filter has not+ already dropped.+ """+ if not src_file or not tgt_file or src_file == tgt_file:+ return False+ return _ext(src_file) == _ext(tgt_file)+++async def load_projected_calls(+ session: AsyncSession, repo_id: str, known_files: set[str]+) -> list[tuple[str, str, str]]:+ """``(source file, target file, edge_type)`` for every reliable execution edge.++ Restricted to ``known_files`` so the projection cannot introduce a file the+ view does not know about; the tree is built from the view's nodes and an+ edge to anything else would be dropped downstream anyway.++ Edge type is preserved rather than collapsed, because the verb is the+ payload: :func:`~repowise.server.services.c4_builder.labels.relation_label`+ turns the set of types on a pair into the arrow's word, and the canvas+ filters on that word.+ """+ rows = await session.execute(+ select(+ GraphEdge.source_node_id,+ GraphEdge.target_node_id,+ GraphEdge.edge_type,+ GraphEdge.resolution_origin,+ ).where(+ GraphEdge.repository_id == repo_id,+ GraphEdge.edge_type.in_(sorted(EXECUTION_EDGE_TYPES)),+ )+ )+ projected: list[tuple[str, str, str]] = []+ for source, target, edge_type, origin in rows:+ if not is_reliable_execution_edge(edge_type, origin):+ continue+ src_file = file_of_symbol(source)+ tgt_file = file_of_symbol(target)+ if not keep_projected_edge(src_file, tgt_file):+ continue+ if src_file not in known_files or tgt_file not in known_files:+ continue+ projected.append((src_file, tgt_file, edge_type))+ return projecteddiff --git a/packages/server/src/repowise/server/services/zoom_builder/scoring.py b/packages/server/src/repowise/server/services/zoom_builder/scoring.pyindex d70948a27..1f06be21d 100644--- a/packages/server/src/repowise/server/services/zoom_builder/scoring.py+++ b/packages/server/src/repowise/server/services/zoom_builder/scoring.py@@ -2,14 +2,16 @@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.+whether it is an entry point, how close it sits to one along the dependency and+call graphs, 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).+ entry points over dependency *and* projected call edges (``on_flow`` =+ reachable).2. ``score_tree`` — per-file raw importance, rolled up to parents, thennormalized within each sibling set into ``importance`` (0..1) +``sibling_rank`` (1 = most important sibling).@@ -22,7 +24,10 @@ from __future__ import annotationsfrom collections import dequefrom dataclasses import dataclass, replace-from repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPES+from repowise.core.ingestion.models import (+ EXECUTION_EDGE_TYPES,+ FILE_DEPENDENCY_EDGE_TYPES,+)from .models import ZoomNode@@ -30,7 +35,20 @@ from .models import ZoomNode# {"imports", "depends_on"}; "depends_on" is a knowledge-graph export label and# never a persisted edge_type, so only "imports" ever matched and framework and# dynamic wiring were invisible to reachability.-_FLOW_EDGE_TYPES = FILE_DEPENDENCY_EDGE_TYPES+#+# The call graph is a union with the file-dependency set, not a replacement for+# it, and the measurement is one-sided. Walking calls *alone* reaches strictly+# fewer files on every repository tried: 45.1% -> 9.8% on Ocelot, 42.3% -> 1.9%+# on eShopOnWeb, 39.7% -> 15.3% on flask. A call edge joins two functions, so it+# can never express the module-level wiring — a router importing its handlers, a+# package __init__ pulling in its submodules — that is how execution actually+# arrives at most files. Taking the union instead adds what calls know on top:+# 20.6% -> 38.6% on celery, 45.1% -> 52.8% on Ocelot, 44.4% -> 51.1% on+# PowerToys.+#+# These types only ever match if the caller passed projected call edges in; the+# view's own edges are file-level and carry none of them.+_FLOW_EDGE_TYPES = FILE_DEPENDENCY_EDGE_TYPES | EXECUTION_EDGE_TYPES_SIZE_WEIGHT = {"simple": 0.0, "moderate": 0.5, "complex": 1.0}diff --git a/packages/ui/__tests__/zoom/relation-summary.test.ts b/packages/ui/__tests__/zoom/relation-summary.test.tsindex 213f9d472..bd8dd6739 100644--- a/packages/ui/__tests__/zoom/relation-summary.test.ts+++ b/packages/ui/__tests__/zoom/relation-summary.test.ts@@ -3,6 +3,7 @@ import {CO_CHANGES,describeCap,describeRelations,+ toggleVerb,indexRelationsByNode,summarizeRelations,} from "../../src/zoom/relation-summary";@@ -111,3 +112,26 @@ describe("describeCap", () => {);});});++describe("toggleVerb", () => {+ it("starts a filter from the unfiltered state", () => {+ expect([...(toggleVerb(null, "calls") ?? [])]).toEqual(["calls"]);+ });++ it("accumulates, so the control is a multi-select and not a radio group", () => {+ const one = toggleVerb(null, "calls");+ expect([...(toggleVerb(one, "imports") ?? [])].sort()).toEqual(["calls", "imports"]);+ });++ it("returns to null when the last verb is removed, never to an empty set", () => {+ // An empty set would draw no arrows at all, which is not what clearing the+ // last chip asks for.+ expect(toggleVerb(new Set(["calls"]), "calls")).toBeNull();+ });++ it("does not mutate the set it was given", () => {+ const before = new Set(["calls"]);+ toggleVerb(before, "imports");+ expect([...before]).toEqual(["calls"]);+ });+});diff --git a/packages/ui/src/health/code-health-controls.tsx b/packages/ui/src/health/code-health-controls.tsxindex 297589f2b..f3bc2126c 100644--- a/packages/ui/src/health/code-health-controls.tsx+++ b/packages/ui/src/health/code-health-controls.tsx@@ -35,7 +35,7 @@ export function FilterSelect({);}-/** Toggleable filter chip (Hotspots / Untested / Failing). */+/** Toggleable filter chip (Hotspots / Untested / Failing, zoom-map verbs). */export function FilterChip({active,onClick,@@ -49,6 +49,7 @@ export function FilterChip({<buttontype="button"onClick={onClick}+ aria-pressed={active}className={cn("text-xs rounded-md px-2 py-1 border transition-colors",activediff --git a/packages/ui/src/zoom/ZoomCanvas.tsx b/packages/ui/src/zoom/ZoomCanvas.tsxindex c84789c7f..ac8d1b12e 100644--- a/packages/ui/src/zoom/ZoomCanvas.tsx+++ b/packages/ui/src/zoom/ZoomCanvas.tsx@@ -45,10 +45,10 @@ export interface ZoomCanvasProps {/** Show a small live frame-stat overlay (drawn/culled/fps). Dev aid. */showStats?: boolean;/**- * Draw only relations carrying this verb, or every relation when unset.- * See `DrawOptions.relationVerb` for why this is one verb and not a set.+ * Draw only relations whose verb is in this set, or every relation when+ * unset. See `DrawOptions.relationVerbs` for why this is a set.*/- relationVerb?: string | null;+ relationVerbs?: ReadonlySet<string> | null;/*** Relations incident to a node, for the hover card's one-line summary. The* host already indexes these for its detail panel, so it passes the lookup in@@ -89,7 +89,7 @@ export const ZoomCanvas = forwardRef<ZoomCanvasHandle, ZoomCanvasProps>(functiononFocusChange,initialFocusId,showStats,- relationVerb = null,+ relationVerbs = null,relationsByNode,},ref,@@ -164,8 +164,8 @@ export const ZoomCanvas = forwardRef<ZoomCanvasHandle, ZoomCanvasProps>(function}, [scene]);useEffect(() => {- rendererRef.current?.setRelationVerb(relationVerb);- }, [relationVerb]);+ rendererRef.current?.setRelationVerbs(relationVerbs);+ }, [relationVerbs]);// One-shot: jump to the URL-provided focus node once the canvas has done its// initial fit (it needs a real viewport size before a node rect can be framed).diff --git a/packages/ui/src/zoom/draw-tree.ts b/packages/ui/src/zoom/draw-tree.tsindex de5b7022a..ca50ff19f 100644--- a/packages/ui/src/zoom/draw-tree.ts+++ b/packages/ui/src/zoom/draw-tree.ts@@ -42,17 +42,18 @@ export interface DrawOptions {/** Shared ruled-paper card texture; null until the asset loads (or on SSR). */paper?: PaperTexture | null;/**- * Draw only relations carrying this verb (`ZoomRelation.label`), or every- * relation when null.+ * Draw only relations whose verb (`ZoomRelation.label`) is in this set, or+ * every relation when null. Null rather than "the set of all verbs" so the+ * unfiltered case costs no lookup and needs no knowledge of the vocabulary.*- * Deliberately one verb and not a set. Measured on a live index, 80.5% of- * relations are `imports` and 89% of boxes carry a single verb across all- * their relations, so a general multi-verb filter would be a no-op on nine- * boxes in ten. The one subset that earns a control is `co-changes` (5.3%):- * files that change together without importing each other, which no other- * view surfaces.+ * This was a single verb while the map was fed file-level edges only, where+ * the arrows carried three verbs, 80.5% of them `imports`, and 89% of boxes+ * had one verb across every relation — a multi-select would have been inert.+ * Projecting the call graph onto file pairs changed that: the vocabulary runs+ * to seven verbs on Ocelot, and the share of boxes carrying more than one+ * goes 48% -> 67% there and 8% -> 32% on jhipster-sample-app.*/- relationVerb?: string | null;+ relationVerbs?: ReadonlySet<string> | null;}/**@@ -214,7 +215,7 @@ export function drawScene(child,opts.lowDetail,focusId,- opts.relationVerb ?? null,+ opts.relationVerbs ?? null,);for (const kid of visible) drawNode(kid, child, depth + 1);@@ -243,7 +244,7 @@ function drawEdges(alpha: number,lowDetail: boolean,focusId: string | null,- relationVerb: string | null,+ relationVerbs: ReadonlySet<string> | null,): void {// Relations are revealed only for the box the user is pointing at / has// selected, so the canvas is not a thicket of arrows. No focus -> no edges.@@ -255,7 +256,7 @@ function drawEdges((r) =>r.source_id !== r.target_id &&(r.source_id === focusId || r.target_id === focusId) &&- (relationVerb === null || r.label === relationVerb) &&+ (relationVerbs === null || relationVerbs.has(r.label)) &&childRects.has(r.source_id) &&childRects.has(r.target_id),);diff --git a/packages/ui/src/zoom/index.ts b/packages/ui/src/zoom/index.tsindex 0a7b5b5f7..e52fd619e 100644--- a/packages/ui/src/zoom/index.ts+++ b/packages/ui/src/zoom/index.ts@@ -26,6 +26,7 @@ export {describeRelations,indexRelationsByNode,summarizeRelations,+ toggleVerb,} from "./relation-summary";export type { RelationSummary, VerbCount } from "./relation-summary";diff --git a/packages/ui/src/zoom/relation-summary.ts b/packages/ui/src/zoom/relation-summary.tsindex 3f4cdf866..3c477c441 100644--- a/packages/ui/src/zoom/relation-summary.ts+++ b/packages/ui/src/zoom/relation-summary.ts@@ -75,6 +75,25 @@ export function summarizeRelations(relations: readonly ZoomRelation[]): Relation};}+/**+ * Add or remove one verb from the drawn set, in the map key's chip row.+ *+ * Null means "every verb draws", and emptying the set returns to it rather than+ * to a canvas with no arrows: a filter whose natural resting state hides+ * everything trains people not to touch it. That makes null the only+ * representation of "unfiltered", so callers never have to treat a full set and+ * null as the same thing.+ */+export function toggleVerb(+ selected: ReadonlySet<string> | null,+ verb: string,+): ReadonlySet<string> | null {+ const next = new Set(selected ?? []);+ if (next.has(verb)) next.delete(verb);+ else next.add(verb);+ return next.size === 0 ? null : next;+}+/*** The summary as one readable line.*diff --git a/packages/ui/src/zoom/renderer.ts b/packages/ui/src/zoom/renderer.tsindex ed3c98073..f436f43fe 100644--- a/packages/ui/src/zoom/renderer.ts+++ b/packages/ui/src/zoom/renderer.ts@@ -21,6 +21,18 @@ import type { ZoomScene } from "./scene";import type { ZoomPalette } from "./theme";import type { ZoomNode } from "./types";+/**+ * Set equality, so a caller that rebuilds its verb set every render does not+ * force a repaint. The sets hold at most the label vocabulary (seven verbs), so+ * a pair of loops beats keeping a sorted key around.+ */+function sameVerbs(a: ReadonlySet<string> | null, b: ReadonlySet<string> | null): boolean {+ if (a === b) return true;+ if (a === null || b === null || a.size !== b.size) return false;+ for (const v of a) if (!b.has(v)) return false;+ return true;+}+export interface FrameStats {drawn: number;culled: number;@@ -75,7 +87,7 @@ export class ZoomRenderer {private selectedId: string | null = null;private hoveredId: string | null = null;- private relationVerb: string | null = null;+ private relationVerbs: ReadonlySet<string> | null = null;private lowDetailFrames = 0;private tween: Tween | null = null;private lastFocusId: string | null = null;@@ -129,10 +141,10 @@ export class ZoomRenderer {this.invalidate();}- /** Restrict drawn relations to one verb, or null for all of them. */- setRelationVerb(verb: string | null): void {- if (verb === this.relationVerb) return;- this.relationVerb = verb;+ /** Restrict drawn relations to these verbs, or null for all of them. */+ setRelationVerbs(verbs: ReadonlySet<string> | null): void {+ if (sameVerbs(verbs, this.relationVerbs)) return;+ this.relationVerbs = verbs;this.invalidate();}@@ -260,7 +272,7 @@ export class ZoomRenderer {hoveredId: this.hoveredId,lowDetail,paper: this.paper,- relationVerb: this.relationVerb,+ relationVerbs: this.relationVerbs,});if (this.onStats) {this.onStats({diff --git a/packages/web/src/app/repos/[id]/knowledge-graph/page.tsx b/packages/web/src/app/repos/[id]/knowledge-graph/page.tsxindex 6af6e23e1..fa01bfa05 100644--- a/packages/web/src/app/repos/[id]/knowledge-graph/page.tsx+++ b/packages/web/src/app/repos/[id]/knowledge-graph/page.tsx@@ -29,7 +29,7 @@ import { parseAsString, useQueryState } from "nuqs";import { ScanSearch } from "lucide-react";import { PageShell } from "@repowise-dev/ui/shared/page-shell";import { ZoomCanvas } from "@repowise-dev/ui/zoom";-import { CO_CHANGES, indexRelationsByNode } from "@repowise-dev/ui/zoom";+import { indexRelationsByNode, summarizeRelations } from "@repowise-dev/ui/zoom";import type { ZoomCanvasHandle, ZoomNode, ZoomRelation } from "@repowise-dev/ui/zoom";import { useZoomMap } from "@/lib/hooks/use-graph";import { ZoomBreadcrumb } from "@/components/zoom/zoom-breadcrumb";@@ -55,7 +55,7 @@ export default function KnowledgeGraphPage({ params }: { params: Promise<{ id: s);const [chain, setChain] = useState<ZoomNode[]>([]);const [selected, setSelected] = useState<ZoomNode | null>(null);- const [relationVerb, setRelationVerb] = useState<string | null>(null);+ const [relationVerbs, setRelationVerbs] = useState<ReadonlySet<string> | null>(null);// Snapshot the initial URL focus once so later URL writes don't re-trigger a jump.const initialFocus = useRef(focusParam ?? undefined).current;@@ -82,8 +82,10 @@ export default function KnowledgeGraphPage({ params }: { params: Promise<{ id: s() => (zoomMap ? indexRelationsByNode(zoomMap) : NO_RELATIONS),[zoomMap],);- const coChangeCount = useMemo(- () => (zoomMap?.relations ?? []).filter((r) => r.label === CO_CHANGES).length,+ // The verb vocabulary of *this* map, so the filter offers what is actually+ // drawable rather than the seven labels the backend can emit.+ const verbs = useMemo(+ () => summarizeRelations(zoomMap?.relations ?? EMPTY_RELATIONS).verbs,[zoomMap],);const showStats = process.env.NODE_ENV === "development";@@ -143,7 +145,7 @@ export default function KnowledgeGraphPage({ params }: { params: Promise<{ id: sonSelect={setSelected}onFocusChange={onFocusChange}showStats={showStats}- relationVerb={relationVerb}+ relationVerbs={relationVerbs}relationsByNode={relationsByNode}/><ZoomHint />@@ -154,7 +156,7 @@ export default function KnowledgeGraphPage({ params }: { params: Promise<{ id: snode={selected}repoId={repoId}relations={relationsByNode.get(selected.id) ?? EMPTY_RELATIONS}- relationVerb={relationVerb}+ relationVerbs={relationVerbs}onClose={() => setSelected(null)}onZoom={(id) => flyTo(id)}/>@@ -163,9 +165,9 @@ export default function KnowledgeGraphPage({ params }: { params: Promise<{ id: s</div><ZoomMapKey- verb={relationVerb}- onVerbChange={setRelationVerb}- coChangeCount={coChangeCount}+ verbs={verbs}+ selected={relationVerbs}+ onSelectedChange={setRelationVerbs}/></>)}diff --git a/packages/web/src/components/zoom/zoom-detail-panel.tsx b/packages/web/src/components/zoom/zoom-detail-panel.tsxindex e6ce2d513..67dfacb5f 100644--- a/packages/web/src/components/zoom/zoom-detail-panel.tsx+++ b/packages/web/src/components/zoom/zoom-detail-panel.tsx@@ -39,7 +39,7 @@ interface ZoomDetailPanelProps {/** Relations incident to this node, in either direction. */relations: ZoomRelation[];/** The verb the map is currently filtered to, or null for all of them. */- relationVerb: string | null;+ relationVerbs: ReadonlySet<string> | null;onClose: () => void;onZoom: (id: string) => void;}@@ -94,7 +94,7 @@ export function ZoomDetailPanel({node,repoId,relations,- relationVerb,+ relationVerbs,onClose,onZoom,}: ZoomDetailPanelProps) {@@ -112,7 +112,7 @@ export function ZoomDetailPanel({// "the 10 strongest" while two arrows are on screen.const summary = summarizeRelations(relations);const drawn = summarizeRelations(- relationVerb === null ? relations : relations.filter((r) => r.label === relationVerb),+ relationVerbs === null ? relations : relations.filter((r) => relationVerbs.has(r.label)),);const cap = describeCap(drawn);diff --git a/packages/web/src/components/zoom/zoom-map-key.tsx b/packages/web/src/components/zoom/zoom-map-key.tsxindex 31a2e516d..784fbea26 100644--- a/packages/web/src/components/zoom/zoom-map-key.tsx+++ b/packages/web/src/components/zoom/zoom-map-key.tsx@@ -1,7 +1,7 @@"use client";/**- * The row that says what the map's marks mean, plus the one control over them.+ * The row that says what the map's marks mean, plus the controls over them.** Chrome goes *around* a canvas, never on it, so this is a hairline row under* the map rather than another floating panel. It carries the two things a card@@ -10,47 +10,54 @@* the two dots shared a palette, so working out one taught you the wrong thing* about the other.*- * Why one toggle and not a verb filter. Measured on a live index, the arrows- * carry three verbs, not the seven the label vocabulary allows: `imports`- * 80.5%, `uses` 14.3%, `co-changes` 5.3%. `calls`, `inherits from`,- * `implements` and `references` cannot occur at all, because the zoom map is- * fed file-level edges and those four are symbol-level. On top of that, 89% of- * boxes carry a single verb across every one of their relations, so a general- * filter would do nothing on nine boxes in ten and its main visible effect- * would be arrows vanishing.+ * Why a verb filter now, when a single co-changes toggle was right before. The+ * toggle was sized against a map fed file-level edges only: the arrows carried+ * three verbs, 80.5% of them `imports`, four of the label vocabulary's seven+ * "could not occur at all" because they are symbol-level, and 89% of boxes had+ * one verb across every relation. A general filter would have done nothing on+ * nine boxes in ten.*- * Co-changes is the exception worth a control: files that change together- * without importing each other, which is coupling no other view on the site- * surfaces, and which is invisible here by default because it is drowned by- * the imports it shares a canvas with.+ * Projecting the symbol graph onto file pairs removed that argument rather than+ * weakening it. The four missing verbs now occur: Ocelot draws all seven, and+ * the share of boxes carrying more than one verb goes 48% -> 67% there and+ * 8% -> 32% on jhipster-sample-app. "Show me what calls what, not what imports+ * what" is a question the map can now answer, so the control earns its place.+ *+ * No verbs selected means every verb draws, rather than an empty canvas. A+ * filter whose natural resting state hides everything trains people not to+ * touch it.*/-import { CO_CHANGES } from "@repowise-dev/ui/zoom";+import { FilterChip } from "@repowise-dev/ui/health";+import { type VerbCount, toggleVerb } from "@repowise-dev/ui/zoom";import { HEALTH_BAND_LABEL } from "@repowise-dev/types/health";interface ZoomMapKeyProps {- /** Null = every relation draws; CO_CHANGES = only co-change relations. */- verb: string | null;- onVerbChange: (verb: string | null) => void;- /** Co-change relations in the whole map, so the toggle can carry its figure. */- coChangeCount: number;+ /** Every verb present in the loaded map, descending by count. */+ verbs: VerbCount[];+ /** Null = every relation draws; otherwise only these verbs do. */+ selected: ReadonlySet<string> | null;+ onSelectedChange: (verbs: ReadonlySet<string> | null) => void;}function Dot({ className }: { className: string }) {return <span aria-hidden className={`inline-block h-2 w-2 shrink-0 rounded-full ${className}`} />;}-export function ZoomMapKey({ verb, onVerbChange, coChangeCount }: ZoomMapKeyProps) {- const only = verb === CO_CHANGES;+export function ZoomMapKey({ verbs, selected, onSelectedChange }: ZoomMapKeyProps) {+ const filtered = selected !== null;return (<div className="mt-3 border-t border-[var(--color-border-default)] pt-3">- <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">+ <div className="flex flex-col gap-2 sm:flex-row sm:items-baseline sm:justify-between"><p className="min-w-0 text-[13px] leading-relaxed text-[var(--color-text-secondary)]">- {only ? (+ {filtered ? (<>- Showing <span className="text-[var(--color-text-primary)]">co-changes only</span>:- files that change in the same commits without importing each other.+ Showing{" "}+ <span className="text-[var(--color-text-primary)]">+ {[...selected].join(", ")}+ </span>{" "}+ only. Arrow weight is how many file pairs the relation covers.</>) : (<>@@ -59,24 +66,33 @@ export function ZoomMapKey({ verb, onVerbChange, coChangeCount }: ZoomMapKeyProp</>)}</p>- {/* A count on the control tells you whether it is worth a click before- you spend one. Only shown because it is already in the loaded map. */}- <button- type="button"- onClick={() => onVerbChange(only ? null : CO_CHANGES)}- aria-pressed={only}- disabled={coChangeCount === 0}- className={`shrink-0 self-start rounded-md border px-2.5 py-1 text-[12px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 sm:self-auto ${- only- ? "border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"- : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-wash-hover)] hover:text-[var(--color-text-primary)]"- }`}- >- Co-changes only{" "}- <span className="font-mono tabular-nums text-[var(--color-text-tertiary)]">- {coChangeCount.toLocaleString()}- </span>- </button>+ {verbs.length > 1 && (+ /* Counts sit on the chips so you can tell whether one is worth a+ click before you spend one. Already in the loaded map. */+ <div className="flex flex-wrap items-center gap-1.5">+ {verbs.map(({ verb, count }) => (+ <FilterChip+ key={verb}+ active={selected?.has(verb) ?? false}+ onClick={() => onSelectedChange(toggleVerb(selected, verb))}+ >+ {verb}{" "}+ <span className="font-mono tabular-nums text-[var(--color-text-tertiary)]">+ {count.toLocaleString()}+ </span>+ </FilterChip>+ ))}+ {filtered && (+ <button+ type="button"+ onClick={() => onSelectedChange(null)}+ className="rounded-md px-2 py-1 text-xs text-[var(--color-text-secondary)] underline-offset-2 transition-colors hover:text-[var(--color-text-primary)] hover:underline"+ >+ Clear+ </button>+ )}+ </div>+ )}</div>{/* The dots. Health keeps the traffic light because the colours carry adiff --git a/tests/unit/server/services/test_zoom_builder.py b/tests/unit/server/services/test_zoom_builder.pyindex 83d54ef34..52e02de0e 100644--- a/tests/unit/server/services/test_zoom_builder.py+++ b/tests/unit/server/services/test_zoom_builder.py@@ -11,6 +11,7 @@ from repowise.server.services.c4_builder.models import (ArchTourStep,)from repowise.server.services.zoom_builder import assemble_zoom_map+from repowise.server.services.zoom_builder.calls import keep_projected_edgefrom repowise.server.services.zoom_builder.metrics import rollup_health, rollup_metricsfrom repowise.server.services.zoom_builder.models import ZoomNodefrom repowise.server.services.zoom_builder.relations import aggregate_relations@@ -600,3 +601,93 @@ def _has_ancestor(nodes: dict[str, ZoomNode], node_id: str, ancestor_id: str) ->return Truecur = nodes[cur].parent_idreturn False+++# --- the projected call graph ----------------------------------------------+++def test_keep_projected_edge_guards():+ # A genuine cross-file pair in one language survives.+ assert keep_projected_edge("a/x.py", "a/y.py")+ # Every intra-file call projects onto a self-loop, which has no sibling to+ # point at, and those outnumber the real ones.+ assert not keep_projected_edge("a/x.py", "a/x.py")+ # Across a language boundary the pair is more often a same-name coincidence+ # than a call.+ assert not keep_projected_edge("a/x.py", "a/x.ts")+ assert not keep_projected_edge("", "a/y.py")+++def test_assemble_zoom_map_projected_calls_relabel_an_existing_pair():+ # main.py -> engine.py is already drawn as "imports". A projected call over+ # the same pair must not add a second arrow; it must upgrade the verb, since+ # "calls" outranks "imports" and is the more precise claim about the pair.+ view = _view()+ before = {(r.source_id, r.target_id): r for r in assemble_zoom_map(view).relations}+ after = {+ (r.source_id, r.target_id): r+ for r in assemble_zoom_map(+ view, call_edges=[("pkg/main.py", "pkg/core/engine.py", "calls")]+ ).relations+ }++ assert set(before) == set(after), "a relabelled pair must not become a new arrow"+ # Under the layer, main.py's folder points at the group holding engine.py.+ key = ("zm:D:zm:L:layer:service:pkg", "zm:G:layer:service:core")+ assert before[key].label == "imports"+ assert after[key].label == "calls"+ assert after[key].edge_count == before[key].edge_count + 1+++def test_assemble_zoom_map_projected_calls_add_a_pair_no_import_covers():+ # util.py never imports main.py, so a call between them is an arrow the map+ # could not draw before — this is the part of the projection that is new+ # information rather than a better word for old information.+ view = _view()+ before = {(r.source_id, r.target_id) for r in assemble_zoom_map(view).relations}+ zoom = assemble_zoom_map(+ view, call_edges=[("pkg/core/util.py", "pkg/main.py", "dispatches_to")]+ )+ added = {(r.source_id, r.target_id) for r in zoom.relations} - before++ # The only edge under the layer ran folder -> group; this is the reverse+ # direction, which nothing imported into existence.+ pair = ("zm:G:layer:service:core", "zm:D:zm:L:layer:service:pkg")+ assert added == {pair}+ new = next(r for r in zoom.relations if (r.source_id, r.target_id) == pair)+ assert new.label == "dispatches to"+++def test_assemble_zoom_map_call_edges_default_to_none():+ # The pure assembly still runs without them: the hosted builder calls it+ # directly and has no symbol graph in its artifacts.+ assert assemble_zoom_map(_view()).relations == assemble_zoom_map(+ _view(), call_edges=None+ ).relations+++def test_compute_file_signals_reaches_over_calls_as_well_as_imports():+ # b.py is imported by nobody, so the dependency graph alone cannot reach it;+ # a call from the entry point does. The union is what makes "on flow" mean+ # execution rather than "appears in an import header somewhere".+ stats = [FileStat(path=p) for p in ("a.py", "b.py")]+ imports_only = compute_file_signals(+ stats, [], entry_points=["a.py"], tour_paths=set()+ )+ assert imports_only["b.py"].on_flow is False++ with_calls = compute_file_signals(+ stats, [("a.py", "b.py", "calls")], entry_points=["a.py"], tour_paths=set()+ )+ assert with_calls["b.py"].on_flow is True+ assert with_calls["b.py"].entry_dist == 1+++def test_compute_file_signals_keeps_import_reachability_when_calls_are_absent():+ # The union must not cost anything where there is no call graph: a hosted+ # build with no projected edges has to reach exactly what it reached before.+ stats = [FileStat(path=p) for p in ("a.py", "b.py")]+ signals = compute_file_signals(+ stats, [("a.py", "b.py", "imports")], entry_points=["a.py"], tour_paths=set()+ )+ assert signals["b.py"].on_flow is True