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(c4): readable C4 model with derived actors, real coupling, and accurate containers (#576)
Raghav Chamadiyade0eef259f15
diff --git a/packages/server/src/repowise/server/routers/c4.py b/packages/server/src/repowise/server/routers/c4.pyindex 7135af5e2..4ad5962b4 100644--- a/packages/server/src/repowise/server/routers/c4.py+++ b/packages/server/src/repowise/server/routers/c4.py@@ -12,10 +12,10 @@ work happens here, so this works on hosted backends without a checkout.from __future__ import annotations+from fastapi import APIRouter, Depends, HTTPException, Queryfrom fastapi.responses import PlainTextResponsefrom sqlalchemy.ext.asyncio import AsyncSession-from fastapi import APIRouter, Depends, HTTPException, Queryfrom repowise.server.deps import get_db_session, verify_api_keyfrom repowise.server.schemas import (ArchitectureViewResponse,@@ -142,7 +142,7 @@ def _system(s: System) -> C4SystemResponse:def _person(p: Person) -> C4PersonResponse:- return C4PersonResponse(id=p.id, name=p.name, description=p.description)+ return C4PersonResponse(id=p.id, name=p.name, description=p.description, kind=p.kind)def _container(c: Container) -> C4ContainerResponse:@@ -176,6 +176,7 @@ def _relation(r: Relation) -> C4RelationResponse:label=r.label,edge_count=r.edge_count,edge_types=list(r.edge_types),+ coupling=r.coupling,)diff --git a/packages/server/src/repowise/server/schemas/c4.py b/packages/server/src/repowise/server/schemas/c4.pyindex 64ac5a7f6..6bdc54217 100644--- a/packages/server/src/repowise/server/schemas/c4.py+++ b/packages/server/src/repowise/server/schemas/c4.py@@ -9,6 +9,7 @@ class C4PersonResponse(BaseModel):id: strname: strdescription: str = ""+ kind: str = "user" # cli | api | scheduler | developer | userclass C4SystemResponse(BaseModel):@@ -53,6 +54,7 @@ class C4RelationResponse(BaseModel):label: str = ""edge_count: int = 1edge_types: list[str] = Field(default_factory=list)+ coupling: str = "" # loose | moderate | tight (empty on synthetic edges)class C4L1Response(BaseModel):diff --git a/packages/server/src/repowise/server/services/c4_builder/__init__.py b/packages/server/src/repowise/server/services/c4_builder/__init__.pyindex d1b31d748..388601490 100644--- a/packages/server/src/repowise/server/services/c4_builder/__init__.py+++ b/packages/server/src/repowise/server/services/c4_builder/__init__.py@@ -15,12 +15,18 @@ re-scan is performed at request time.from __future__ import annotations+import jsonfrom collections import defaultdict+from dataclasses import replace-from repowise.core.persistence import ExternalSystem, Repositoryfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.persistence import ExternalSystem, Repository+from repowise.core.persistence.crud import get_kg_project_meta+from repowise.core.persistence.models import DeadCodeFinding, GitMetadata++from .actors import derive_actorsfrom .components import detect_componentsfrom .containers import container_id, detect_containersfrom .models import (@@ -35,6 +41,7 @@ from .models import (System,)from .relations import aggregate_relations, external_node_to_system_id+from .signals import count_box_signals__all__ = ["C4L1",@@ -117,11 +124,17 @@ async def build_l1(session: AsyncSession, repo_id: str) -> C4L1:system = _system_for(repo, repo_id)externals, _ = await _external_views(session, repo_id)- # Default actor — Phase 1 of issue #203 keeps a single generic User.- person = Person(id="person:user", name="User", description="Uses the system")+ # Derive the actor set from how the system is actually entered (CLI user,+ # API client, scheduled job …) rather than a lone hardcoded "User".+ entry_points = await _curated_entry_points(session, repo_id)+ actors = derive_actors(entry_points)+ people = [+ Person(id=a.id, name=a.name, description=a.description, kind=a.kind)+ for a in actors+ ]relations: list[Relation] = [- Relation(source_id=person.id, target_id=system.id, label="uses")+ Relation(source_id=a.id, target_id=system.id, label=a.verb) for a in actors]for ext in externals:relations.append(@@ -129,19 +142,26 @@ async def build_l1(session: AsyncSession, repo_id: str) -> C4L1:)return C4L1(system=system,- people=[person],+ people=people,external_systems=externals,relations=relations,)async def build_l2(session: AsyncSession, repo_id: str) -> C4L2:- containers = await detect_containers(session, repo_id)+ repo = await load_repo(session, repo_id)+ containers = await detect_containers(+ session, repo_id, root_name=repo.name if repo else None+ )externals, _ = await _external_views(session, repo_id)file_to_container = await _file_to_container_map(session, repo_id, containers)file_to_external = await external_node_to_system_id(session, repo_id)+ containers = await _annotate_container_signals(+ session, repo_id, containers, file_to_container+ )+relations = await aggregate_relations(session,repo_id,@@ -157,15 +177,33 @@ async def build_l2(session: AsyncSession, repo_id: str) -> C4L2:async def build_l3(session: AsyncSession, repo_id: str, container_id_value: str) -> C4L3 | None:"""Return L3 view for one container, or ``None`` if it doesn't exist."""- containers = await detect_containers(session, repo_id)+ repo = await load_repo(session, repo_id)+ containers = await detect_containers(+ session, repo_id, root_name=repo.name if repo else None+ )container = next((c for c in containers if c.id == container_id_value), None)if container is None:return None+ # Files owned by sibling containers must not be re-bucketed as this+ # container's components (matters for a root/catch-all container).+ sibling_roots = [c.path for c in containers if c.id != container.id and c.path]components, in_container_index = await detect_components(- session, repo_id, container.path+ session,+ repo_id,+ container.path,+ sibling_roots=sibling_roots,)+ # Annotate the focused container with its hotspot / dead-code counts so the+ # header card matches what L2 shows.+ full_file_to_container = await _file_to_container_map(session, repo_id, containers)+ container = (+ await _annotate_container_signals(+ session, repo_id, [container], full_file_to_container+ )+ )[0]+# Files outside this container map to their owning container so cross-# container edges show as component → other-container.file_to_box: dict[str, str] = dict(in_container_index)@@ -208,6 +246,60 @@ async def build_l3(session: AsyncSession, repo_id: str, container_id_value: str)# ---------------------------------------------------------------------------+async def _curated_entry_points(session: AsyncSession, repo_id: str) -> list[str]:+ """Return the curated entry-point paths persisted at index time.++ These are the ranked, cleaned execution starts (Phase 1) — not the raw+ ingestion ``is_entry_point`` flags, which still include barrels/configs.+ """+ project_meta = await get_kg_project_meta(session, repo_id)+ if not project_meta:+ return []+ try:+ return list(json.loads(project_meta.entry_points_json or "[]"))+ except (ValueError, TypeError):+ return []+++async def _annotate_container_signals(+ session: AsyncSession,+ repo_id: str,+ containers: list[Container],+ file_to_container: dict[str, str],+) -> list[Container]:+ """Populate each container's ``hotspot_count`` / ``dead_count`` from the+ persisted git-metadata hotspots and open unreachable-file findings."""+ hotspot_paths = {+ row[0]+ for row in (+ await session.execute(+ select(GitMetadata.file_path).where(+ GitMetadata.repository_id == repo_id,+ GitMetadata.is_hotspot.is_(True),+ )+ )+ ).all()+ }+ dead_paths = {+ row[0]+ for row in (+ await session.execute(+ select(DeadCodeFinding.file_path).where(+ DeadCodeFinding.repository_id == repo_id,+ DeadCodeFinding.status == "open",+ DeadCodeFinding.kind == "unreachable_file",+ )+ )+ ).all()+ }+ counts = count_box_signals(file_to_container, hotspot_paths, dead_paths)+ annotated: list[Container] = []+ for c in containers:+ hot, dead = counts.get(c.id, (0, 0))+ annotated.append(replace(c, hotspot_count=hot, dead_count=dead))+ return annotated++async def _file_to_container_map(session: AsyncSession,repo_id: str,@@ -220,6 +312,8 @@ async def _file_to_container_map(select(GraphNode.node_id).where(GraphNode.repository_id == repo_id,GraphNode.node_type == "file",+ # External / unresolved-import targets are not source files.+ ~GraphNode.node_id.like("external:%"),))paths = [row[0] for row in result.all()]diff --git a/packages/server/src/repowise/server/services/c4_builder/actors.py b/packages/server/src/repowise/server/services/c4_builder/actors.pynew file mode 100644index 000000000..278ac167c--- /dev/null+++ b/packages/server/src/repowise/server/services/c4_builder/actors.py@@ -0,0 +1,116 @@+"""Derive C4 L1 actors from a repository's curated entry points.++The L1 System Context answers "who or what drives this system?" A lone+hardcoded "User" is no information. The curated entry-point paths already+encode how the system is entered: a ``cli/main.py`` is run by a person at a+terminal, a ``server/app.py`` is called by an API client, a ``worker``/``cron``+module is woken by a scheduler. This module maps those path conventions to a+small, deduplicated set of actors so the diagram reflects reality, while+falling back to a generic user when nothing is determinable.++Pure functions — operate on the path strings, no DB — so they unit-test in+isolation.+"""++from __future__ import annotations++from dataclasses import dataclass++# Actor kind -> (display name, what it does to the system). Order here is the+# stable render order when several kinds are present.+_ACTOR_META: dict[str, tuple[str, str]] = {+ "cli": ("CLI user", "Runs commands from a terminal"),+ "api": ("API client", "Calls the HTTP API"),+ "scheduler": ("Scheduled job", "Triggers background runs on a schedule"),+ "developer": ("Developer / CI", "Runs scripts and tooling"),+ "user": ("User", "Uses the system"),+}+_KIND_ORDER: tuple[str, ...] = ("cli", "api", "scheduler", "developer", "user")++# How each actor kind relates to the system on the L1 arrow.+_ACTOR_VERB: dict[str, str] = {+ "cli": "runs",+ "api": "calls",+ "scheduler": "triggers",+ "developer": "runs",+ "user": "uses",+}+++@dataclass(frozen=True)+class Actor:+ """A derived L1 actor: a stable id, a display name, the system-edge verb."""++ id: str+ kind: str+ name: str+ description: str+ verb: str+++def _segments(path: str) -> tuple[list[str], str]:+ """Return (lowercased path segments, lowercased basename)."""+ parts = path.replace("\\", "/").lower().split("/")+ return parts, parts[-1] if parts else ""+++def classify_entry_point(path: str) -> str | None:+ """Classify one entry-point path into an actor kind, or ``None``.++ Convention-based and framework-agnostic: matches on conventional directory+ and file names rather than any specific tool. Checked most-specific first.+ """+ segs, base = _segments(path)+ segset = set(segs)++ # Scheduled/background entry: a worker or cron-style module.+ if segset & {"worker", "workers", "cron", "scheduler", "beat", "tasks", "celery"}:+ return "scheduler"++ # CLI entry: a cli package or a conventional command launcher.+ if "cli" in segset or base in {"__main__.py", "manage.py"}:+ return "cli"++ # HTTP/API entry: a server app or web framework launcher.+ if segset & {"server", "api", "routers", "asgi", "wsgi"}:+ return "api"+ if base in {"app.py", "asgi.py", "wsgi.py", "server.py"}:+ return "api"++ # Developer / CI tooling: scripts and standalone runners.+ if segset & {"scripts", "tools", "tooling"} or base == "run.py":+ return "developer"++ return None+++def derive_actors(entry_points: list[str]) -> list[Actor]:+ """Derive the deduplicated, ordered actor set for the L1 view.++ Each distinct actor kind appears once. When no entry point is classifiable+ (or the list is empty) a single generic ``user`` actor is returned so L1 is+ never empty.+ """+ kinds: list[str] = []+ for path in entry_points:+ kind = classify_entry_point(path)+ if kind is not None and kind not in kinds:+ kinds.append(kind)++ if not kinds:+ kinds = ["user"]++ ordered = [k for k in _KIND_ORDER if k in kinds]+ actors: list[Actor] = []+ for kind in ordered:+ name, description = _ACTOR_META[kind]+ actors.append(+ Actor(+ id=f"person:{kind}",+ kind=kind,+ name=name,+ description=description,+ verb=_ACTOR_VERB[kind],+ )+ )+ return actorsdiff --git a/packages/server/src/repowise/server/services/c4_builder/components.py b/packages/server/src/repowise/server/services/c4_builder/components.pyindex dbfc8b419..43c3270cd 100644--- a/packages/server/src/repowise/server/services/c4_builder/components.py+++ b/packages/server/src/repowise/server/services/c4_builder/components.py@@ -1,117 +1,169 @@"""Detect C4 L3 components inside a single container.-A component is a top-level subdirectory of the container. Files that sit-directly at the container root (no subdirectory) are bucketed into a-synthetic ``_root`` component so the UI can render them without a-"missing parent" gap.--Returns the components plus a ``file_index`` mapping each file path inside-the container to its owning component id — relations.py reuses this index-to roll file→file edges up to component→component edges.+A component is a meaningful child directory of the container. Two refinements+keep the view legible:++* **Pass-through roots are skipped.** A leading build-convention directory+ (``src``/``lib``/``app``/…) carries no architectural meaning, so a file at+ ``packages/ui/src/health/x.tsx`` is grouped under ``health`` rather than a+ single giant ``src``. This is the "one more level where it adds clarity"+ rule — the displayed level tracks the real feature directory.+* **Files at the container root** (or only inside pass-through dirs) collapse+ into one synthetic bucket labeled ``(root)`` — never the leaky ``_root``+ token, which used to reach the API verbatim.++External (``external:*``) nodes and files owned by sibling containers are+excluded so a root/catch-all container does not absorb another container's+tree.++Returns the components plus a ``file_index`` mapping each owned file path to+its component id — relations.py reuses this index to roll file->file edges up+to component->component edges."""from __future__ import annotations-from collections import Counter, defaultdict+from collections import defaultdict+from collections.abc import Iterable-from repowise.core.persistence import GraphNodefrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.persistence import GraphNode+from .containers import container_idfrom .models import Component-ROOT_COMPONENT_NAME = "_root"+# Source-root directories that carry no architectural meaning — skipped so a+# component reflects the real feature directory beneath them. Deliberately only+# genuine source roots (not build-output dirs like ``dist``, which we do want+# to surface as their own component if indexed).+_PASS_THROUGH_DIRS = frozenset({"src", "lib", "app", "source"})++# Display label + id sentinel for the bucket of files that sit at the container+# root. Chosen so neither ever serializes the old "_root" token.+ROOT_BUCKET_LABEL = "(root)"+_ROOT_BUCKET_SUFFIX = "::root"+++def component_id(component_path: str) -> str:+ """Stable id for a component, keyed on its repo-relative directory."""+ return f"cmp:{component_path or '.'}"+++def _relative(file_path: str, container_path: str) -> str:+ if container_path and file_path.startswith(container_path + "/"):+ return file_path[len(container_path) + 1 :]+ return file_path+++def _component_for(+ file_path: str, container_path: str, root_label: str+) -> tuple[str, str, str]:+ """Return ``(component_id, name, path)`` for a file's owning component.++ Skips leading pass-through directories; files with no meaningful directory+ fall into the ``(root)`` bucket.+ """+ rel = _relative(file_path, container_path)+ dirs = rel.split("/")[:-1] # directory segments only (drop the filename)++ i = 0+ while i < len(dirs) and dirs[i] in _PASS_THROUGH_DIRS:+ i += 1+ if i >= len(dirs):+ base = container_path or "."+ return f"cmp:{base}{_ROOT_BUCKET_SUFFIX}", root_label, container_path or "."-def component_id(container_path: str, component_name: str) -> str:- base = container_path or "."- return f"cmp:{base}/{component_name}"+ name = dirs[i]+ rel_dir = "/".join(dirs[: i + 1])+ path = f"{container_path}/{rel_dir}" if container_path else rel_dir+ return component_id(path), name, pathasync def detect_components(session: AsyncSession,repository_id: str,container_path: str,+ *,+ sibling_roots: Iterable[str] = (),+ root_label: str = ROOT_BUCKET_LABEL,) -> tuple[list[Component], dict[str, str]]:"""Return (components, file_index) for ``container_path``.- ``file_index`` maps every file path inside the container to the id of- the component that owns it.+ ``sibling_roots`` are the paths of other containers; files under them are+ excluded so a catch-all/root container does not claim another container's+ files. ``root_label`` names the container-root bucket.++ ``file_index`` maps every owned file path to the id of its component."""- file_nodes = await _files_in(session, repository_id, container_path)+ file_nodes = await _files_in(+ session, repository_id, container_path, sibling_roots=sibling_roots+ )bucket: dict[str, list[GraphNode]] = defaultdict(list)+ meta: dict[str, tuple[str, str]] = {} # comp_id -> (name, path)+ file_owner: dict[str, str] = {}+ cid = container_id(container_path)for node in file_nodes:- comp = _component_name(node.node_id, container_path)- bucket[comp].append(node)+ comp_id, name, path = _component_for(node.node_id, container_path, root_label)+ bucket[comp_id].append(node)+ meta[comp_id] = (name, path)+ file_owner[node.node_id] = comp_idcomponents: list[Component] = []- file_index: dict[str, str] = {}- cid = container_id(container_path)- for comp_name in sorted(bucket):- nodes = bucket[comp_name]- comp_path = f"{container_path}/{comp_name}" if container_path else comp_name- comp_id = component_id(container_path, comp_name)+ for comp_id in sorted(bucket, key=lambda c: meta[c][1]):+ nodes = bucket[comp_id]+ name, path = meta[comp_id]components.append(Component(id=comp_id,- name=comp_name,- path=comp_path,+ name=name,+ path=path,container_id=cid,file_count=len(nodes),symbol_count=sum(n.symbol_count or 0 for n in nodes),))- for n in nodes:- file_index[n.node_id] = comp_id- return components, file_index---def _component_name(file_path: str, container_path: str) -> str:- """Compute the top-level subdirectory of ``file_path`` relative to the- container root."""- if container_path:- rel = file_path[len(container_path) + 1 :] if file_path.startswith(container_path + "/") else file_path- else:- rel = file_path- if "/" in rel:- return rel.split("/", 1)[0]- return ROOT_COMPONENT_NAME+ return components, file_ownerasync def _files_in(- session: AsyncSession, repository_id: str, container_path: str+ session: AsyncSession,+ repository_id: str,+ container_path: str,+ *,+ sibling_roots: Iterable[str] = (),) -> list[GraphNode]:stmt = select(GraphNode).where(GraphNode.repository_id == repository_id,GraphNode.node_type == "file",+ # Unresolved-import / dependency targets are not source files.+ ~GraphNode.node_id.like("external:%"),)if container_path:prefix = container_path + "/"- # SQLite's LIKE is case-sensitive when the LHS is binary; for path- # matching that's the behaviour we want.stmt = stmt.where((GraphNode.node_id == container_path) | GraphNode.node_id.like(prefix + "%"))result = await session.execute(stmt)nodes = list(result.scalars())- if not container_path:- return nodes- # We may have over-selected files whose path simply starts with the- # container name as a prefix substring (e.g., "packages/core" should not- # capture "packages/core-extras/foo.py"). Final filter:- prefix = container_path + "/"- return [n for n in nodes if n.node_id == container_path or n.node_id.startswith(prefix)]+ # The LIKE prefix can over-select on a shared substring (e.g. "packages/core"+ # must not capture "packages/core-extras/foo.py"). Final exact filter.+ if container_path:+ prefix = container_path + "/"+ nodes = [+ n for n in nodes if n.node_id == container_path or n.node_id.startswith(prefix)+ ]-# Re-export so callers can introspect / display the synthetic bucket name-__all__ = ["ROOT_COMPONENT_NAME", "component_id", "detect_components"]+ # Drop files owned by a sibling container so a root/catch-all container does+ # not absorb another container's tree.+ sibling_prefixes = tuple(r + "/" for r in sibling_roots if r)+ if sibling_prefixes:+ nodes = [n for n in nodes if not n.node_id.startswith(sibling_prefixes)]+ return nodes-# Convenience used by L2 relations: dominant language across the bucket.-def dominant_language(nodes: list[GraphNode]) -> str:- counter: Counter[str] = Counter(- n.language for n in nodes if n.language and n.language != "unknown"- )- return counter.most_common(1)[0][0] if counter else "unknown"+__all__ = ["ROOT_BUCKET_LABEL", "component_id", "detect_components"]diff --git a/packages/server/src/repowise/server/services/c4_builder/containers.py b/packages/server/src/repowise/server/services/c4_builder/containers.pyindex b21ee3072..021f88cea 100644--- a/packages/server/src/repowise/server/services/c4_builder/containers.py+++ b/packages/server/src/repowise/server/services/c4_builder/containers.py@@ -20,24 +20,62 @@ from __future__ import annotationsfrom collections import Counter, defaultdictfrom collections.abc import Iterable-from repowise.core.persistence import ExternalSystem, GraphNodefrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.persistence import ExternalSystem, GraphNode+from .models import Container+# Package-manifest basenames. A directory holding one of these is a container+# root even when the manifest declares no external dependencies (so a package+# like ``packages/core`` is its own container rather than dissolving into the+# repo-root catch-all).+_MANIFEST_BASENAMES = frozenset(+ {+ "pyproject.toml",+ "setup.py",+ "setup.cfg",+ "package.json",+ "cargo.toml",+ "go.mod",+ "pom.xml",+ "build.gradle",+ "composer.json",+ "gemfile",+ }+)+_MANIFEST_SUFFIXES = (".csproj",)+++def _is_manifest(node_id: str) -> bool:+ base = node_id.rsplit("/", 1)[-1].lower()+ return base in _MANIFEST_BASENAMES or base.endswith(_MANIFEST_SUFFIXES)+async def detect_containers(- session: AsyncSession, repository_id: str+ session: AsyncSession,+ repository_id: str,+ *,+ root_name: str | None = None,) -> list[Container]:"""Return the list of containers detected for ``repository_id``.+ ``root_name`` (the repository name) labels the root container of a+ single-manifest / root-manifest repo, which would otherwise serialize as+ the uninformative ``"."``.+Stable ordering by ``path`` so the C4 diagram doesn't reshuffle betweenrequests."""container_roots = await _container_roots_from_manifests(session, repository_id)file_nodes = await _file_nodes(session, repository_id)+ # Also treat any directory holding a package manifest as a container root,+ # even when that manifest declared no external deps (catches e.g. a core+ # package that would otherwise dissolve into the repo-root catch-all).+ container_roots |= _manifest_roots(node.node_id for node in file_nodes)+if not container_roots:container_roots = _top_level_dirs(node.node_id for node in file_nodes)@@ -50,15 +88,16 @@ async def detect_containers(if root is not None:grouped[root].append(node)+ fallback_root_name = (root_name or ".").strip() or "."containers: list[Container] = []for root in sorted(grouped):nodes = grouped[root]lang = _dominant_language(nodes)- name = root.split("/")[-1] if root else "."+ name = root.split("/")[-1] if root else fallback_root_namecontainers.append(Container(id=container_id(root),- name=name or ".",+ name=name or fallback_root_name,path=root,language=lang,file_count=len(nodes),@@ -96,11 +135,24 @@ async def _file_nodes(session: AsyncSession, repository_id: str) -> list[GraphNoselect(GraphNode).where(GraphNode.repository_id == repository_id,GraphNode.node_type == "file",+ # ``external:*`` nodes are unresolved-import / dependency targets,+ # not real source files — they must not become containers or inflate+ # file counts. Real external deps surface via the ext: mechanism.+ ~GraphNode.node_id.like("external:%"),))return list(result.scalars())+def _manifest_roots(paths: Iterable[str]) -> set[str]:+ """Parent directories of every package-manifest file node."""+ roots: set[str] = set()+ for path in paths:+ if _is_manifest(path):+ roots.add(path.rsplit("/", 1)[0] if "/" in path else "")+ return roots++def _top_level_dirs(paths: Iterable[str]) -> set[str]:out: set[str] = set()for path in paths:diff --git a/packages/server/src/repowise/server/services/c4_builder/labels.py b/packages/server/src/repowise/server/services/c4_builder/labels.pynew file mode 100644index 000000000..22f238d64--- /dev/null+++ b/packages/server/src/repowise/server/services/c4_builder/labels.py@@ -0,0 +1,72 @@+"""Human-readable relation labels and coupling strength for C4 edges.++The persisted graph stores raw edge-type tokens (``imports``,+``dynamic_imports``, ``co_changes``, ``calls`` …). Rolled up to box→box+relations these previously surfaced as opaque labels like ``"co_changes +1"``+plus a bare file-pair count. This module turns an aggregated edge's set of+types into one readable verb and buckets the pair-count into a qualitative+coupling notion, so the diagram reads in plain language instead of internals.++Pure functions — no DB, no I/O — so they unit-test in isolation.+"""++from __future__ import annotations++from collections.abc import Iterable++# Raw edge-type token -> the verb a reader expects on a C4 arrow.+_EDGE_VERB: dict[str, str] = {+ "imports": "imports",+ "dynamic_imports": "imports",+ "calls": "calls",+ "inherits": "inherits from",+ "implements": "implements",+ "references": "references",+ "contains": "contains",+ "co_changes": "co-changes",+}++# When an aggregated edge carries several types, a concrete code dependency is+# more informative than a historical (co-change) or containment signal, so we+# surface the single highest-priority verb rather than concatenating tokens.+_VERB_PRIORITY: tuple[str, ...] = (+ "calls",+ "inherits from",+ "implements",+ "imports",+ "references",+ "contains",+ "co-changes",+)++# Pair-count thresholds (inclusive lower bounds) for the coupling buckets.+_TIGHT_MIN = 50+_MODERATE_MIN = 10+++def relation_label(edge_types: Iterable[str]) -> str:+ """Return the dominant human-readable verb for a set of raw edge types.++ Folds synonyms (``dynamic_imports`` -> ``imports``), de-duplicates, and+ picks the most informative verb by :data:`_VERB_PRIORITY`. Falls back to+ ``"depends on"`` for an empty or wholly-unknown set so an arrow is never+ unlabeled.+ """+ verbs = {_EDGE_VERB[t] for t in edge_types if t in _EDGE_VERB}+ for verb in _VERB_PRIORITY:+ if verb in verbs:+ return verb+ return "depends on"+++def coupling_strength(edge_count: int) -> str:+ """Bucket a box→box pair-count into a qualitative coupling label.++ ``tight`` / ``moderate`` / ``loose`` reads as a meaningful strength where+ a raw count (``666``) does not.+ """+ if edge_count >= _TIGHT_MIN:+ return "tight"+ if edge_count >= _MODERATE_MIN:+ return "moderate"+ return "loose"diff --git a/packages/server/src/repowise/server/services/c4_builder/models.py b/packages/server/src/repowise/server/services/c4_builder/models.pyindex bcecd833f..6c1fc5eaa 100644--- a/packages/server/src/repowise/server/services/c4_builder/models.py+++ b/packages/server/src/repowise/server/services/c4_builder/models.py@@ -18,6 +18,9 @@ class Person:id: strname: strdescription: str = ""+ # How this actor enters the system: cli | api | scheduler | developer |+ # user. Drives the L1 actor icon; "user" is the generic fallback.+ kind: str = "user"@dataclass(frozen=True)@@ -60,8 +63,8 @@ class Container:@dataclass(frozen=True)class Component:- """A sub-module inside a container — top-level child directory, or the- synthetic ``_root`` group for files at the container root.+ """A sub-module inside a container — a meaningful child directory, or the+ synthetic ``(root)`` group for files that sit at the container root."""id: str # "cmp:packages/core/ingestion"@@ -83,6 +86,9 @@ class Relation:label: str = ""edge_count: int = 1edge_types: tuple[str, ...] = field(default_factory=tuple)+ # Qualitative coupling strength derived from ``edge_count``:+ # loose | moderate | tight. Empty on synthetic edges (e.g. L1 actor->system).+ coupling: str = ""@dataclass(frozen=True)diff --git a/packages/server/src/repowise/server/services/c4_builder/relations.py b/packages/server/src/repowise/server/services/c4_builder/relations.pyindex 9edbca06d..6d3e0b8b7 100644--- a/packages/server/src/repowise/server/services/c4_builder/relations.py+++ b/packages/server/src/repowise/server/services/c4_builder/relations.py@@ -20,10 +20,12 @@ from __future__ import annotationsfrom collections import defaultdict-from repowise.core.persistence import ExternalSystem, GraphEdge, GraphNodefrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.persistence import ExternalSystem, GraphEdge, GraphNode++from .labels import coupling_strength, relation_labelfrom .models import Relation@@ -73,14 +75,14 @@ async def aggregate_relations(relations: list[Relation] = []for (src_box, tgt_box), count in counts.items():etypes = tuple(sorted(types[(src_box, tgt_box)]))- label = etypes[0] if len(etypes) == 1 else f"{etypes[0]} +{len(etypes) - 1}"relations.append(Relation(source_id=src_box,target_id=tgt_box,- label=label,+ label=relation_label(etypes),edge_count=count,edge_types=etypes,+ coupling=coupling_strength(count),))relations.sort(key=lambda r: (-r.edge_count, r.source_id, r.target_id))diff --git a/packages/server/src/repowise/server/services/c4_builder/signals.py b/packages/server/src/repowise/server/services/c4_builder/signals.pynew file mode 100644index 000000000..3445ed0d2--- /dev/null+++ b/packages/server/src/repowise/server/services/c4_builder/signals.py@@ -0,0 +1,38 @@+"""Roll per-file health signals (hotspots, dead code) up to C4 boxes.++The graph already carries which files are churn hotspots (``git_metadata``)+and which are unreachable dead code (``dead_code_findings``); the container+view simply never counted them, so every box serialized ``0``. This module is+the pure aggregation: given a file->box map and the sets of flagged file+paths, count per box. The DB load lives in the builder; the counting is here+so it unit-tests without a session.+"""++from __future__ import annotations++from collections import defaultdict+from collections.abc import Iterable, Mapping+++def count_box_signals(+ file_to_box: Mapping[str, str],+ hotspot_paths: Iterable[str],+ dead_paths: Iterable[str],+) -> dict[str, tuple[int, int]]:+ """Return ``box_id -> (hotspot_count, dead_count)``.++ Every box present in ``file_to_box`` appears in the result (with zeros+ when it owns no flagged files), so callers can annotate unconditionally.+ """+ hotspots = set(hotspot_paths)+ dead = set(dead_paths)+ hot_by_box: dict[str, int] = defaultdict(int)+ dead_by_box: dict[str, int] = defaultdict(int)+ boxes: set[str] = set()+ for path, box in file_to_box.items():+ boxes.add(box)+ if path in hotspots:+ hot_by_box[box] += 1+ if path in dead:+ dead_by_box[box] += 1+ return {box: (hot_by_box[box], dead_by_box[box]) for box in boxes}diff --git a/packages/ui/src/c4/edges/RelationEdge.tsx b/packages/ui/src/c4/edges/RelationEdge.tsxindex 8666b76c2..e6ac62ede 100644--- a/packages/ui/src/c4/edges/RelationEdge.tsx+++ b/packages/ui/src/c4/edges/RelationEdge.tsx@@ -41,13 +41,17 @@ function RelationEdgeImpl(props: EdgeProps) {});const stroke = selected ? THEME.selection.ring : "var(--color-diagram-edge)";- const strokeWidth = relation && relation.edge_count > 5 ? 2 : 1.25;+ // Tighter coupling reads as a heavier line. Falls back to the pair-count+ // when the relation predates the coupling field.+ const couplingWidth: Record<string, number> = { tight: 2.25, moderate: 1.75, loose: 1.25 };+ const strokeWidth = relation+ ? (couplingWidth[relation.coupling ?? ""] ?? (relation.edge_count > 5 ? 2 : 1.25))+ : 1.25;+ // The backend now ships a readable verb ("imports", "co-changes"); keep a+ // bare-type fallback only for older payloads that predate it.const label = relation- ? relation.label ||- (relation.edge_count > 1- ? `${relation.edge_count} ${relation.edge_types[0] ?? "calls"}`- : (relation.edge_types[0] ?? ""))+ ? relation.label || (relation.edge_types[0] ?? ""): "";return (diff --git a/packages/ui/src/c4/nodes/ArchContainerNode.tsx b/packages/ui/src/c4/nodes/ArchContainerNode.tsxindex 71d4e301b..001b18ab4 100644--- a/packages/ui/src/c4/nodes/ArchContainerNode.tsx+++ b/packages/ui/src/c4/nodes/ArchContainerNode.tsx@@ -25,12 +25,19 @@ function ArchContainerNodeImpl(props: NodeProps) {const ChevronIcon = expanded ? ChevronDown : ChevronRight;// Unified click grammar (kg-ux plan B5): single click selects (page-level- // handler); double-click expands/collapses (page-level too). Keyboard- // Enter/Space mirrors single-click selection.+ // handler). Keyboard Enter/Space mirrors single-click selection.const handleSelect = () => {useArchitectureStore.getState().selectNode(containerId);};+ // Expand/collapse on double-click, owned here so it stays reliable even when+ // a preceding single-click eases the camera and slides the node out from+ // under the cursor (which would make React Flow miss the second click).+ const handleToggle = (e: { stopPropagation: () => void }) => {+ e.stopPropagation();+ useArchitectureStore.getState().toggleContainer(containerId);+ };+// Diagram ink, not panel chrome: the panel border tokens sit at ~12% alpha// and disappear into the paper canvas in light mode, leaving the (full-ink)// edges pointing at boxes the eye can't see. Folder containers are@@ -44,6 +51,7 @@ function ArchContainerNodeImpl(props: NodeProps) {role="button"tabIndex={0}aria-label={`Inspect folder ${label}`}+ onDoubleClick={handleToggle}onKeyDown={(e) => {if (e.key === "Enter" || e.key === " ") {e.preventDefault();diff --git a/packages/ui/src/c4/nodes/ComponentNode.tsx b/packages/ui/src/c4/nodes/ComponentNode.tsxindex fc1cddb2f..22977eb68 100644--- a/packages/ui/src/c4/nodes/ComponentNode.tsx+++ b/packages/ui/src/c4/nodes/ComponentNode.tsx@@ -18,7 +18,7 @@ function ComponentNodeImpl(props: NodeProps) {<NodeShelltone="component"kindLabel="Component"- title={component.name === "_root" ? "(root)" : component.name}+ title={component.name}subtitle={component.path !== component.name ? component.path : undefined}selected={selected}hasDocs={hasDocs}diff --git a/packages/ui/src/c4/nodes/LayerClusterNode.tsx b/packages/ui/src/c4/nodes/LayerClusterNode.tsxindex 947812c3f..8e10126ff 100644--- a/packages/ui/src/c4/nodes/LayerClusterNode.tsx+++ b/packages/ui/src/c4/nodes/LayerClusterNode.tsx@@ -35,11 +35,26 @@ function LayerClusterNodeImpl(props: NodeProps) {// Unified click grammar (kg-ux plan B5): single click / Enter = select +// inspect (the page-level onNodeClick handles mouse; keyboard mirrors it- // here). Drilling moved to double-click, owned by the page handler.+ // here).const handleSelect = () => {useArchitectureStore.getState().selectNode(layer.id);};+ // Drill on double-click, owned here rather than only by the page-level+ // onNodeDoubleClick: a single click eases the camera onto the selected card,+ // which can slide the node out from under the cursor so React Flow never+ // registers the second click as a node double-click. Handling it on the card+ // (and stopping propagation) makes "double-click to open" reliable.+ const handleDrill = (e: { stopPropagation: () => void }) => {+ e.stopPropagation();+ const store = useArchitectureStore.getState();+ if (kind === "subGroup") {+ store.drillIntoSubGroup(layer.id);+ } else {+ store.drillIntoLayer(layer.id);+ }+ };+const dominantComplexity = (["complex", "moderate", "simple"] as const).find((c) => (layer.complexity_distribution[c] ?? 0) > 0) ?? "simple";@@ -108,6 +123,7 @@ function LayerClusterNodeImpl(props: NodeProps) {role="button"tabIndex={0}aria-label={`${kind === "subGroup" ? "Inspect group" : "Inspect layer"} ${layer.name}`}+ onDoubleClick={handleDrill}onKeyDown={(e) => {if (e.key === "Enter" || e.key === " ") {e.preventDefault();diff --git a/packages/ui/src/c4/nodes/PersonNode.tsx b/packages/ui/src/c4/nodes/PersonNode.tsxindex 17774e7a8..ec3f0780c 100644--- a/packages/ui/src/c4/nodes/PersonNode.tsx+++ b/packages/ui/src/c4/nodes/PersonNode.tsx@@ -1,7 +1,8 @@"use client";-import { memo } from "react";-import { User } from "lucide-react";+import { memo, type ComponentType } from "react";+import { Clock, Globe, Terminal, TerminalSquare, User } from "lucide-react";+import type { LucideProps } from "lucide-react";import type { NodeProps } from "@xyflow/react";import { NodeShell } from "./node-shell";import type { C4Person } from "../types";@@ -10,9 +11,28 @@ export interface PersonNodeProps {person: C4Person;}+// Actor kind -> (icon, short footer label). Keeps the L1 actor visually+// distinct (a CLI user reads differently from an API client or a scheduler)+// instead of every actor being a generic person.+interface ActorPresentation {+ Icon: ComponentType<LucideProps>;+ label: string;+}++const GENERIC_ACTOR: ActorPresentation = { Icon: User, label: "actor" };++const ACTOR_PRESENTATION: Record<string, ActorPresentation> = {+ cli: { Icon: Terminal, label: "cli user" },+ api: { Icon: Globe, label: "api client" },+ scheduler: { Icon: Clock, label: "scheduled" },+ developer: { Icon: TerminalSquare, label: "developer" },+ user: GENERIC_ACTOR,+};+function PersonNodeImpl(props: NodeProps) {const { data, selected } = props as NodeProps & { data: PersonNodeProps };const { person } = data;+ const { Icon, label } = ACTOR_PRESENTATION[person.kind] ?? GENERIC_ACTOR;return (<NodeShelltone="person"@@ -22,7 +42,7 @@ function PersonNodeImpl(props: NodeProps) {selected={selected}footer={<span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>- <User size={11} aria-hidden /> actor+ <Icon size={11} aria-hidden /> {label}</span>}/>diff --git a/packages/ui/src/c4/types.ts b/packages/ui/src/c4/types.tsindex 88b434538..b2323cbca 100644--- a/packages/ui/src/c4/types.ts+++ b/packages/ui/src/c4/types.ts@@ -11,10 +11,14 @@ export type C4Category = "framework" | "service" | "tool" | "library";/** I/O-boundary type of an external dependency (mirrors backend `io_kind`). */export type C4IoKind = "db" | "network" | "filesystem" | "subprocess" | "lock";+/** How an L1 actor enters the system (mirrors backend `Person.kind`). */+export type C4ActorKind = "cli" | "api" | "scheduler" | "developer" | "user";+export interface C4Person {id: string;name: string;description: string;+ kind: C4ActorKind | string;}export interface C4System {@@ -54,12 +58,17 @@ export interface C4Component {symbol_count: number;}+/** Qualitative coupling strength of a relation (mirrors backend `coupling`). */+export type C4Coupling = "loose" | "moderate" | "tight";+export interface C4Relation {source_id: string;target_id: string;label: string;edge_count: number;edge_types: string[];+ /** loose | moderate | tight; empty on synthetic edges (L1 actor->system). */+ coupling?: C4Coupling | string;}export interface C4L1 {diff --git a/tests/unit/server/services/test_c4_actors.py b/tests/unit/server/services/test_c4_actors.pynew file mode 100644index 000000000..48caf1930--- /dev/null+++ b/tests/unit/server/services/test_c4_actors.py@@ -0,0 +1,56 @@+"""Unit tests for c4_builder.actors — actor derivation from entry points."""++from __future__ import annotations++import pytest++from repowise.server.services.c4_builder.actors import (+ classify_entry_point,+ derive_actors,+)+++ "path,kind",+ [+ ("packages/cli/src/repowise/cli/main.py", "cli"),+ ("src/app/__main__.py", "cli"),+ ("manage.py", "cli"),+ ("packages/server/src/repowise/server/app.py", "api"),+ ("services/gateway/asgi.py", "api"),+ ("app/api/routes.py", "api"),+ ("jobs/cron/nightly.py", "scheduler"),+ ("src/worker/tasks.py", "scheduler"),+ ("scripts/kg_validate/run.py", "developer"),+ ("tools/gen.py", "developer"),+ ("packages/types/src/index.ts", None),+ ("README.md", None),+ ],+)+def test_classify_entry_point(path, kind):+ assert classify_entry_point(path) == kind+++def test_derive_actors_dedupes_and_orders():+ actors = derive_actors(+ [+ "packages/cli/src/repowise/cli/main.py",+ "packages/server/src/repowise/server/app.py",+ "scripts/kg_validate/run.py",+ "another/cli/thing.py", # duplicate cli kind+ ]+ )+ assert [a.kind for a in actors] == ["cli", "api", "developer"]+ assert [a.id for a in actors] == ["person:cli", "person:api", "person:developer"]+ assert all(a.name and a.verb for a in actors)+++def test_derive_actors_falls_back_to_generic_user():+ actors = derive_actors([])+ assert [a.kind for a in actors] == ["user"]+ assert actors[0].name == "User"+++def test_derive_actors_ignores_unclassifiable_only():+ actors = derive_actors(["packages/types/src/index.ts", "README.md"])+ assert [a.kind for a in actors] == ["user"]diff --git a/tests/unit/server/services/test_c4_builder.py b/tests/unit/server/services/test_c4_builder.pyindex 23567265f..1b55db8da 100644--- a/tests/unit/server/services/test_c4_builder.py+++ b/tests/unit/server/services/test_c4_builder.py@@ -7,6 +7,8 @@ asserts the shape of build_l1 / build_l2 / build_l3 output.from __future__ import annotations+import json+import pytestfrom repowise.core.persistence import (@@ -16,6 +18,11 @@ from repowise.core.persistence import (link_graph_nodes_to_external_systems,upsert_repository,)+from repowise.core.persistence.models import (+ DeadCodeFinding,+ GitMetadata,+ KnowledgeGraphProjectMeta,+)from repowise.server.services import c4_builder@@ -122,3 +129,125 @@ async def test_build_l3_unknown_container_returns_none(async_session):repo = await _seed_monorepo(async_session)view = await c4_builder.build_l3(async_session, repo.id, "pkg:does/not/exist")assert view is None+++# ---------------------------------------------------------------------------+# Phase 3 shaping: root naming, external/sibling exclusion, component depth,+# signal counts, derived L1 actors.+# ---------------------------------------------------------------------------+++async def _seed_single_package(session):+ """A root-manifest repo (one pyproject.toml at the root) with a ``src``+ layout, a stray unresolved external node, and curated entry points.+ """+ repo = await upsert_repository(session, name="acme-tool", local_path="/tmp/acme")+ files = [+ "pyproject.toml",+ "README.md",+ "src/acme/cli/main.py",+ "src/acme/server/app.py",+ "src/acme/core/engine.py",+ "scripts/run.py",+ ]+ nodes = [+ {"node_id": f, "node_type": "file", "language": "python", "symbol_count": 2}+ for f in files+ ]+ # An unresolved-import target — must never become a file/component.+ nodes.append({"node_id": "external:@/lib/thing", "node_type": "file", "language": "python", "symbol_count": 0})+ await batch_upsert_graph_nodes(session, repo.id, nodes)++ session.add(+ KnowledgeGraphProjectMeta(+ repository_id=repo.id,+ entry_points_json=json.dumps(+ ["src/acme/cli/main.py", "src/acme/server/app.py", "scripts/run.py"]+ ),+ )+ )+ # One hotspot + one dead file so the counts have something to report.+ session.add(GitMetadata(repository_id=repo.id, file_path="src/acme/core/engine.py", is_hotspot=True))+ session.add(+ DeadCodeFinding(+ repository_id=repo.id,+ kind="unreachable_file",+ file_path="src/acme/cli/main.py",+ status="open",+ confidence=0.9,+ reason="",+ )+ )+ await session.commit()+ return repo+++async def test_root_container_uses_repo_name_not_dot(async_session):+ repo = await _seed_single_package(async_session)+ view = await c4_builder.build_l2(async_session, repo.id)+ root = next(c for c in view.containers if c.path == "")+ assert root.name == "acme-tool"+ assert root.name != "."+++async def test_external_nodes_excluded_from_counts_and_components(async_session):+ repo = await _seed_single_package(async_session)+ view = await c4_builder.build_l2(async_session, repo.id)+ root = next(c for c in view.containers if c.path == "")+ # 6 real files, not 7 — the external:@ node is excluded.+ assert root.file_count == 6++ l3 = await c4_builder.build_l3(async_session, repo.id, root.id)+ assert l3 is not None+ assert all("external:" not in c.id for c in l3.components)+ assert all("external:" not in c.path for c in l3.components)+++async def test_component_depth_skips_passthrough_and_names_root_bucket(async_session):+ repo = await _seed_single_package(async_session)+ root = next(+ c for c in (await c4_builder.build_l2(async_session, repo.id)).containers if c.path == ""+ )+ l3 = await c4_builder.build_l3(async_session, repo.id, root.id)+ assert l3 is not None+ names = {c.name for c in l3.components}+ # `src/acme/...` strips `src`, surfacing `acme` rather than a giant `src`;+ # the root-level files collapse into a labeled bucket, never "_root".+ assert "acme" in names+ assert "scripts" in names+ assert "_root" not in names+ assert "(root)" in names+ assert not any(c.id.endswith("/_root") or "_root" in c.id for c in l3.components)+++async def test_container_signal_counts_populated(async_session):+ repo = await _seed_single_package(async_session)+ view = await c4_builder.build_l2(async_session, repo.id)+ root = next(c for c in view.containers if c.path == "")+ assert root.hotspot_count == 1+ assert root.dead_count == 1+++async def test_l1_actors_derived_from_entry_points(async_session):+ repo = await _seed_single_package(async_session)+ view = await c4_builder.build_l1(async_session, repo.id)+ kinds = [p.kind for p in view.people]+ assert kinds == ["cli", "api", "developer"]+ # Every actor drives one edge into the system.+ actor_edges = [r for r in view.relations if r.target_id == view.system.id]+ assert len(actor_edges) == 3+++async def test_relation_labels_are_readable_with_coupling(async_session):+ repo = await _seed_monorepo(async_session)+ view = await c4_builder.build_l2(async_session, repo.id)+ cross = next(r for r in view.relations if r.source_id == "pkg:packages/web")+ assert cross.label == "imports"+ assert cross.coupling in {"loose", "moderate", "tight"}+ assert "+1" not in cross.labeldiff --git a/tests/unit/server/services/test_c4_labels.py b/tests/unit/server/services/test_c4_labels.pynew file mode 100644index 000000000..ec0a5278d--- /dev/null+++ b/tests/unit/server/services/test_c4_labels.py@@ -0,0 +1,46 @@+"""Unit tests for c4_builder.labels — relation verbs + coupling buckets."""++from __future__ import annotations++import pytest++from repowise.server.services.c4_builder.labels import coupling_strength, relation_label+++ "edge_types,expected",+ [+ (("imports",), "imports"),+ (("co_changes",), "co-changes"),+ # A concrete code dependency outranks a historical co-change signal.+ (("co_changes", "imports"), "imports"),+ # Synonyms fold into one verb, not "imports +1".+ (("dynamic_imports", "imports"), "imports"),+ (("dynamic_imports",), "imports"),+ (("calls", "imports"), "calls"),+ # Empty / unknown never yields a bare token or empty string.+ ((), "depends on"),+ (("totally_unknown",), "depends on"),+ ],+)+def test_relation_label(edge_types, expected):+ assert relation_label(edge_types) == expected+++def test_relation_label_accepts_any_iterable_order():+ assert relation_label({"imports", "co_changes"}) == "imports"+++ "count,expected",+ [+ (1, "loose"),+ (9, "loose"),+ (10, "moderate"),+ (49, "moderate"),+ (50, "tight"),+ (666, "tight"),+ ],+)+def test_coupling_strength(count, expected):+ assert coupling_strength(count) == expecteddiff --git a/tests/unit/server/services/test_c4_signals.py b/tests/unit/server/services/test_c4_signals.pynew file mode 100644index 000000000..49563b078--- /dev/null+++ b/tests/unit/server/services/test_c4_signals.py@@ -0,0 +1,30 @@+"""Unit tests for c4_builder.signals — per-box hotspot/dead aggregation."""++from __future__ import annotations++from repowise.server.services.c4_builder.signals import count_box_signals+++def test_count_box_signals_buckets_per_box():+ file_to_box = {+ "a/x.py": "pkg:a",+ "a/y.py": "pkg:a",+ "b/z.py": "pkg:b",+ "b/q.py": "pkg:b",+ }+ hotspots = ["a/x.py", "b/z.py", "b/q.py"]+ dead = ["a/y.py"]+ counts = count_box_signals(file_to_box, hotspots, dead)+ assert counts == {"pkg:a": (1, 1), "pkg:b": (2, 0)}+++def test_count_box_signals_includes_zero_boxes():+ file_to_box = {"a/x.py": "pkg:a"}+ counts = count_box_signals(file_to_box, [], [])+ assert counts == {"pkg:a": (0, 0)}+++def test_count_box_signals_ignores_unmapped_paths():+ # A flagged path with no box mapping must not crash or count anywhere.+ counts = count_box_signals({"a/x.py": "pkg:a"}, ["unmapped/file.py"], [])+ assert counts == {"pkg:a": (0, 0)}diff --git a/tests/unit/server/test_c4.py b/tests/unit/server/test_c4.pyindex fd7cac8be..43a81df75 100644--- a/tests/unit/server/test_c4.py+++ b/tests/unit/server/test_c4.py@@ -104,9 +104,11 @@ async def test_l3_endpoint_returns_components_for_container(client: AsyncClient,assert resp.status_code == 200body = resp.json()assert body["container"]["path"] == "packages/core"- # All files in packages/core sit at the container root → _root component+ # All files in packages/core sit at the container root → the labeled root+ # bucket, never the leaky "_root" token.comp_names = {c["name"] for c in body["components"]}- assert comp_names == {"_root"}+ assert comp_names == {"(root)"}+ assert "_root" not in {c["id"] for c in body["components"]}# Only fastapi (used from packages/core), react is filtered outassert {e["name"] for e in body["external_systems"]} == {"fastapi"}