Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

refactor(external-systems): fold package summaries and relationships in core (#2025)

Raghav Chamadiya4a810833c323
diff --git a/packages/core/src/repowise/core/analysis/external_systems/__init__.py b/packages/core/src/repowise/core/analysis/external_systems/__init__.py
new file mode 100644
index 000000000..a11c366b3
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/external_systems/__init__.py
@@ -0,0 +1,83 @@
+"""Session-free folds behind the external-dependency surface.
+
+The aggregation these modules perform used to be SQL fused to a live
+``AsyncSession`` in ``repowise.server.services``, which meant any second
+consumer — an indexer precomputing artifacts, a deployment without the graph
+tables — had to reimplement the bounds and the truncation flags and could
+disagree with the product about what a page was not showing. Taking plain
+records instead of a session leaves one owner for those semantics.
+
+The server layer keeps the queries; it fetches rows and hands them here.
+"""
+
+from __future__ import annotations
+
+from .records import (
+ AUXILIARY_PREFIXES,
+ Scope,
+ in_scope,
+ is_primary_path,
+ package_key,
+ split_package_key,
+ target_basis,
+)
+from .registry import PackageRegistry, RegistryEntry, build_registry
+from .relationships import (
+ DEFAULT_FILE_LIMIT,
+ DEFAULT_RELATIONSHIP_EDGE_LIMIT,
+ DEFAULT_RELATIONSHIP_NODE_LIMIT,
+ EVIDENCE_TARGET_LIMIT,
+ EXTERNAL_TARGET_LIMIT,
+ GraphTarget,
+ ImportingFile,
+ ImportingFiles,
+ RelationshipEdge,
+ RelationshipGraph,
+ RelationshipNode,
+ build_importing_files,
+ build_relationship_graph,
+ community_key,
+ resolve_targets,
+ split_community_key,
+)
+from .summary import (
+ DEFAULT_SUMMARY_LIMIT,
+ SUMMARY_VERSION_LIMIT,
+ PackageEntry,
+ PackageSummary,
+ build_package_summary,
+)
+
+__all__ = [
+ "AUXILIARY_PREFIXES",
+ "DEFAULT_FILE_LIMIT",
+ "DEFAULT_RELATIONSHIP_EDGE_LIMIT",
+ "DEFAULT_RELATIONSHIP_NODE_LIMIT",
+ "DEFAULT_SUMMARY_LIMIT",
+ "EVIDENCE_TARGET_LIMIT",
+ "EXTERNAL_TARGET_LIMIT",
+ "SUMMARY_VERSION_LIMIT",
+ "GraphTarget",
+ "ImportingFile",
+ "ImportingFiles",
+ "PackageEntry",
+ "PackageRegistry",
+ "PackageSummary",
+ "RegistryEntry",
+ "RelationshipEdge",
+ "RelationshipGraph",
+ "RelationshipNode",
+ "Scope",
+ "build_importing_files",
+ "build_package_summary",
+ "build_registry",
+ "build_relationship_graph",
+ "community_key",
+ "in_scope",
+ "is_primary_path",
+ "package_key",
+ "resolve_targets",
+ "split_community_key",
+ "split_package_key",
+ "target_basis",
+]
diff --git a/packages/core/src/repowise/core/analysis/external_systems/records.py b/packages/core/src/repowise/core/analysis/external_systems/records.py
new file mode 100644
index 000000000..580c85665
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/external_systems/records.py
@@ -0,0 +1,71 @@
+"""The record conventions both external-dependency folds share.
+
+Both folds read the same three record kinds — a manifest declaration, an
+external graph node resolved to a declared package, and an import edge that
+reaches one — and both need the same two conventions: which declaration paths
+count as the repository proper, and how a package identity round-trips through
+a single string. They live here so the two folds cannot answer them
+differently.
+"""
+
+from __future__ import annotations
+
+from typing import Literal
+
+# ``field`` reads a dataclass, an ORM row or a dict alike. It is the shared
+# adapter for exactly this problem; it sits under ``health`` only because that
+# is where the first fold needing it was written.
+from repowise.core.analysis.health.rows import field
+
+Scope = Literal["primary", "all"]
+
+#: Declaration paths that describe a checkout of some other tree living inside
+#: this one. Counted, reported as ``excluded_declarations``, never folded into
+#: the primary scope's totals.
+AUXILIARY_PREFIXES = (".claude/worktrees/", "local-stash/")
+
+
+def is_primary_path(path: str | None) -> bool:
+ """Whether a declaration or importing file belongs to the repository proper."""
+ return not (path or "").startswith(AUXILIARY_PREFIXES)
+
+
+def in_scope(path: str | None, scope: Scope) -> bool:
+ """Whether a path is visible under ``scope``."""
+ return True if scope == "all" else is_primary_path(path)
+
+
+def package_key(ecosystem: str, name: str) -> str:
+ """The single string that addresses one package across the HTTP surface."""
+ return f"{ecosystem}:{name}"
+
+
+def split_package_key(key: str) -> tuple[str, str]:
+ """Invert :func:`package_key`, rejecting anything that is not one."""
+ ecosystem, separator, name = key.partition(":")
+ if not separator or not ecosystem or not name:
+ raise ValueError("package_key must contain an ecosystem and package name")
+ return ecosystem, name
+
+
+def target_basis(node_id: str, package_name: str) -> Literal["exact", "subpath", "mapped"]:
+ """How confidently one external graph node stands for the declared package."""
+ value = node_id.casefold()
+ expected = f"external:{package_name}".casefold()
+ if value == expected:
+ return "exact"
+ if value.startswith(f"{expected}/") or value.startswith(f"{expected}:"):
+ return "subpath"
+ return "mapped"
+
+
+__all__ = [
+ "AUXILIARY_PREFIXES",
+ "Scope",
+ "field",
+ "in_scope",
+ "is_primary_path",
+ "package_key",
+ "split_package_key",
+ "target_basis",
+]
diff --git a/packages/core/src/repowise/core/analysis/external_systems/registry.py b/packages/core/src/repowise/core/analysis/external_systems/registry.py
new file mode 100644
index 000000000..a21cb1b30
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/external_systems/registry.py
@@ -0,0 +1,98 @@
+"""The declaration registry, folded without deduplication or bounds.
+
+The unit here is a declaration, not a package: one row per name and manifest,
+so a monorepo's per-package manifests stay distinguishable. That is what
+separates this from :mod:`.summary`, which collapses the same rows to one entry
+per package and pages them. Neither is a view of the other.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from dataclasses import dataclass
+from typing import Any
+
+from .records import field
+
+#: Sort prominence, not a judgement of importance — a stable order to render in.
+_CATEGORY_ORDER = {"framework": 0, "service": 1, "tool": 2, "library": 3}
+_UNRANKED = 9
+
+
+@dataclass(frozen=True, slots=True)
+class RegistryEntry:
+ """One declared third-party dependency, as one manifest declared it."""
+
+ name: str
+ display_name: str
+ ecosystem: str
+ category: str
+ io_kind: str | None
+ version: str | None
+ declared_in: str
+ is_dev_dep: bool
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "name": self.name,
+ "display_name": self.display_name,
+ "ecosystem": self.ecosystem,
+ "category": self.category,
+ "io_kind": self.io_kind,
+ "version": self.version,
+ "declared_in": self.declared_in,
+ "is_dev_dep": self.is_dev_dep,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class PackageRegistry:
+ """Every declaration in the repository, ordered and counted."""
+
+ items: list[RegistryEntry]
+ total: int
+ prod_count: int
+ dev_count: int
+ ecosystems: list[str]
+ manifests: list[str]
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "items": [item.as_dict() for item in self.items],
+ "total": self.total,
+ "prod_count": self.prod_count,
+ "dev_count": self.dev_count,
+ "ecosystems": list(self.ecosystems),
+ "manifests": list(self.manifests),
+ }
+
+
+def build_registry(declarations: Iterable[Any]) -> PackageRegistry:
+ """Fold declaration records into the unfiltered, undeduplicated registry."""
+ items = sorted(
+ (
+ RegistryEntry(
+ name=field(row, "name", "") or "",
+ display_name=field(row, "display_name", "") or field(row, "name", "") or "",
+ ecosystem=field(row, "ecosystem", "") or "",
+ category=field(row, "category", "") or "",
+ io_kind=field(row, "io_kind", None),
+ version=field(row, "version", None),
+ declared_in=field(row, "declared_in", "") or "",
+ is_dev_dep=bool(field(row, "is_dev_dep", False)),
+ )
+ for row in declarations
+ ),
+ key=lambda e: (_CATEGORY_ORDER.get(e.category, _UNRANKED), e.name.lower(), e.declared_in),
+ )
+ return PackageRegistry(
+ items=items,
+ total=len(items),
+ prod_count=sum(1 for e in items if not e.is_dev_dep),
+ dev_count=sum(1 for e in items if e.is_dev_dep),
+ ecosystems=sorted({e.ecosystem for e in items}),
+ manifests=sorted({e.declared_in for e in items}),
+ )
+
+
+__all__ = ["PackageRegistry", "RegistryEntry", "build_registry"]
diff --git a/packages/core/src/repowise/core/analysis/external_systems/relationships.py b/packages/core/src/repowise/core/analysis/external_systems/relationships.py
new file mode 100644
index 000000000..4f70c8c57
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/external_systems/relationships.py
@@ -0,0 +1,450 @@
+"""Composing one package's bounded relationship graph and its file expansion.
+
+Aggregate-first: the graph never names a file. Its nodes are the first-party
+communities that import the package, and a file list is a second, separately
+bounded request against one of them. That is what keeps a package with
+thousands of importers renderable.
+
+Session-free for the same reason as :mod:`.summary` — one implementation
+answers for a live database and for a precomputed artifact, so the caps and the
+flags that confess them cannot be re-derived differently by a second consumer.
+
+Both folds resolve the package's target nodes through the same helper, so the
+evidence the graph counts is the evidence the file expansion pages. Divergence
+there would let a community claim importers the drill-down could not show.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import json
+from collections.abc import Iterable
+from dataclasses import dataclass
+from typing import Any
+
+from .records import Scope, field, in_scope, split_package_key, target_basis
+
+#: Communities returned per graph, and edges, which are one per community here.
+DEFAULT_RELATIONSHIP_NODE_LIMIT = 50
+DEFAULT_RELATIONSHIP_EDGE_LIMIT = 200
+#: Files returned per expansion page.
+DEFAULT_FILE_LIMIT = 25
+#: Resolved external nodes named in the response, out of those counted.
+EXTERNAL_TARGET_LIMIT = 20
+#: Resolved external nodes whose edges are counted at all. Beyond this the
+#: response says ``evidence_truncated`` rather than quietly undercounting.
+EVIDENCE_TARGET_LIMIT = 200
+
+
+@dataclass(frozen=True, slots=True)
+class GraphTarget:
+ """One persisted external graph node linked to the selected package."""
+
+ node_id: str
+ match_basis: str
+
+ def as_dict(self) -> dict[str, Any]:
+ return {"node_id": self.node_id, "match_basis": self.match_basis}
+
+
+@dataclass(frozen=True, slots=True)
+class RelationshipNode:
+ """A first-party graph community that imports the selected package."""
+
+ aggregate_key: str
+ label: str
+ community_id: int
+ importing_file_count: int
+ import_edge_count: int
+ top_file: str | None
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "aggregate_key": self.aggregate_key,
+ "label": self.label,
+ "community_id": self.community_id,
+ "importing_file_count": self.importing_file_count,
+ "import_edge_count": self.import_edge_count,
+ "top_file": self.top_file,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class RelationshipEdge:
+ source: str
+ target: str
+ import_edge_count: int
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "source": self.source,
+ "target": self.target,
+ "import_edge_count": self.import_edge_count,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class RelationshipGraph:
+ """One package plus the bounded set of communities that reach it."""
+
+ package_key: str
+ package_name: str
+ package_node_id: str
+ match_basis: str
+ matched_external_nodes: list[GraphTarget]
+ matched_external_nodes_total: int
+ matched_external_nodes_truncated: bool
+ evidence_target_limit: int
+ evidence_truncated: bool
+ nodes: list[RelationshipNode]
+ edges: list[RelationshipEdge]
+ aggregate_total: int
+ aggregate_returned: int
+ edge_total: int
+ edge_returned: int
+ importing_file_total: int
+ import_edge_total: int
+ node_limit: int
+ edge_limit: int
+ truncated: bool
+ scope: str
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "package_key": self.package_key,
+ "package_name": self.package_name,
+ "package_node_id": self.package_node_id,
+ "match_basis": self.match_basis,
+ "matched_external_nodes": [t.as_dict() for t in self.matched_external_nodes],
+ "matched_external_nodes_total": self.matched_external_nodes_total,
+ "matched_external_nodes_truncated": self.matched_external_nodes_truncated,
+ "evidence_target_limit": self.evidence_target_limit,
+ "evidence_truncated": self.evidence_truncated,
+ "nodes": [n.as_dict() for n in self.nodes],
+ "edges": [e.as_dict() for e in self.edges],
+ "aggregate_total": self.aggregate_total,
+ "aggregate_returned": self.aggregate_returned,
+ "edge_total": self.edge_total,
+ "edge_returned": self.edge_returned,
+ "importing_file_total": self.importing_file_total,
+ "import_edge_total": self.import_edge_total,
+ "node_limit": self.node_limit,
+ "edge_limit": self.edge_limit,
+ "truncated": self.truncated,
+ "scope": self.scope,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class ImportingFile:
+ path: str
+ language: str
+ import_edge_count: int
+ matched_external_node_count: int
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "path": self.path,
+ "language": self.language,
+ "import_edge_count": self.import_edge_count,
+ "matched_external_node_count": self.matched_external_node_count,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class ImportingFiles:
+ """One independently bounded page of files behind an aggregate node."""
+
+ package_key: str
+ aggregate_key: str
+ items: list[ImportingFile]
+ total: int
+ returned: int
+ limit: int
+ offset: int
+ truncated: bool
+ scope: str
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "package_key": self.package_key,
+ "aggregate_key": self.aggregate_key,
+ "items": [item.as_dict() for item in self.items],
+ "total": self.total,
+ "returned": self.returned,
+ "limit": self.limit,
+ "offset": self.offset,
+ "truncated": self.truncated,
+ "scope": self.scope,
+ }
+
+
+def community_key(community_id: int) -> str:
+ """The aggregate key that addresses one community across the surface."""
+ return f"community:{community_id}"
+
+
+def split_community_key(aggregate_key: str) -> int:
+ """Invert :func:`community_key`, rejecting anything that is not one."""
+ prefix, separator, value = aggregate_key.partition(":")
+ if prefix != "community" or not separator:
+ raise ValueError("aggregate_key must identify a graph community")
+ try:
+ return int(value)
+ except ValueError as exc:
+ raise ValueError("aggregate_key must identify a graph community") from exc
+
+
+def _community_label(meta_json: str | None, community_id: int, top_file: str | None) -> str:
+ """A community's own label, else the shared root of what it imports from."""
+ try:
+ label = json.loads(meta_json or "{}").get("label")
+ except (json.JSONDecodeError, TypeError, AttributeError):
+ label = None
+ if isinstance(label, str) and label.strip():
+ return label.strip()
+ if top_file:
+ parts = top_file.replace("\\", "/").split("/")
+ return "/".join(parts[:2]) if len(parts) > 1 else parts[0]
+ return f"Community {community_id}"
+
+
+def resolve_targets(
+ declarations: Iterable[Any],
+ links: Iterable[Any],
+ ecosystem: str,
+ name: str,
+ scope: Scope,
+) -> tuple[str, list[str], int] | None:
+ """The scoped, capped target universe both relationship reads work from.
+
+ Returns ``None`` when the package is not declared in this scope, which the
+ surface answers as a 404. A package declared but linked to nothing resolves
+ to an empty target list, which is a different and answerable state.
+ """
+ declared_name: str | None = None
+ for row in declarations:
+ if not in_scope(field(row, "declared_in", "") or "", scope):
+ continue
+ if (field(row, "ecosystem", "") or "") == ecosystem and (
+ field(row, "name", "") or ""
+ ) == name:
+ declared_name = name
+ break
+ if declared_name is None:
+ return None
+ node_ids = sorted(
+ {
+ node_id
+ for row in links
+ if (field(row, "ecosystem", "") or "") == ecosystem
+ and (field(row, "name", "") or "") == name
+ and (node_id := field(row, "node_id", None)) is not None
+ }
+ )
+ return declared_name, node_ids[:EVIDENCE_TARGET_LIMIT], len(node_ids)
+
+
+@dataclass(slots=True)
+class _Community:
+ """One community's import evidence, reduced as edges arrive."""
+
+ community_id: int
+ import_edge_count: int = 0
+ importing_files: set[str] = dataclasses.field(default_factory=set)
+ top_file: str | None = None
+ community_meta_json: str | None = None
+
+
+def _group_by_community(
+ import_edges: Iterable[Any], targets: set[str], scope: Scope
+) -> list[_Community]:
+ """Fold the edges reaching ``targets`` into ranked per-community aggregates."""
+ groups: dict[int, _Community] = {}
+ for row in import_edges:
+ source = field(row, "source_path", None)
+ if field(row, "target_node_id", None) not in targets:
+ continue
+ if not in_scope(source, scope):
+ continue
+ community_id = int(field(row, "community_id", 0) or 0)
+ group = groups.get(community_id)
+ if group is None:
+ group = _Community(community_id=community_id)
+ groups[community_id] = group
+ group.import_edge_count += 1
+ group.importing_files.add(source)
+ if group.top_file is None or source < group.top_file:
+ group.top_file = source
+ meta = field(row, "community_meta_json", None)
+ if meta is not None and (
+ group.community_meta_json is None or meta > group.community_meta_json
+ ):
+ group.community_meta_json = meta
+ ranked = sorted(
+ groups.values(),
+ key=lambda g: (-len(g.importing_files), -g.import_edge_count, g.community_id),
+ )
+ return ranked
+
+
+def build_relationship_graph(
+ declarations: Iterable[Any],
+ links: Iterable[Any],
+ import_edges: Iterable[Any],
+ package_key: str,
+ *,
+ scope: Scope = "primary",
+ node_limit: int = DEFAULT_RELATIONSHIP_NODE_LIMIT,
+ edge_limit: int = DEFAULT_RELATIONSHIP_EDGE_LIMIT,
+) -> RelationshipGraph | None:
+ """Fold one package's importers into bounded per-community aggregates.
+
+ ``import_edges`` are the file-sourced import edges, each carrying
+ ``source_path``, ``target_node_id``, ``community_id`` and
+ ``community_meta_json`` for the importing file's community. A
+ ``package_key`` that names no ecosystem and package raises ``ValueError``.
+ """
+ ecosystem, name = split_package_key(package_key)
+ resolved = resolve_targets(declarations, links, ecosystem, name, scope)
+ if resolved is None:
+ return None
+ package_name, target_nodes, target_total = resolved
+ matched = [
+ GraphTarget(node_id=node_id, match_basis=target_basis(node_id, package_name))
+ for node_id in target_nodes[:EXTERNAL_TARGET_LIMIT]
+ ]
+ bases = {target_basis(node_id, package_name) for node_id in target_nodes}
+ match_basis = "unresolved" if not bases else next(iter(bases)) if len(bases) == 1 else "mixed"
+ evidence_truncated = target_total > len(target_nodes)
+ package_node_id = f"package:{package_key}"
+
+ ranked = _group_by_community(import_edges, set(target_nodes), scope) if target_nodes else []
+ returned = ranked[: min(node_limit, edge_limit)]
+ nodes = [
+ RelationshipNode(
+ aggregate_key=community_key(group.community_id),
+ label=_community_label(group.community_meta_json, group.community_id, group.top_file),
+ community_id=group.community_id,
+ importing_file_count=len(group.importing_files),
+ import_edge_count=group.import_edge_count,
+ top_file=group.top_file,
+ )
+ for group in returned
+ ]
+ edges = [
+ RelationshipEdge(
+ source=node.aggregate_key,
+ target=package_node_id,
+ import_edge_count=node.import_edge_count,
+ )
+ for node in nodes
+ ]
+ return RelationshipGraph(
+ package_key=package_key,
+ package_name=package_name,
+ package_node_id=package_node_id,
+ match_basis=match_basis,
+ matched_external_nodes=matched,
+ matched_external_nodes_total=target_total,
+ matched_external_nodes_truncated=target_total > len(matched),
+ evidence_target_limit=EVIDENCE_TARGET_LIMIT,
+ evidence_truncated=evidence_truncated,
+ nodes=nodes,
+ edges=edges,
+ aggregate_total=len(ranked),
+ aggregate_returned=len(nodes),
+ edge_total=len(ranked),
+ edge_returned=len(edges),
+ importing_file_total=sum(len(g.importing_files) for g in ranked),
+ import_edge_total=sum(g.import_edge_count for g in ranked),
+ node_limit=node_limit,
+ edge_limit=edge_limit,
+ truncated=len(ranked) > len(nodes) or evidence_truncated,
+ scope=scope,
+ )
+
+
+def build_importing_files(
+ declarations: Iterable[Any],
+ links: Iterable[Any],
+ import_edges: Iterable[Any],
+ package_key: str,
+ aggregate_key: str,
+ *,
+ scope: Scope = "primary",
+ limit: int = DEFAULT_FILE_LIMIT,
+ offset: int = 0,
+) -> ImportingFiles | None:
+ """Page the files behind one community aggregate, bounded independently.
+
+ Raises ``ValueError`` if either key is not the shape its builder emits.
+ """
+ ecosystem, name = split_package_key(package_key)
+ community_id = split_community_key(aggregate_key)
+ resolved = resolve_targets(declarations, links, ecosystem, name, scope)
+ if resolved is None:
+ return None
+ _, target_nodes, _ = resolved
+
+ per_file: dict[str, tuple[str, int, set[str]]] = {}
+ if target_nodes:
+ targets = set(target_nodes)
+ for row in import_edges:
+ source = field(row, "source_path", None)
+ target = field(row, "target_node_id", None)
+ if target not in targets:
+ continue
+ if int(field(row, "community_id", 0) or 0) != community_id:
+ continue
+ if not in_scope(source, scope):
+ continue
+ language, count, matched_nodes = per_file.get(source, ("", 0, set()))
+ per_file[source] = (
+ language or (field(row, "language", "") or ""),
+ count + 1,
+ matched_nodes | {target},
+ )
+
+ ranked = sorted(per_file.items(), key=lambda entry: (-entry[1][1], entry[0]))
+ page = ranked[offset : offset + limit]
+ items = [
+ ImportingFile(
+ path=path,
+ language=language,
+ import_edge_count=count,
+ matched_external_node_count=len(matched_nodes),
+ )
+ for path, (language, count, matched_nodes) in page
+ ]
+ return ImportingFiles(
+ package_key=package_key,
+ aggregate_key=aggregate_key,
+ items=items,
+ total=len(ranked),
+ returned=len(items),
+ limit=limit,
+ offset=offset,
+ truncated=offset + len(items) < len(ranked),
+ scope=scope,
+ )
+
+
+__all__ = [
+ "DEFAULT_FILE_LIMIT",
+ "DEFAULT_RELATIONSHIP_EDGE_LIMIT",
+ "DEFAULT_RELATIONSHIP_NODE_LIMIT",
+ "EVIDENCE_TARGET_LIMIT",
+ "EXTERNAL_TARGET_LIMIT",
+ "GraphTarget",
+ "ImportingFile",
+ "ImportingFiles",
+ "RelationshipEdge",
+ "RelationshipGraph",
+ "RelationshipNode",
+ "build_importing_files",
+ "build_relationship_graph",
+ "community_key",
+ "resolve_targets",
+ "split_community_key",
+]
diff --git a/packages/core/src/repowise/core/analysis/external_systems/summary.py b/packages/core/src/repowise/core/analysis/external_systems/summary.py
new file mode 100644
index 000000000..2a1af6673
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/external_systems/summary.py
@@ -0,0 +1,310 @@
+"""Composing the bounded package page the external-dependency surface serves.
+
+Session-free by design. The fold takes declaration, link and import-edge
+records — dataclasses, dicts or ORM rows — so one implementation answers for a
+live database and for a precomputed artifact. Every bound and every honesty
+flag it reports (``limit``, ``offset``, ``truncated``, ``returned``,
+``total_packages``, ``excluded_declarations``, ``versions_truncated``) is
+decided here, because a consumer that re-derives one is a consumer that can
+disagree with the UI about what it is not showing.
+
+Composition runs at read time rather than being materialized at index time the
+way ``analysis/health/refactoring/opportunity.py`` is. That fold was measured
+at 91 ms over 2,283 plans; this one folds a few hundred packages against a few
+thousand edges, so a table and a finalizer would buy nothing and cost a
+migration. Paging is therefore done in Python, not pushed into SQL. If a
+repository ever declares packages in the tens of thousands, materialize this
+the same way refactoring did.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+from collections.abc import Iterable
+from dataclasses import dataclass
+from typing import Any
+
+from .records import Scope, field, in_scope, is_primary_path, package_key
+
+#: The page size the surface asks for when it does not say.
+DEFAULT_SUMMARY_LIMIT = 200
+#: Versions shown per package before ``versions_truncated`` starts claiming.
+SUMMARY_VERSION_LIMIT = 5
+
+
+@dataclass(frozen=True, slots=True)
+class PackageEntry:
+ """One canonical package with its declaration and graph-usage aggregates."""
+
+ package_key: str
+ name: str
+ display_name: str
+ ecosystem: str
+ category: str
+ io_kind: str | None
+ runtime_declared: bool
+ dev_declared: bool
+ declaration_count: int
+ manifest_count: int
+ versions: list[str]
+ versions_total: int
+ versions_truncated: bool
+ multiple_versions: bool
+ external_node_count: int
+ import_edge_count: int
+ importing_file_count: int
+ link_state: str
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "package_key": self.package_key,
+ "name": self.name,
+ "display_name": self.display_name,
+ "ecosystem": self.ecosystem,
+ "category": self.category,
+ "io_kind": self.io_kind,
+ "runtime_declared": self.runtime_declared,
+ "dev_declared": self.dev_declared,
+ "declaration_count": self.declaration_count,
+ "manifest_count": self.manifest_count,
+ "versions": list(self.versions),
+ "versions_total": self.versions_total,
+ "versions_truncated": self.versions_truncated,
+ "multiple_versions": self.multiple_versions,
+ "external_node_count": self.external_node_count,
+ "import_edge_count": self.import_edge_count,
+ "importing_file_count": self.importing_file_count,
+ "link_state": self.link_state,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class PackageSummary:
+ """One page of packages plus the totals that say what the page omits."""
+
+ items: list[PackageEntry]
+ returned: int
+ total_packages: int
+ limit: int
+ offset: int
+ truncated: bool
+ scope: str
+ excluded_declarations: int
+ total_declarations: int
+ runtime_packages: int
+ dev_only_packages: int
+ observed_packages: int
+ linked_packages: int
+ unlinked_packages: int
+ linked_without_imports: int
+ ecosystems: list[str]
+ manifest_count: int
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "items": [item.as_dict() for item in self.items],
+ "returned": self.returned,
+ "total_packages": self.total_packages,
+ "limit": self.limit,
+ "offset": self.offset,
+ "truncated": self.truncated,
+ "scope": self.scope,
+ "excluded_declarations": self.excluded_declarations,
+ "total_declarations": self.total_declarations,
+ "runtime_packages": self.runtime_packages,
+ "dev_only_packages": self.dev_only_packages,
+ "observed_packages": self.observed_packages,
+ "linked_packages": self.linked_packages,
+ "unlinked_packages": self.unlinked_packages,
+ "linked_without_imports": self.linked_without_imports,
+ "ecosystems": list(self.ecosystems),
+ "manifest_count": self.manifest_count,
+ }
+
+
+@dataclass(slots=True)
+class _Declared:
+ """One package's declarations, reduced as they arrive."""
+
+ ecosystem: str
+ name: str
+ display_name: str = ""
+ category: str | None = None
+ io_kind: str | None = None
+ runtime_declared: bool = False
+ dev_declared: bool = False
+ declaration_count: int = 0
+ manifests: set[str] = dataclasses.field(default_factory=set)
+ versions: set[str] = dataclasses.field(default_factory=set)
+
+
+def _least(current: str | None, candidate: str | None) -> str | None:
+ """SQL ``MIN`` over text: ignore nulls rather than let one win."""
+ if candidate is None:
+ return current
+ return candidate if current is None or candidate < current else current
+
+
+def _greatest(current: str, candidate: str | None) -> str:
+ """SQL ``MAX`` over text, where the column cannot be null."""
+ return candidate if candidate is not None and candidate > current else current
+
+
+def _declared_packages(
+ declarations: Iterable[Any], scope: Scope
+) -> tuple[dict[tuple[str, str], _Declared], int]:
+ """Group in-scope declarations by identity, counting the ones left out."""
+ groups: dict[tuple[str, str], _Declared] = {}
+ excluded = 0
+ for row in declarations:
+ declared_in = field(row, "declared_in", "") or ""
+ if not is_primary_path(declared_in):
+ excluded += 1
+ if not in_scope(declared_in, scope):
+ continue
+ ecosystem = field(row, "ecosystem", "") or ""
+ name = field(row, "name", "") or ""
+ group = groups.get((ecosystem, name))
+ if group is None:
+ group = _Declared(ecosystem=ecosystem, name=name)
+ groups[(ecosystem, name)] = group
+ group.display_name = _greatest(group.display_name, field(row, "display_name", "") or "")
+ group.category = _least(group.category, field(row, "category", None))
+ group.io_kind = _least(group.io_kind, field(row, "io_kind", None))
+ if field(row, "is_dev_dep", False):
+ group.dev_declared = True
+ else:
+ group.runtime_declared = True
+ group.declaration_count += 1
+ group.manifests.add(declared_in)
+ version = field(row, "version", None)
+ if version is not None:
+ group.versions.add(version)
+ return groups, excluded
+
+
+_Identity = tuple[str, str]
+
+
+def _usage(
+ links: Iterable[Any], import_edges: Iterable[Any], scope: Scope
+) -> tuple[dict[_Identity, set[str]], dict[_Identity, int], dict[_Identity, set[str]]]:
+ """Resolve import evidence onto package identities.
+
+ Linked nodes are counted whatever scope is asked for — a node exists or it
+ does not — while the edges that reach them are scoped by importing file,
+ which is what makes ``observed`` a claim about the repository proper.
+ """
+ nodes_by_identity: dict[tuple[str, str], set[str]] = {}
+ identity_by_node: dict[str, tuple[str, str]] = {}
+ for row in links:
+ node_id = field(row, "node_id", None)
+ if node_id is None:
+ continue
+ identity = (field(row, "ecosystem", "") or "", field(row, "name", "") or "")
+ nodes_by_identity.setdefault(identity, set()).add(node_id)
+ identity_by_node[node_id] = identity
+
+ edge_counts: dict[tuple[str, str], int] = {}
+ files_by_identity: dict[tuple[str, str], set[str]] = {}
+ for row in import_edges:
+ source = field(row, "source_path", None)
+ if not in_scope(source, scope):
+ continue
+ identity = identity_by_node.get(field(row, "target_node_id", None))
+ if identity is None:
+ continue
+ edge_counts[identity] = edge_counts.get(identity, 0) + 1
+ files_by_identity.setdefault(identity, set()).add(source)
+ return nodes_by_identity, edge_counts, files_by_identity
+
+
+def build_package_summary(
+ declarations: Iterable[Any],
+ links: Iterable[Any],
+ import_edges: Iterable[Any],
+ *,
+ scope: Scope = "primary",
+ limit: int = DEFAULT_SUMMARY_LIMIT,
+ offset: int = 0,
+) -> PackageSummary:
+ """Fold declarations and import evidence into one bounded package page.
+
+ ``declarations`` carry ``ecosystem``, ``name``, ``display_name``,
+ ``category``, ``io_kind``, ``version``, ``declared_in`` and ``is_dev_dep``.
+ ``links`` name one resolved external graph node each, as ``node_id`` plus
+ the ``ecosystem`` and ``name`` it was resolved to. ``import_edges`` carry
+ ``source_path`` and ``target_node_id``.
+ """
+ groups, excluded = _declared_packages(declarations, scope)
+ nodes_by_identity, edge_counts, files_by_identity = _usage(links, import_edges, scope)
+
+ entries: list[PackageEntry] = []
+ for identity, group in groups.items():
+ versions = sorted(group.versions)
+ shown = versions[:SUMMARY_VERSION_LIMIT]
+ node_count = len(nodes_by_identity.get(identity, ()))
+ entries.append(
+ PackageEntry(
+ package_key=package_key(group.ecosystem, group.name),
+ name=group.name,
+ display_name=group.display_name or group.name,
+ ecosystem=group.ecosystem,
+ category=group.category or "",
+ io_kind=group.io_kind,
+ runtime_declared=group.runtime_declared,
+ dev_declared=group.dev_declared,
+ declaration_count=group.declaration_count,
+ manifest_count=len(group.manifests),
+ versions=shown,
+ versions_total=len(versions),
+ versions_truncated=len(versions) > len(shown),
+ multiple_versions=len(versions) > 1,
+ external_node_count=node_count,
+ import_edge_count=edge_counts.get(identity, 0),
+ importing_file_count=len(files_by_identity.get(identity, ())),
+ link_state="linked" if node_count else "unlinked",
+ )
+ )
+
+ entries.sort(
+ key=lambda e: (
+ not e.runtime_declared,
+ -e.importing_file_count,
+ e.name.lower(),
+ e.ecosystem,
+ )
+ )
+ page = entries[offset : offset + limit]
+ linked_packages = sum(1 for e in entries if e.external_node_count)
+ return PackageSummary(
+ items=page,
+ returned=len(page),
+ total_packages=len(entries),
+ limit=limit,
+ offset=offset,
+ truncated=offset + len(page) < len(entries),
+ scope=scope,
+ # Only the primary scope is hiding anything, so only it makes the claim.
+ excluded_declarations=excluded if scope == "primary" else 0,
+ total_declarations=sum(e.declaration_count for e in entries),
+ runtime_packages=sum(1 for e in entries if e.runtime_declared),
+ dev_only_packages=sum(1 for e in entries if e.dev_declared and not e.runtime_declared),
+ observed_packages=sum(1 for e in entries if e.import_edge_count),
+ linked_packages=linked_packages,
+ unlinked_packages=len(entries) - linked_packages,
+ linked_without_imports=sum(
+ 1 for e in entries if e.external_node_count and not e.import_edge_count
+ ),
+ ecosystems=sorted({e.ecosystem for e in entries}),
+ manifest_count=len({m for group in groups.values() for m in group.manifests}),
+ )
+
+
+__all__ = [
+ "DEFAULT_SUMMARY_LIMIT",
+ "SUMMARY_VERSION_LIMIT",
+ "PackageEntry",
+ "PackageSummary",
+ "build_package_summary",
+]
diff --git a/packages/server/src/repowise/server/routers/external_systems.py b/packages/server/src/repowise/server/routers/external_systems.py
index b8dc80c00..0be2df1a7 100644
--- a/packages/server/src/repowise/server/routers/external_systems.py
+++ b/packages/server/src/repowise/server/routers/external_systems.py
@@ -14,10 +14,10 @@ from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.external_systems import build_registry
from repowise.core.persistence.models import ExternalSystem
from repowise.server.deps import get_db_session, verify_api_key
from repowise.server.schemas.external_systems import (
- ExternalSystemEntry,
ExternalSystemImportingFilesResponse,
ExternalSystemRelationshipGraphResponse,
ExternalSystemsResponse,
@@ -146,30 +146,4 @@ async def list_external_systems(
.scalars()
.all()
)
- category_order = {"framework": 0, "service": 1, "tool": 2, "library": 3}
- items = sorted(
- (
- ExternalSystemEntry(
- name=r.name,
- display_name=r.display_name or r.name,
- ecosystem=r.ecosystem,
- category=r.category,
- io_kind=r.io_kind,
- version=r.version,
- declared_in=r.declared_in,
- is_dev_dep=bool(r.is_dev_dep),
- )
- for r in rows
- ),
- key=lambda e: (category_order.get(e.category, 9), e.name.lower(), e.declared_in),
- )
- ecosystems = sorted({e.ecosystem for e in items})
- manifests = sorted({e.declared_in for e in items})
- return ExternalSystemsResponse(
- items=items,
- total=len(items),
- prod_count=sum(1 for e in items if not e.is_dev_dep),
- dev_count=sum(1 for e in items if e.is_dev_dep),
- ecosystems=ecosystems,
- manifests=manifests,
- )
+ return ExternalSystemsResponse.model_validate(build_registry(rows).as_dict())
diff --git a/packages/server/src/repowise/server/services/external_system_relationships.py b/packages/server/src/repowise/server/services/external_system_relationships.py
index 1c5cdca01..704f19b49 100644
--- a/packages/server/src/repowise/server/services/external_system_relationships.py
+++ b/packages/server/src/repowise/server/services/external_system_relationships.py
@@ -1,134 +1,117 @@
-"""Bounded, aggregate-first reads for one external package's relationships."""
+"""Fetching the rows one package's relationship reads are folded from.
-from __future__ import annotations
+Nothing here aggregates. Composition, the caps and the flags that confess them
+live in ``repowise.core.analysis.external_systems.relationships``, session-free
+so a second consumer folds the same records rather than reimplementing the
+bounds.
+
+Both reads resolve the package's target nodes first and fetch only the edges
+that reach them, so the query stays proportional to one package rather than to
+the repository.
+"""
-import json
-from typing import Literal
+from __future__ import annotations
-from sqlalchemy import and_, case, distinct, func, literal, not_, or_, select
+from sqlalchemy import and_, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import aliased
+from repowise.core.analysis.external_systems import (
+ DEFAULT_FILE_LIMIT,
+ DEFAULT_RELATIONSHIP_EDGE_LIMIT,
+ DEFAULT_RELATIONSHIP_NODE_LIMIT,
+ EVIDENCE_TARGET_LIMIT,
+ Scope,
+ build_importing_files,
+ build_relationship_graph,
+ resolve_targets,
+ split_community_key,
+ split_package_key,
+)
from repowise.core.persistence.models import ExternalSystem, GraphEdge, GraphNode
from repowise.server.schemas.external_systems import (
- ExternalSystemGraphTarget,
- ExternalSystemImportingFile,
ExternalSystemImportingFilesResponse,
- ExternalSystemRelationshipEdge,
ExternalSystemRelationshipGraphResponse,
- ExternalSystemRelationshipNode,
)
-RelationshipScope = Literal["primary", "all"]
-DEFAULT_RELATIONSHIP_NODE_LIMIT = 50
+RelationshipScope = Scope
+#: Ceilings on what a caller may ask for. HTTP validation, so they stay with
+#: the route; the defaults the folds apply are the folds' own.
MAX_RELATIONSHIP_NODE_LIMIT = 50
-DEFAULT_RELATIONSHIP_EDGE_LIMIT = 200
MAX_RELATIONSHIP_EDGE_LIMIT = 200
-DEFAULT_FILE_LIMIT = 25
MAX_FILE_LIMIT = 100
-EXTERNAL_TARGET_LIMIT = 20
-EVIDENCE_TARGET_LIMIT = 200
-_AUXILIARY_PREFIXES = (".claude/worktrees/", "local-stash/")
-
-
-def _primary_path(path_column):
- return not_(or_(*(path_column.like(f"{prefix}%") for prefix in _AUXILIARY_PREFIXES)))
-
-
-def _source_scope(scope: RelationshipScope):
- return literal(True) if scope == "all" else _primary_path(GraphEdge.source_node_id)
-
-def _declaration_scope(scope: RelationshipScope):
- return literal(True) if scope == "all" else _primary_path(ExternalSystem.declared_in)
-
-
-def _identity(package_key: str) -> tuple[str, str]:
- ecosystem, separator, name = package_key.partition(":")
- if not separator or not ecosystem or not name:
- raise ValueError("package_key must contain an ecosystem and package name")
- return ecosystem, name
-
-
-def _target_basis(node_id: str, package_name: str) -> Literal["exact", "subpath", "mapped"]:
- value = node_id.casefold()
- expected = f"external:{package_name}".casefold()
- if value == expected:
- return "exact"
- if value.startswith(f"{expected}/") or value.startswith(f"{expected}:"):
- return "subpath"
- return "mapped"
-
-
-def _community_label(meta_json: str | None, community_id: int, top_file: str | None) -> str:
- try:
- label = json.loads(meta_json or "{}").get("label")
- except (json.JSONDecodeError, TypeError, AttributeError):
- label = None
- if isinstance(label, str) and label.strip():
- return label.strip()
- if top_file:
- parts = top_file.replace("\\", "/").split("/")
- return "/".join(parts[:2]) if len(parts) > 1 else parts[0]
- return f"Community {community_id}"
-
-
-async def _selected_package_targets(
- session: AsyncSession,
- repository_id: str,
- ecosystem: str,
- package_name: str,
- scope: RelationshipScope,
-) -> tuple[str, list[str], int] | None:
- """Resolve the same scoped, capped target universe for graph and expansion reads."""
- declared = (
- select(
- ExternalSystem.ecosystem.label("ecosystem"),
- ExternalSystem.name.label("name"),
- )
- .where(
- ExternalSystem.repository_id == repository_id,
- ExternalSystem.ecosystem == ecosystem,
- ExternalSystem.name == package_name,
- _declaration_scope(scope),
- )
- .group_by(ExternalSystem.ecosystem, ExternalSystem.name)
- .subquery("selected_package")
- )
- targets = (
- select(
- declared.c.name,
- GraphNode.node_id,
- func.sum(case((GraphNode.node_id.is_not(None), 1), else_=0))
- .over()
- .label("target_total"),
- )
- .select_from(declared)
- .outerjoin(
- ExternalSystem,
- and_(
+__all__ = [
+ "DEFAULT_FILE_LIMIT",
+ "DEFAULT_RELATIONSHIP_EDGE_LIMIT",
+ "DEFAULT_RELATIONSHIP_NODE_LIMIT",
+ "EVIDENCE_TARGET_LIMIT",
+ "MAX_FILE_LIMIT",
+ "MAX_RELATIONSHIP_EDGE_LIMIT",
+ "MAX_RELATIONSHIP_NODE_LIMIT",
+ "RelationshipScope",
+ "build_external_system_importing_files",
+ "build_external_system_relationship_graph",
+]
+
+
+async def _package_records(
+ session: AsyncSession, repository_id: str, ecosystem: str, name: str
+) -> tuple[list, list]:
+ """The one package's declarations and the external nodes it resolved to."""
+ declarations = (
+ await session.execute(
+ select(ExternalSystem.ecosystem, ExternalSystem.name, ExternalSystem.declared_in).where(
ExternalSystem.repository_id == repository_id,
- ExternalSystem.ecosystem == declared.c.ecosystem,
- ExternalSystem.name == declared.c.name,
- ),
+ ExternalSystem.ecosystem == ecosystem,
+ ExternalSystem.name == name,
+ )
)
- .outerjoin(
- GraphNode,
- and_(
+ ).all()
+ links = (
+ await session.execute(
+ select(GraphNode.node_id, ExternalSystem.ecosystem, ExternalSystem.name)
+ .join(ExternalSystem, ExternalSystem.id == GraphNode.external_system_id)
+ .where(
GraphNode.repository_id == repository_id,
- GraphNode.external_system_id == ExternalSystem.id,
- ),
+ ExternalSystem.repository_id == repository_id,
+ ExternalSystem.ecosystem == ecosystem,
+ ExternalSystem.name == name,
+ )
)
- .group_by(declared.c.name, GraphNode.node_id)
- .order_by(GraphNode.node_id)
- .limit(EVIDENCE_TARGET_LIMIT + 1)
- )
- rows = (await session.execute(targets)).all()
- if not rows:
- return None
- target_total = int(rows[0].target_total or 0)
- target_nodes = [row.node_id for row in rows if row.node_id is not None][:EVIDENCE_TARGET_LIMIT]
- return rows[0].name, target_nodes, target_total
+ ).all()
+ return declarations, links
+
+
+async def _import_edges(session: AsyncSession, repository_id: str, target_nodes: list[str]) -> list:
+ """File-sourced import edges reaching the package, with their communities."""
+ if not target_nodes:
+ return []
+ source_node = aliased(GraphNode, name="source_node")
+ return (
+ await session.execute(
+ select(
+ GraphEdge.source_node_id.label("source_path"),
+ GraphEdge.target_node_id,
+ source_node.community_id,
+ source_node.community_meta_json,
+ source_node.language,
+ )
+ .join(
+ source_node,
+ and_(
+ source_node.repository_id == repository_id,
+ source_node.node_id == GraphEdge.source_node_id,
+ source_node.node_type == "file",
+ ),
+ )
+ .where(
+ GraphEdge.repository_id == repository_id,
+ GraphEdge.edge_type == "imports",
+ GraphEdge.target_node_id.in_(target_nodes),
+ )
+ )
+ ).all()
async def build_external_system_relationship_graph(
@@ -140,135 +123,25 @@ async def build_external_system_relationship_graph(
node_limit: int = DEFAULT_RELATIONSHIP_NODE_LIMIT,
edge_limit: int = DEFAULT_RELATIONSHIP_EDGE_LIMIT,
) -> ExternalSystemRelationshipGraphResponse | None:
- """Return one package plus bounded first-party community aggregates in two queries."""
- ecosystem, package_name = _identity(package_key)
- selected_targets = await _selected_package_targets(
- session, repository_id, ecosystem, package_name, scope
- )
- if selected_targets is None:
+ """Serve one package's bounded community graph, or ``None`` if undeclared."""
+ ecosystem, name = split_package_key(package_key)
+ declarations, links = await _package_records(session, repository_id, ecosystem, name)
+ resolved = resolve_targets(declarations, links, ecosystem, name, scope)
+ if resolved is None:
return None
- package_name, target_nodes, target_total = selected_targets
- matched_targets = [
- ExternalSystemGraphTarget(
- node_id=node_id,
- match_basis=_target_basis(node_id, package_name),
- )
- for node_id in target_nodes[:EXTERNAL_TARGET_LIMIT]
- ]
-
- bases = {_target_basis(node_id, package_name) for node_id in target_nodes}
- match_basis = "unresolved" if not bases else next(iter(bases)) if len(bases) == 1 else "mixed"
- evidence_truncated = target_total > len(target_nodes)
- package_node_id = f"package:{package_key}"
- if not target_nodes:
- return ExternalSystemRelationshipGraphResponse(
- package_key=package_key,
- package_name=package_name,
- package_node_id=package_node_id,
- match_basis=match_basis,
- matched_external_nodes=matched_targets,
- matched_external_nodes_total=target_total,
- matched_external_nodes_truncated=target_total > len(matched_targets),
- evidence_target_limit=EVIDENCE_TARGET_LIMIT,
- evidence_truncated=evidence_truncated,
- nodes=[],
- edges=[],
- aggregate_total=0,
- aggregate_returned=0,
- edge_total=0,
- edge_returned=0,
- importing_file_total=0,
- import_edge_total=0,
- node_limit=node_limit,
- edge_limit=edge_limit,
- truncated=evidence_truncated,
- scope=scope,
- )
-
- source_node = aliased(GraphNode, name="source_node")
- grouped = (
- select(
- source_node.community_id.label("community_id"),
- func.count(GraphEdge.id).label("import_edge_count"),
- func.count(distinct(GraphEdge.source_node_id)).label("importing_file_count"),
- func.min(GraphEdge.source_node_id).label("top_file"),
- func.max(source_node.community_meta_json).label("community_meta_json"),
- )
- .select_from(GraphEdge)
- .join(
- source_node,
- and_(
- source_node.repository_id == repository_id,
- source_node.node_id == GraphEdge.source_node_id,
- source_node.node_type == "file",
- ),
- )
- .where(
- GraphEdge.repository_id == repository_id,
- GraphEdge.edge_type == "imports",
- GraphEdge.target_node_id.in_(target_nodes),
- _source_scope(scope),
- )
- .group_by(source_node.community_id)
- .subquery("package_relationship_groups")
- )
- aggregates = select(
- grouped,
- func.count().over().label("aggregate_total"),
- func.sum(grouped.c.import_edge_count).over().label("import_edge_total"),
- func.sum(grouped.c.importing_file_count).over().label("importing_file_total"),
- ).order_by(
- grouped.c.importing_file_count.desc(),
- grouped.c.import_edge_count.desc(),
- grouped.c.community_id,
- )
- aggregate_rows = (await session.execute(aggregates.limit(node_limit + 1))).all()
- returned_rows = aggregate_rows[: min(node_limit, edge_limit)]
- nodes = [
- ExternalSystemRelationshipNode(
- aggregate_key=f"community:{row.community_id}",
- label=_community_label(row.community_meta_json, row.community_id, row.top_file),
- community_id=int(row.community_id),
- importing_file_count=int(row.importing_file_count),
- import_edge_count=int(row.import_edge_count),
- top_file=row.top_file,
- )
- for row in returned_rows
- ]
- edges = [
- ExternalSystemRelationshipEdge(
- source=node.aggregate_key,
- target=package_node_id,
- import_edge_count=node.import_edge_count,
- )
- for node in nodes
- ]
- aggregate_total = int(aggregate_rows[0].aggregate_total or 0) if aggregate_rows else 0
- import_edge_total = int(aggregate_rows[0].import_edge_total or 0) if aggregate_rows else 0
- importing_file_total = int(aggregate_rows[0].importing_file_total or 0) if aggregate_rows else 0
- return ExternalSystemRelationshipGraphResponse(
- package_key=package_key,
- package_name=package_name,
- package_node_id=package_node_id,
- match_basis=match_basis,
- matched_external_nodes=matched_targets,
- matched_external_nodes_total=target_total,
- matched_external_nodes_truncated=target_total > len(matched_targets),
- evidence_target_limit=EVIDENCE_TARGET_LIMIT,
- evidence_truncated=evidence_truncated,
- nodes=nodes,
- edges=edges,
- aggregate_total=aggregate_total,
- aggregate_returned=len(nodes),
- edge_total=aggregate_total,
- edge_returned=len(edges),
- importing_file_total=importing_file_total,
- import_edge_total=import_edge_total,
+ import_edges = await _import_edges(session, repository_id, resolved[1])
+ graph = build_relationship_graph(
+ declarations,
+ links,
+ import_edges,
+ package_key,
+ scope=scope,
node_limit=node_limit,
edge_limit=edge_limit,
- truncated=aggregate_total > len(nodes) or evidence_truncated,
- scope=scope,
)
+ if graph is None:
+ return None
+ return ExternalSystemRelationshipGraphResponse.model_validate(graph.as_dict())
async def build_external_system_importing_files(
@@ -281,90 +154,28 @@ async def build_external_system_importing_files(
limit: int = DEFAULT_FILE_LIMIT,
offset: int = 0,
) -> ExternalSystemImportingFilesResponse | None:
- """Return one bounded file page for a selected relationship aggregate."""
- ecosystem, package_name = _identity(package_key)
- prefix, separator, community_value = aggregate_key.partition(":")
- if prefix != "community" or not separator:
- raise ValueError("aggregate_key must identify a graph community")
- try:
- community_id = int(community_value)
- except ValueError as exc:
- raise ValueError("aggregate_key must identify a graph community") from exc
-
- selected_targets = await _selected_package_targets(
- session, repository_id, ecosystem, package_name, scope
- )
- if selected_targets is None:
+ """Serve one bounded file page for a selected aggregate, or ``None``.
+
+ Both keys are checked before any read, so a malformed one is rejected
+ rather than answered as a missing package.
+ """
+ ecosystem, name = split_package_key(package_key)
+ split_community_key(aggregate_key)
+ declarations, links = await _package_records(session, repository_id, ecosystem, name)
+ resolved = resolve_targets(declarations, links, ecosystem, name, scope)
+ if resolved is None:
return None
- _, target_nodes, _ = selected_targets
- if not target_nodes:
- return ExternalSystemImportingFilesResponse(
- package_key=package_key,
- aggregate_key=aggregate_key,
- items=[],
- total=0,
- returned=0,
- limit=limit,
- offset=offset,
- truncated=False,
- scope=scope,
- )
-
- source_node = aliased(GraphNode, name="source_node")
- grouped = (
- select(
- GraphEdge.source_node_id.label("path"),
- source_node.language.label("language"),
- func.count(GraphEdge.id).label("import_edge_count"),
- func.count(distinct(GraphEdge.target_node_id)).label("matched_external_node_count"),
- )
- .select_from(GraphEdge)
- .join(
- source_node,
- and_(
- source_node.repository_id == repository_id,
- source_node.node_id == GraphEdge.source_node_id,
- source_node.node_type == "file",
- ),
- )
- .where(
- GraphEdge.repository_id == repository_id,
- GraphEdge.edge_type == "imports",
- GraphEdge.target_node_id.in_(target_nodes),
- source_node.community_id == community_id,
- _source_scope(scope),
- )
- .group_by(GraphEdge.source_node_id, source_node.language)
- .subquery("aggregate_importing_files")
- )
- rows = (
- await session.execute(
- select(grouped, func.count().over().label("total"))
- .order_by(grouped.c.import_edge_count.desc(), grouped.c.path)
- .limit(limit)
- .offset(offset)
- )
- ).all()
- total = int(rows[0].total or 0) if rows else 0
- if not rows and offset:
- total = int((await session.execute(select(func.count()).select_from(grouped))).scalar_one())
- items = [
- ExternalSystemImportingFile(
- path=row.path,
- language=row.language,
- import_edge_count=int(row.import_edge_count),
- matched_external_node_count=int(row.matched_external_node_count),
- )
- for row in rows
- ]
- return ExternalSystemImportingFilesResponse(
- package_key=package_key,
- aggregate_key=aggregate_key,
- items=items,
- total=total,
- returned=len(items),
+ import_edges = await _import_edges(session, repository_id, resolved[1])
+ page = build_importing_files(
+ declarations,
+ links,
+ import_edges,
+ package_key,
+ aggregate_key,
+ scope=scope,
limit=limit,
offset=offset,
- truncated=offset + len(items) < total,
- scope=scope,
)
+ if page is None:
+ return None
+ return ExternalSystemImportingFilesResponse.model_validate(page.as_dict())
diff --git a/packages/server/src/repowise/server/services/external_systems.py b/packages/server/src/repowise/server/services/external_systems.py
index a03aea046..721e960f1 100644
--- a/packages/server/src/repowise/server/services/external_systems.py
+++ b/packages/server/src/repowise/server/services/external_systems.py
@@ -1,146 +1,88 @@
-"""Bounded read models for declared packages and persisted graph usage."""
+"""Fetching the rows the external-dependency summary is folded from.
-from __future__ import annotations
+Nothing here groups, ranks, pages or truncates. Composition is
+``repowise.core.analysis.external_systems.summary`` and it is session-free, so
+an indexer or a deployment without these tables folds the same records through
+the same code and cannot disagree with this surface about what a page omits.
+
+The queries narrow — they select only the columns the fold reads, and join
+import edges to resolved external nodes so the fold is handed evidence rather
+than the repository's whole import graph.
+"""
-from collections import defaultdict
-from typing import Literal
+from __future__ import annotations
-from sqlalchemy import and_, case, distinct, func, literal, not_, or_, select
+from sqlalchemy import and_, select
from sqlalchemy.ext.asyncio import AsyncSession
-from repowise.core.persistence.models import ExternalSystem, GraphEdge, GraphNode
-from repowise.server.schemas.external_systems import (
- ExternalSystemsSummaryResponse,
- ExternalSystemSummaryEntry,
+from repowise.core.analysis.external_systems import (
+ DEFAULT_SUMMARY_LIMIT,
+ Scope,
+ build_package_summary,
)
+from repowise.core.persistence.models import ExternalSystem, GraphEdge, GraphNode
+from repowise.server.schemas.external_systems import ExternalSystemsSummaryResponse
-SummaryScope = Literal["primary", "all"]
-DEFAULT_SUMMARY_LIMIT = 200
+SummaryScope = Scope
+#: Bound on what a caller may ask for. A page-size ceiling is HTTP validation,
+#: so it stays with the route; the default the fold applies is the fold's own.
MAX_SUMMARY_LIMIT = 400
-SUMMARY_VERSION_LIMIT = 5
-PRIMARY_AUXILIARY_PREFIXES = (".claude/worktrees/", "local-stash/")
-
-def _primary_path_predicate(path_column):
- return not_(or_(*(path_column.like(f"{prefix}%") for prefix in PRIMARY_AUXILIARY_PREFIXES)))
-
-
-def _scope_predicate(scope: SummaryScope):
- if scope == "all":
- return literal(True)
- return _primary_path_predicate(ExternalSystem.declared_in)
-
-
-def _package_query(repository_id: str, scope: SummaryScope):
- runtime = func.max(case((ExternalSystem.is_dev_dep.is_(False), 1), else_=0))
- dev = func.max(case((ExternalSystem.is_dev_dep.is_(True), 1), else_=0))
+__all__ = [
+ "DEFAULT_SUMMARY_LIMIT",
+ "MAX_SUMMARY_LIMIT",
+ "SummaryScope",
+ "build_external_systems_summary",
+]
+
+
+def _declaration_query(repository_id: str):
+ return select(
+ ExternalSystem.ecosystem,
+ ExternalSystem.name,
+ ExternalSystem.display_name,
+ ExternalSystem.category,
+ ExternalSystem.io_kind,
+ ExternalSystem.version,
+ ExternalSystem.declared_in,
+ ExternalSystem.is_dev_dep,
+ ).where(ExternalSystem.repository_id == repository_id)
+
+
+def _link_query(repository_id: str):
+ """Every external graph node, named by the package it was resolved to."""
return (
- select(
- ExternalSystem.ecosystem.label("ecosystem"),
- ExternalSystem.name.label("name"),
- func.max(ExternalSystem.display_name).label("display_name"),
- func.min(ExternalSystem.category).label("category"),
- func.min(ExternalSystem.io_kind).label("io_kind"),
- runtime.label("runtime_declared"),
- dev.label("dev_declared"),
- func.count(ExternalSystem.id).label("declaration_count"),
- func.count(distinct(ExternalSystem.declared_in)).label("manifest_count"),
- )
+ select(GraphNode.node_id, ExternalSystem.ecosystem, ExternalSystem.name)
+ .join(ExternalSystem, ExternalSystem.id == GraphNode.external_system_id)
.where(
- ExternalSystem.repository_id == repository_id,
- _scope_predicate(scope),
+ GraphNode.repository_id == repository_id,
+ GraphNode.external_system_id.is_not(None),
)
- .group_by(ExternalSystem.ecosystem, ExternalSystem.name)
- .subquery("declared_packages")
)
-def _usage_query(repository_id: str, scope: SummaryScope):
- edge_scope = (
- literal(True) if scope == "all" else _primary_path_predicate(GraphEdge.source_node_id)
- )
+def _import_edge_query(repository_id: str):
+ """Import edges that reach a resolved external node, and nothing else."""
return (
select(
- ExternalSystem.ecosystem.label("ecosystem"),
- ExternalSystem.name.label("name"),
- func.count(distinct(GraphNode.node_id)).label("external_node_count"),
- func.count(GraphEdge.id).label("import_edge_count"),
- func.count(distinct(GraphEdge.source_node_id)).label("importing_file_count"),
+ GraphEdge.source_node_id.label("source_path"),
+ GraphEdge.target_node_id,
)
- .select_from(GraphNode)
- .join(ExternalSystem, ExternalSystem.id == GraphNode.external_system_id)
- .outerjoin(
- GraphEdge,
+ .join(
+ GraphNode,
and_(
- GraphEdge.repository_id == repository_id,
- GraphEdge.target_node_id == GraphNode.node_id,
- GraphEdge.edge_type == "imports",
- edge_scope,
+ GraphNode.repository_id == repository_id,
+ GraphNode.node_id == GraphEdge.target_node_id,
+ GraphNode.external_system_id.is_not(None),
),
)
.where(
- GraphNode.repository_id == repository_id,
- GraphNode.external_system_id.is_not(None),
+ GraphEdge.repository_id == repository_id,
+ GraphEdge.edge_type == "imports",
)
- .group_by(ExternalSystem.ecosystem, ExternalSystem.name)
- .subquery("package_usage")
)
-async def _versions_for_page(
- session: AsyncSession,
- repository_id: str,
- scope: SummaryScope,
- identities: list[tuple[str, str]],
-) -> dict[tuple[str, str], tuple[list[str], int]]:
- """Fetch at most ``SUMMARY_VERSION_LIMIT`` values for each page item."""
- if not identities:
- return {}
- identity_filter = or_(
- *(
- and_(ExternalSystem.ecosystem == ecosystem, ExternalSystem.name == name)
- for ecosystem, name in identities
- )
- )
- distinct_versions = (
- select(
- ExternalSystem.ecosystem.label("ecosystem"),
- ExternalSystem.name.label("name"),
- ExternalSystem.version.label("version"),
- )
- .where(
- ExternalSystem.repository_id == repository_id,
- _scope_predicate(scope),
- ExternalSystem.version.is_not(None),
- identity_filter,
- )
- .group_by(ExternalSystem.ecosystem, ExternalSystem.name, ExternalSystem.version)
- .subquery("distinct_versions")
- )
- ranked = select(
- distinct_versions,
- func.row_number()
- .over(
- partition_by=(distinct_versions.c.ecosystem, distinct_versions.c.name),
- order_by=distinct_versions.c.version,
- )
- .label("version_rank"),
- func.count()
- .over(partition_by=(distinct_versions.c.ecosystem, distinct_versions.c.name))
- .label("versions_total"),
- ).subquery("ranked_versions")
- rows = (
- await session.execute(select(ranked).where(ranked.c.version_rank <= SUMMARY_VERSION_LIMIT))
- ).all()
- values: dict[tuple[str, str], list[str]] = defaultdict(list)
- totals: dict[tuple[str, str], int] = {}
- for row in rows:
- key = (row.ecosystem, row.name)
- values[key].append(row.version)
- totals[key] = int(row.versions_total)
- return {key: (versions, totals[key]) for key, versions in values.items()}
-
-
async def build_external_systems_summary(
session: AsyncSession,
repository_id: str,
@@ -149,149 +91,16 @@ async def build_external_systems_summary(
limit: int = DEFAULT_SUMMARY_LIMIT,
offset: int = 0,
) -> ExternalSystemsSummaryResponse:
- """Return a bounded package page in constant SQL statements, independent of N."""
- packages = _package_query(repository_id, scope)
- usage = _usage_query(repository_id, scope)
- node_count = func.coalesce(usage.c.external_node_count, 0)
- edge_count = func.coalesce(usage.c.import_edge_count, 0)
- file_count = func.coalesce(usage.c.importing_file_count, 0)
- joined = packages.outerjoin(
- usage,
- and_(
- usage.c.ecosystem == packages.c.ecosystem,
- usage.c.name == packages.c.name,
- ),
- )
- summaries = select(
- packages,
- node_count.label("external_node_count"),
- edge_count.label("import_edge_count"),
- file_count.label("importing_file_count"),
- func.count().over().label("total_packages"),
- func.sum(packages.c.declaration_count).over().label("total_declarations"),
- func.sum(packages.c.runtime_declared).over().label("runtime_packages"),
- func.sum(
- case(
- (
- and_(
- packages.c.dev_declared == 1,
- packages.c.runtime_declared == 0,
- ),
- 1,
- ),
- else_=0,
- )
- )
- .over()
- .label("dev_only_packages"),
- func.sum(case((edge_count > 0, 1), else_=0)).over().label("observed_packages"),
- func.sum(case((node_count > 0, 1), else_=0)).over().label("linked_packages"),
- func.sum(case((and_(node_count > 0, edge_count == 0), 1), else_=0))
- .over()
- .label("linked_without_imports"),
- ).select_from(joined)
- ordered_summaries = summaries.order_by(
- packages.c.runtime_declared.desc(),
- file_count.desc(),
- func.lower(packages.c.name),
- packages.c.ecosystem,
- )
- page_rows = (await session.execute(ordered_summaries.limit(limit).offset(offset))).all()
- manifest_count = (
- select(func.count(distinct(ExternalSystem.declared_in)))
- .where(
- ExternalSystem.repository_id == repository_id,
- _scope_predicate(scope),
- )
- .scalar_subquery()
- )
- excluded_declarations = (
- select(func.count(ExternalSystem.id))
- .where(
- ExternalSystem.repository_id == repository_id,
- ~_scope_predicate("primary"),
- )
- .scalar_subquery()
- )
- metadata_rows = (
- await session.execute(
- select(
- ExternalSystem.ecosystem,
- manifest_count.label("manifest_count"),
- excluded_declarations.label("excluded_declarations"),
- )
- .where(
- ExternalSystem.repository_id == repository_id,
- _scope_predicate(scope),
- )
- .group_by(ExternalSystem.ecosystem)
- )
- ).all()
- excluded = 0
- if scope == "primary" and metadata_rows:
- excluded = int(metadata_rows[0].excluded_declarations or 0)
- elif scope == "primary":
- # Grouped totals have no row when every declaration is auxiliary.
- excluded = int(
- (
- await session.execute(
- select(func.count(ExternalSystem.id)).where(
- ExternalSystem.repository_id == repository_id,
- ~_scope_predicate("primary"),
- )
- )
- ).scalar_one()
- )
- totals_row = page_rows[0] if page_rows else None
- if totals_row is None and offset:
- totals_row = (await session.execute(ordered_summaries.limit(1))).first()
- identities = [(row.ecosystem, row.name) for row in page_rows]
- versions = await _versions_for_page(session, repository_id, scope, identities)
- items: list[ExternalSystemSummaryEntry] = []
- for row in page_rows:
- package_versions, versions_total = versions.get((row.ecosystem, row.name), ([], 0))
- resolved_nodes = int(row.external_node_count or 0)
- items.append(
- ExternalSystemSummaryEntry(
- package_key=f"{row.ecosystem}:{row.name}",
- name=row.name,
- display_name=row.display_name or row.name,
- ecosystem=row.ecosystem,
- category=row.category,
- io_kind=row.io_kind,
- runtime_declared=bool(row.runtime_declared),
- dev_declared=bool(row.dev_declared),
- declaration_count=int(row.declaration_count),
- manifest_count=int(row.manifest_count),
- versions=package_versions,
- versions_total=versions_total,
- versions_truncated=versions_total > len(package_versions),
- multiple_versions=versions_total > 1,
- external_node_count=resolved_nodes,
- import_edge_count=int(row.import_edge_count or 0),
- importing_file_count=int(row.importing_file_count or 0),
- link_state="linked" if resolved_nodes else "unlinked",
- )
- )
- total_packages = int(totals_row.total_packages or 0) if totals_row else 0
- linked_packages = int(totals_row.linked_packages or 0) if totals_row else 0
- first_metadata = metadata_rows[0] if metadata_rows else None
- return ExternalSystemsSummaryResponse(
- items=items,
- returned=len(items),
- total_packages=total_packages,
+ """Serve one bounded package page from three narrowing reads."""
+ declarations = (await session.execute(_declaration_query(repository_id))).all()
+ links = (await session.execute(_link_query(repository_id))).all()
+ import_edges = (await session.execute(_import_edge_query(repository_id))).all()
+ summary = build_package_summary(
+ declarations,
+ links,
+ import_edges,
+ scope=scope,
limit=limit,
offset=offset,
- truncated=offset + len(items) < total_packages,
- scope=scope,
- excluded_declarations=excluded,
- total_declarations=int(totals_row.total_declarations or 0) if totals_row else 0,
- runtime_packages=int(totals_row.runtime_packages or 0) if totals_row else 0,
- dev_only_packages=int(totals_row.dev_only_packages or 0) if totals_row else 0,
- observed_packages=int(totals_row.observed_packages or 0) if totals_row else 0,
- linked_packages=linked_packages,
- unlinked_packages=total_packages - linked_packages,
- linked_without_imports=(int(totals_row.linked_without_imports or 0) if totals_row else 0),
- ecosystems=sorted(row.ecosystem for row in metadata_rows),
- manifest_count=(int(first_metadata.manifest_count or 0) if first_metadata else 0),
)
+ return ExternalSystemsSummaryResponse.model_validate(summary.as_dict())
diff --git a/tests/unit/analysis/test_external_systems_relationships.py b/tests/unit/analysis/test_external_systems_relationships.py
new file mode 100644
index 000000000..9e28b06c9
--- /dev/null
+++ b/tests/unit/analysis/test_external_systems_relationships.py
@@ -0,0 +1,348 @@
+"""One package's relationship folds: target evidence, community aggregates, file pages."""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+
+import pytest
+
+from repowise.core.analysis.external_systems import (
+ DEFAULT_FILE_LIMIT,
+ EVIDENCE_TARGET_LIMIT,
+ EXTERNAL_TARGET_LIMIT,
+ build_importing_files,
+ build_relationship_graph,
+ resolve_targets,
+ split_community_key,
+ split_package_key,
+)
+
+
+@dataclass
+class _Declaration:
+ ecosystem: str = "npm"
+ name: str = "react"
+ declared_in: str = "package.json"
+
+
+@dataclass
+class _Link:
+ node_id: str
+ ecosystem: str = "npm"
+ name: str = "react"
+
+
+@dataclass
+class _Edge:
+ """Stub of an import edge joined to its importing file's community."""
+
+ source_path: str
+ target_node_id: str = "external:react"
+ community_id: int = 1
+ community_meta_json: str | None = "{}"
+ language: str = "ts"
+
+
+DECLARED = [_Declaration()]
+LINKED = [_Link(node_id="external:react")]
+
+
+def test_undeclared_package_resolves_to_nothing() -> None:
+ assert build_relationship_graph(DECLARED, LINKED, [], "npm:missing") is None
+ assert build_importing_files(DECLARED, LINKED, [], "npm:missing", "community:1") is None
+ assert resolve_targets(DECLARED, LINKED, "npm", "missing", "primary") is None
+
+
+def test_a_package_declared_only_out_of_scope_is_not_found() -> None:
+ declared = [_Declaration(declared_in="local-stash/package.json")]
+
+ assert build_relationship_graph(declared, LINKED, [], "npm:react") is None
+ assert build_relationship_graph(declared, LINKED, [], "npm:react", scope="all") is not None
+
+
+def test_declared_but_unlinked_package_is_an_answerable_empty_graph() -> None:
+ graph = build_relationship_graph(DECLARED, [], [], "npm:react")
+
+ assert graph is not None
+ assert graph.match_basis == "unresolved"
+ assert graph.nodes == []
+ assert graph.edges == []
+ assert graph.matched_external_nodes_total == 0
+ assert graph.evidence_truncated is False
+ assert graph.truncated is False
+ assert graph.package_node_id == "package:npm:react"
+
+
+def test_match_basis_names_how_the_target_was_reached() -> None:
+ def basis(*node_ids: str) -> str:
+ links = [_Link(node_id=node_id) for node_id in node_ids]
+ graph = build_relationship_graph(DECLARED, links, [], "npm:react")
+ assert graph is not None
+ return graph.match_basis
+
+ assert basis("external:react") == "exact"
+ assert basis("external:react/jsx-runtime") == "subpath"
+ assert basis("external:react:server") == "subpath"
+ assert basis("external:preact-compat") == "mapped"
+ assert basis("external:react", "external:preact-compat") == "mixed"
+
+
+def test_target_evidence_is_capped_and_says_so() -> None:
+ links = [
+ _Link(node_id=f"external:react/m{index:04d}") for index in range(EVIDENCE_TARGET_LIMIT + 7)
+ ]
+
+ graph = build_relationship_graph(DECLARED, links, [], "npm:react")
+
+ assert graph is not None
+ assert graph.matched_external_nodes_total == EVIDENCE_TARGET_LIMIT + 7
+ assert len(graph.matched_external_nodes) == EXTERNAL_TARGET_LIMIT
+ assert graph.matched_external_nodes_truncated is True
+ assert graph.evidence_target_limit == EVIDENCE_TARGET_LIMIT
+ assert graph.evidence_truncated is True
+ # Truncated evidence makes the whole graph a partial answer.
+ assert graph.truncated is True
+
+
+def test_communities_are_ranked_by_importers_then_edges() -> None:
+ edges = [
+ _Edge("src/a.ts", community_id=7),
+ _Edge("src/b.ts", community_id=7),
+ _Edge("src/c.ts", community_id=3),
+ _Edge("src/c.ts", community_id=3),
+ _Edge("src/c.ts", community_id=3),
+ _Edge("src/d.ts", community_id=9),
+ ]
+
+ graph = build_relationship_graph(DECLARED, LINKED, edges, "npm:react")
+
+ assert graph is not None
+ assert [n.aggregate_key for n in graph.nodes] == ["community:7", "community:3", "community:9"]
+ assert [n.importing_file_count for n in graph.nodes] == [2, 1, 1]
+ assert [n.import_edge_count for n in graph.nodes] == [2, 3, 1]
+ assert graph.aggregate_total == 3
+ assert graph.import_edge_total == 6
+ assert graph.importing_file_total == 4
+ # Every community carries exactly one edge to the package it imports.
+ assert [(e.source, e.target, e.import_edge_count) for e in graph.edges] == [
+ ("community:7", "package:npm:react", 2),
+ ("community:3", "package:npm:react", 3),
+ ("community:9", "package:npm:react", 1),
+ ]
+
+
+def test_a_community_label_prefers_its_own_name() -> None:
+ labelled = json.dumps({"label": " Web surface "})
+ edges = [
+ _Edge("packages/web/a.ts", community_id=1, community_meta_json=labelled),
+ _Edge("single.ts", community_id=2, community_meta_json="{}"),
+ _Edge("packages/ui/b.ts", community_id=3, community_meta_json=None),
+ _Edge("x/y.ts", community_id=4, community_meta_json="not json"),
+ ]
+
+ graph = build_relationship_graph(DECLARED, LINKED, edges, "npm:react")
+
+ assert graph is not None
+ labels = {n.community_id: n.label for n in graph.nodes}
+ assert labels[1] == "Web surface"
+ # No label: the shared root of what it imports from, else the bare id.
+ assert labels[2] == "single.ts"
+ assert labels[3] == "packages/ui"
+ # Two segments is already the root; unparseable metadata degrades to it too.
+ assert labels[4] == "x/y.ts"
+
+
+def test_a_community_with_no_label_and_no_files_falls_back_to_its_id() -> None:
+ from repowise.core.analysis.external_systems.relationships import _community_label
+
+ assert _community_label(None, 12, None) == "Community 12"
+ assert _community_label(json.dumps({"label": " "}), 12, None) == "Community 12"
+
+
+def test_the_graph_is_bounded_by_the_smaller_of_its_two_limits() -> None:
+ edges = [_Edge(f"src/{index}.ts", community_id=index) for index in range(6)]
+
+ assert _returned(edges, node_limit=2, edge_limit=50) == 2
+ assert _returned(edges, node_limit=50, edge_limit=3) == 3
+ assert _returned(edges, node_limit=50, edge_limit=50) == 6
+
+
+def _returned(edges: list[_Edge], *, node_limit: int, edge_limit: int) -> int:
+ graph = build_relationship_graph(
+ DECLARED, LINKED, edges, "npm:react", node_limit=node_limit, edge_limit=edge_limit
+ )
+ assert graph is not None
+ assert graph.aggregate_returned == graph.edge_returned == len(graph.nodes)
+ assert graph.truncated is (graph.aggregate_total > len(graph.nodes))
+ return len(graph.nodes)
+
+
+def test_totals_count_every_community_not_just_the_returned_ones() -> None:
+ edges = [_Edge(f"src/{index}.ts", community_id=index) for index in range(6)]
+
+ graph = build_relationship_graph(DECLARED, LINKED, edges, "npm:react", node_limit=2)
+
+ assert graph is not None
+ assert graph.aggregate_total == 6
+ assert graph.edge_total == 6
+ assert graph.import_edge_total == 6
+ assert graph.importing_file_total == 6
+ assert graph.aggregate_returned == 2
+ assert graph.truncated is True
+
+
+def test_importers_outside_the_scope_are_not_counted() -> None:
+ edges = [
+ _Edge("src/a.ts", community_id=1),
+ _Edge("local-stash/b.ts", community_id=1),
+ _Edge(".claude/worktrees/w/c.ts", community_id=1),
+ ]
+
+ scoped = build_relationship_graph(DECLARED, LINKED, edges, "npm:react")
+ assert scoped is not None
+ assert scoped.nodes[0].importing_file_count == 1
+
+ everything = build_relationship_graph(DECLARED, LINKED, edges, "npm:react", scope="all")
+ assert everything is not None
+ assert everything.nodes[0].importing_file_count == 3
+
+
+def test_edges_to_other_packages_are_ignored() -> None:
+ edges = [_Edge("src/a.ts", target_node_id="external:vue", community_id=1)]
+
+ graph = build_relationship_graph(DECLARED, LINKED, edges, "npm:react")
+
+ assert graph is not None
+ assert graph.nodes == []
+ assert graph.aggregate_total == 0
+
+
+def test_file_expansion_pages_one_community() -> None:
+ edges = [
+ _Edge("src/a.ts", community_id=1),
+ _Edge("src/a.ts", community_id=1),
+ _Edge("src/b.ts", community_id=1),
+ _Edge("other/c.ts", community_id=2),
+ ]
+
+ page = build_importing_files(DECLARED, LINKED, edges, "npm:react", "community:1")
+
+ assert page is not None
+ assert page.total == 2
+ assert [(i.path, i.import_edge_count) for i in page.items] == [("src/a.ts", 2), ("src/b.ts", 1)]
+ assert page.items[0].language == "ts"
+ assert page.truncated is False
+ assert page.limit == DEFAULT_FILE_LIMIT
+
+
+def test_file_expansion_counts_the_targets_each_file_reached() -> None:
+ links = [_Link(node_id="external:react"), _Link(node_id="external:react/jsx-runtime")]
+ edges = [
+ _Edge("src/a.ts", target_node_id="external:react"),
+ _Edge("src/a.ts", target_node_id="external:react/jsx-runtime"),
+ _Edge("src/b.ts", target_node_id="external:react"),
+ ]
+
+ page = build_importing_files(DECLARED, links, edges, "npm:react", "community:1")
+
+ assert page is not None
+ assert [(i.path, i.matched_external_node_count) for i in page.items] == [
+ ("src/a.ts", 2),
+ ("src/b.ts", 1),
+ ]
+
+
+def test_file_expansion_is_bounded_independently_of_the_graph() -> None:
+ edges = [_Edge(f"src/{index:03d}.ts") for index in range(5)]
+
+ first = build_importing_files(DECLARED, LINKED, edges, "npm:react", "community:1", limit=2)
+ assert first is not None
+ assert [i.path for i in first.items] == ["src/000.ts", "src/001.ts"]
+ assert first.total == 5
+ assert first.truncated is True
+
+ past_end = build_importing_files(
+ DECLARED, LINKED, edges, "npm:react", "community:1", limit=2, offset=99
+ )
+ assert past_end is not None
+ assert past_end.items == []
+ assert past_end.total == 5
+ assert past_end.truncated is False
+
+
+def test_file_expansion_of_an_unlinked_package_is_empty_not_missing() -> None:
+ page = build_importing_files(DECLARED, [], [], "npm:react", "community:1")
+
+ assert page is not None
+ assert page.items == []
+ assert page.total == 0
+ assert page.truncated is False
+
+
+def test_the_graph_and_the_expansion_share_one_target_universe() -> None:
+ """A community may not claim importers the drill-down cannot show."""
+ links = [
+ _Link(node_id=f"external:react/m{index:04d}") for index in range(EVIDENCE_TARGET_LIMIT + 5)
+ ]
+ edges = [
+ _Edge(f"src/{index:04d}.ts", target_node_id=link.node_id)
+ for index, link in enumerate(links)
+ ]
+
+ graph = build_relationship_graph(DECLARED, links, edges, "npm:react")
+ page = build_importing_files(
+ DECLARED, links, edges, "npm:react", "community:1", limit=EVIDENCE_TARGET_LIMIT + 5
+ )
+
+ assert graph is not None and page is not None
+ assert graph.nodes[0].importing_file_count == EVIDENCE_TARGET_LIMIT
+ assert page.total == EVIDENCE_TARGET_LIMIT
+
+
[email protected]("bad", ["", "react", ":react", "npm:"])
+def test_a_malformed_package_key_is_rejected(bad: str) -> None:
+ with pytest.raises(ValueError, match="ecosystem and package name"):
+ split_package_key(bad)
+ with pytest.raises(ValueError, match="ecosystem and package name"):
+ build_relationship_graph(DECLARED, LINKED, [], bad)
+
+
[email protected]("bad", ["", "community", "community:x", "cluster:1"])
+def test_a_malformed_aggregate_key_is_rejected(bad: str) -> None:
+ with pytest.raises(ValueError, match="graph community"):
+ split_community_key(bad)
+ with pytest.raises(ValueError, match="graph community"):
+ build_importing_files(DECLARED, LINKED, [], "npm:react", bad)
+
+
+def test_a_scoped_npm_name_round_trips_through_the_key() -> None:
+ declared = [_Declaration(name="@scope/pkg")]
+ links = [_Link(node_id="external:@scope/pkg", name="@scope/pkg")]
+
+ graph = build_relationship_graph(declared, links, [], "npm:@scope/pkg")
+
+ assert graph is not None
+ assert graph.package_name == "@scope/pkg"
+ assert graph.match_basis == "exact"
+
+
+def test_plain_dicts_fold_the_same_as_objects() -> None:
+ as_objects = build_relationship_graph(DECLARED, LINKED, [_Edge("src/a.ts")], "npm:react")
+ as_dicts = build_relationship_graph(
+ [{"ecosystem": "npm", "name": "react", "declared_in": "package.json"}],
+ [{"node_id": "external:react", "ecosystem": "npm", "name": "react"}],
+ [
+ {
+ "source_path": "src/a.ts",
+ "target_node_id": "external:react",
+ "community_id": 1,
+ "community_meta_json": "{}",
+ "language": "ts",
+ }
+ ],
+ "npm:react",
+ )
+
+ assert as_objects is not None and as_dicts is not None
+ assert as_dicts.as_dict() == as_objects.as_dict()
diff --git a/tests/unit/analysis/test_external_systems_summary.py b/tests/unit/analysis/test_external_systems_summary.py
new file mode 100644
index 000000000..74355e8c6
--- /dev/null
+++ b/tests/unit/analysis/test_external_systems_summary.py
@@ -0,0 +1,377 @@
+"""The package summary fold: grouping, scope, bounds and the flags that confess them."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import pytest
+
+from repowise.core.analysis.external_systems import (
+ DEFAULT_SUMMARY_LIMIT,
+ SUMMARY_VERSION_LIMIT,
+ build_package_summary,
+ build_registry,
+)
+
+
+@dataclass
+class _Declaration:
+ """Stub mirroring the ExternalSystem columns the fold reads."""
+
+ ecosystem: str = "npm"
+ name: str = "react"
+ display_name: str = ""
+ category: str = "library"
+ io_kind: str | None = None
+ version: str | None = None
+ declared_in: str = "package.json"
+ is_dev_dep: bool = False
+
+
+@dataclass
+class _Link:
+ node_id: str
+ ecosystem: str = "npm"
+ name: str = "react"
+
+
+@dataclass
+class _Edge:
+ source_path: str
+ target_node_id: str
+
+
+def _declared(name: str, **kwargs) -> _Declaration:
+ return _Declaration(name=name, **kwargs)
+
+
+def test_groups_declarations_into_one_entry_per_package() -> None:
+ summary = build_package_summary(
+ [
+ _declared("react", declared_in="a/package.json", version="18.0.0"),
+ _declared("react", declared_in="b/package.json", version="18.0.0"),
+ _declared("jest", declared_in="a/package.json", is_dev_dep=True),
+ ],
+ [],
+ [],
+ )
+
+ assert summary.total_packages == 2
+ assert summary.total_declarations == 3
+ assert summary.manifest_count == 2
+ assert summary.ecosystems == ["npm"]
+ react = next(item for item in summary.items if item.name == "react")
+ assert react.package_key == "npm:react"
+ assert react.declaration_count == 2
+ assert react.manifest_count == 2
+
+
+def test_auxiliary_declarations_are_excluded_and_counted() -> None:
+ rows = [
+ _declared("react", declared_in="package.json"),
+ _declared("vue", declared_in="local-stash/package.json"),
+ _declared("svelte", declared_in=".claude/worktrees/x/package.json"),
+ ]
+
+ primary = build_package_summary(rows, [], [])
+ assert [item.name for item in primary.items] == ["react"]
+ assert primary.excluded_declarations == 2
+
+ everything = build_package_summary(rows, [], [], scope="all")
+ assert sorted(item.name for item in everything.items) == ["react", "svelte", "vue"]
+ # Nothing is hidden under this scope, so it makes no claim about omissions.
+ assert everything.excluded_declarations == 0
+
+
+def test_auxiliary_only_repository_still_reports_what_it_hid() -> None:
+ summary = build_package_summary([_declared("vue", declared_in="local-stash/p.json")], [], [])
+
+ assert summary.total_packages == 0
+ assert summary.items == []
+ assert summary.excluded_declarations == 1
+ assert summary.manifest_count == 0
+ assert summary.truncated is False
+
+
+def test_versions_are_distinct_sorted_and_capped() -> None:
+ versions = [f"1.0.{index}" for index in range(SUMMARY_VERSION_LIMIT + 3)]
+ rows = [
+ _declared("react", declared_in=f"p{index}/package.json", version=version)
+ for index, version in enumerate(versions)
+ ]
+ rows.append(_declared("react", declared_in="dup/package.json", version=versions[0]))
+
+ entry = build_package_summary(rows, [], []).items[0]
+
+ assert entry.versions == sorted(versions)[:SUMMARY_VERSION_LIMIT]
+ assert entry.versions_total == len(versions)
+ assert entry.versions_truncated is True
+ assert entry.multiple_versions is True
+
+
+def test_single_version_is_not_truncated_or_multiple() -> None:
+ entry = build_package_summary([_declared("react", version="18.0.0")], [], []).items[0]
+
+ assert entry.versions == ["18.0.0"]
+ assert entry.versions_total == 1
+ assert entry.versions_truncated is False
+ assert entry.multiple_versions is False
+
+
+def test_declarations_without_a_version_contribute_none() -> None:
+ entry = build_package_summary([_declared("react", version=None)], [], []).items[0]
+
+ assert entry.versions == []
+ assert entry.versions_total == 0
+ assert entry.versions_truncated is False
+
+
+def test_import_evidence_is_scoped_by_importing_file() -> None:
+ rows = [_declared("react")]
+ links = [_Link(node_id="external:react")]
+ edges = [
+ _Edge("src/a.ts", "external:react"),
+ _Edge("src/a.ts", "external:react"),
+ _Edge("src/b.ts", "external:react"),
+ _Edge("local-stash/c.ts", "external:react"),
+ ]
+
+ primary = build_package_summary(rows, links, edges).items[0]
+ assert primary.external_node_count == 1
+ assert primary.import_edge_count == 3
+ assert primary.importing_file_count == 2
+ assert primary.link_state == "linked"
+
+ everything = build_package_summary(rows, links, edges, scope="all").items[0]
+ assert everything.import_edge_count == 4
+ assert everything.importing_file_count == 3
+ # A node exists or it does not; scope is a claim about importers, not nodes.
+ assert everything.external_node_count == 1
+
+
+def test_edges_to_unresolved_targets_are_ignored() -> None:
+ entry = build_package_summary(
+ [_declared("react")],
+ [_Link(node_id="external:react")],
+ [_Edge("src/a.ts", "external:something-else")],
+ ).items[0]
+
+ assert entry.import_edge_count == 0
+ assert entry.link_state == "linked"
+
+
+def test_declared_but_unlinked_package_reads_unlinked() -> None:
+ entry = build_package_summary([_declared("react")], [], []).items[0]
+
+ assert entry.external_node_count == 0
+ assert entry.import_edge_count == 0
+ assert entry.link_state == "unlinked"
+
+
+def test_totals_describe_the_whole_scope_not_the_page() -> None:
+ rows = [
+ _declared("react"),
+ _declared("vue"),
+ _declared("jest", is_dev_dep=True),
+ _declared("react", is_dev_dep=True, declared_in="b/package.json"),
+ ]
+ links = [_Link(node_id="external:react"), _Link(node_id="external:vue", name="vue")]
+ edges = [_Edge("src/a.ts", "external:react")]
+
+ summary = build_package_summary(rows, links, edges, limit=1)
+
+ assert summary.total_packages == 3
+ assert summary.returned == 1
+ assert summary.runtime_packages == 2
+ assert summary.dev_only_packages == 1
+ assert summary.observed_packages == 1
+ assert summary.linked_packages == 2
+ assert summary.unlinked_packages == 1
+ # Linked to a node but with no importer in scope — the honest middle state.
+ assert summary.linked_without_imports == 1
+
+
+def test_ordering_puts_runtime_then_most_imported_first() -> None:
+ rows = [
+ _declared("zzz-dev", is_dev_dep=True),
+ _declared("aaa-runtime"),
+ _declared("mmm-imported"),
+ ]
+ links = [_Link(node_id="external:mmm-imported", name="mmm-imported")]
+ edges = [_Edge("src/a.ts", "external:mmm-imported")]
+
+ summary = build_package_summary(rows, links, edges)
+
+ assert [item.name for item in summary.items] == ["mmm-imported", "aaa-runtime", "zzz-dev"]
+
+
+def test_ties_break_on_lowercased_name_then_ecosystem() -> None:
+ rows = [
+ _declared("Beta"),
+ _declared("alpha"),
+ _declared("alpha", ecosystem="pypi"),
+ ]
+
+ summary = build_package_summary(rows, [], [])
+
+ assert [(i.ecosystem, i.name) for i in summary.items] == [
+ ("npm", "alpha"),
+ ("pypi", "alpha"),
+ ("npm", "Beta"),
+ ]
+
+
+def test_paging_reports_what_it_left_out() -> None:
+ rows = [_declared(f"pkg-{index:03d}") for index in range(5)]
+
+ first = build_package_summary(rows, [], [], limit=2)
+ assert [i.name for i in first.items] == ["pkg-000", "pkg-001"]
+ assert first.returned == 2
+ assert first.truncated is True
+
+ last = build_package_summary(rows, [], [], limit=2, offset=4)
+ assert [i.name for i in last.items] == ["pkg-004"]
+ assert last.truncated is False
+ assert last.total_packages == 5
+
+ past_end = build_package_summary(rows, [], [], limit=2, offset=99)
+ assert past_end.items == []
+ assert past_end.returned == 0
+ # Totals still describe the scope even when the page is empty.
+ assert past_end.total_packages == 5
+ assert past_end.truncated is False
+
+
+def test_default_limit_is_the_folds_own() -> None:
+ rows = [_declared(f"pkg-{index:04d}") for index in range(DEFAULT_SUMMARY_LIMIT + 5)]
+
+ summary = build_package_summary(rows, [], [])
+
+ assert summary.limit == DEFAULT_SUMMARY_LIMIT
+ assert summary.returned == DEFAULT_SUMMARY_LIMIT
+ assert summary.truncated is True
+
+
+def test_conflicting_declaration_metadata_resolves_deterministically() -> None:
+ rows = [
+ _declared("react", category="library", io_kind=None, display_name=""),
+ _declared("react", category="framework", io_kind="network", declared_in="b/package.json"),
+ ]
+
+ entry = build_package_summary(rows, [], []).items[0]
+
+ # Lowest category and io_kind win, ignoring absent values; display name
+ # falls back to the package name when no declaration supplied one.
+ assert entry.category == "framework"
+ assert entry.io_kind == "network"
+ assert entry.display_name == "react"
+
+
+def test_a_declaration_may_be_both_runtime_and_dev() -> None:
+ rows = [
+ _declared("react", is_dev_dep=False),
+ _declared("react", is_dev_dep=True, declared_in="b/package.json"),
+ ]
+
+ entry = build_package_summary(rows, [], []).items[0]
+
+ assert entry.runtime_declared is True
+ assert entry.dev_declared is True
+
+
+def test_empty_input_is_an_honest_empty_page() -> None:
+ summary = build_package_summary([], [], [])
+
+ assert summary.as_dict() == {
+ "items": [],
+ "returned": 0,
+ "total_packages": 0,
+ "limit": DEFAULT_SUMMARY_LIMIT,
+ "offset": 0,
+ "truncated": False,
+ "scope": "primary",
+ "excluded_declarations": 0,
+ "total_declarations": 0,
+ "runtime_packages": 0,
+ "dev_only_packages": 0,
+ "observed_packages": 0,
+ "linked_packages": 0,
+ "unlinked_packages": 0,
+ "linked_without_imports": 0,
+ "ecosystems": [],
+ "manifest_count": 0,
+ }
+
+
+def test_plain_dicts_fold_the_same_as_objects() -> None:
+ """The artifact path: records arrive as JSON, not as rows."""
+ as_objects = build_package_summary(
+ [_declared("react", version="18.0.0")],
+ [_Link(node_id="external:react")],
+ [_Edge("src/a.ts", "external:react")],
+ )
+ as_dicts = build_package_summary(
+ [
+ {
+ "ecosystem": "npm",
+ "name": "react",
+ "display_name": "",
+ "category": "library",
+ "io_kind": None,
+ "version": "18.0.0",
+ "declared_in": "package.json",
+ "is_dev_dep": False,
+ }
+ ],
+ [{"node_id": "external:react", "ecosystem": "npm", "name": "react"}],
+ [{"source_path": "src/a.ts", "target_node_id": "external:react"}],
+ )
+
+ assert as_dicts.as_dict() == as_objects.as_dict()
+
+
[email protected]("scope", ["primary", "all"])
+def test_scope_is_echoed_back(scope: str) -> None:
+ assert build_package_summary([], [], [], scope=scope).scope == scope
+
+
+def test_registry_keeps_every_declaration_and_orders_by_prominence() -> None:
+ rows = [
+ _declared("zlib", category="library", declared_in="b/package.json"),
+ _declared("fastapi", category="framework"),
+ _declared("ruff", category="tool"),
+ _declared("postgres", category="service"),
+ _declared("zlib", category="library", declared_in="a/package.json"),
+ _declared("unknown-kind", category="mystery"),
+ ]
+
+ registry = build_registry(rows)
+
+ assert [item.name for item in registry.items] == [
+ "fastapi",
+ "postgres",
+ "ruff",
+ "zlib",
+ "zlib",
+ "unknown-kind",
+ ]
+ # One row per declaration: the two zlib manifests both survive, in path order.
+ assert [i.declared_in for i in registry.items if i.name == "zlib"] == [
+ "a/package.json",
+ "b/package.json",
+ ]
+ assert registry.total == 6
+ assert registry.manifests == ["a/package.json", "b/package.json", "package.json"]
+
+
+def test_registry_counts_the_dev_split_and_falls_back_to_the_name() -> None:
+ registry = build_registry(
+ [
+ _declared("react", display_name="React"),
+ _declared("jest", display_name="", is_dev_dep=True),
+ ]
+ )
+
+ assert registry.prod_count == 1
+ assert registry.dev_count == 1
+ assert {i.name: i.display_name for i in registry.items} == {"react": "React", "jest": "jest"}
diff --git a/tests/unit/server/test_external_systems.py b/tests/unit/server/test_external_systems.py
index 668a94707..1e6d04f88 100644
--- a/tests/unit/server/test_external_systems.py
+++ b/tests/unit/server/test_external_systems.py
@@ -773,4 +773,8 @@ async def test_relationship_graph_query_count_is_constant(
assert response.status_code == 200
selects = [statement for statement in statements if statement.lstrip().startswith("SELECT")]
- assert len(selects) == 2
+ # Declarations, resolved external nodes, then the edges reaching them. The
+ # count is what matters: it does not grow with importers, communities or
+ # declared packages. Composition moved to a session-free fold, so the third
+ # read replaces the aggregate the graph query used to push down.
+ assert len(selects) == 3