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(architecture): add focused package relationships (#1946)
Raghav Chamadiya8941f21e00c3
diff --git a/packages/api-client/src/external-systems.ts b/packages/api-client/src/external-systems.tsindex 393fbdb46..9a8d816a8 100644--- a/packages/api-client/src/external-systems.ts+++ b/packages/api-client/src/external-systems.ts@@ -1,5 +1,7 @@import type {ExternalSystemsRegistry,+ ExternalSystemImportingFiles,+ ExternalSystemRelationshipGraph,ExternalSystemsSummary,ExternalSystemsSummaryScope,} from "@repowise-dev/types/external-systems";@@ -15,6 +17,38 @@ export async function getExternalSystems();}+/** Aggregate-first focused relationship graph for one selected package. */+export async function getExternalSystemRelationshipGraph(+ repoId: string,+ packageKey: string,+ options: { scope?: ExternalSystemsSummaryScope; nodeLimit?: number; edgeLimit?: number } = {},+): Promise<ExternalSystemRelationshipGraph> {+ const params = new URLSearchParams();+ if (options.scope) params.set("scope", options.scope);+ if (options.nodeLimit !== undefined) params.set("node_limit", String(options.nodeLimit));+ if (options.edgeLimit !== undefined) params.set("edge_limit", String(options.edgeLimit));+ const query = params.size ? `?${params.toString()}` : "";+ return apiGet<ExternalSystemRelationshipGraph>(+ `/api/repos/${repoId}/external-systems/${encodeURIComponent(packageKey)}/graph${query}`,+ );+}++/** One independently bounded page of importing files for an aggregate. */+export async function getExternalSystemImportingFiles(+ repoId: string,+ packageKey: string,+ aggregateKey: string,+ options: { scope?: ExternalSystemsSummaryScope; limit?: number; offset?: number } = {},+): Promise<ExternalSystemImportingFiles> {+ const params = new URLSearchParams({ aggregate_key: aggregateKey });+ if (options.scope) params.set("scope", options.scope);+ if (options.limit !== undefined) params.set("limit", String(options.limit));+ if (options.offset !== undefined) params.set("offset", String(options.offset));+ return apiGet<ExternalSystemImportingFiles>(+ `/api/repos/${repoId}/external-systems/${encodeURIComponent(packageKey)}/graph/files?${params.toString()}`,+ );+}+/** Canonical packages with bounded declaration and persisted usage aggregates. */export async function getExternalSystemsSummary(repoId: string,diff --git a/packages/server/src/repowise/server/routers/external_systems.py b/packages/server/src/repowise/server/routers/external_systems.pyindex 855517c97..b8dc80c00 100644--- a/packages/server/src/repowise/server/routers/external_systems.py+++ b/packages/server/src/repowise/server/routers/external_systems.py@@ -10,7 +10,7 @@ from __future__ import annotationsfrom typing import Literal-from fastapi import APIRouter, Depends, Query+from fastapi import APIRouter, Depends, HTTPException, Queryfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession@@ -18,9 +18,21 @@ from repowise.core.persistence.models import ExternalSystemfrom repowise.server.deps import get_db_session, verify_api_keyfrom repowise.server.schemas.external_systems import (ExternalSystemEntry,+ ExternalSystemImportingFilesResponse,+ ExternalSystemRelationshipGraphResponse,ExternalSystemsResponse,ExternalSystemsSummaryResponse,)+from repowise.server.services.external_system_relationships import (+ DEFAULT_FILE_LIMIT,+ DEFAULT_RELATIONSHIP_EDGE_LIMIT,+ DEFAULT_RELATIONSHIP_NODE_LIMIT,+ MAX_FILE_LIMIT,+ MAX_RELATIONSHIP_EDGE_LIMIT,+ MAX_RELATIONSHIP_NODE_LIMIT,+ build_external_system_importing_files,+ build_external_system_relationship_graph,+)from repowise.server.services.external_systems import (MAX_SUMMARY_LIMIT,build_external_systems_summary,@@ -50,6 +62,70 @@ async def summarize_external_systems()+ "/{repo_id}/external-systems/{package_key:path}/graph/files",+ response_model=ExternalSystemImportingFilesResponse,+)+async def external_system_importing_files(+ repo_id: str,+ package_key: str,+ aggregate_key: str = Query(...),+ scope: Literal["primary", "all"] = "primary",+ limit: int = Query(default=DEFAULT_FILE_LIMIT, ge=1, le=MAX_FILE_LIMIT),+ offset: int = Query(default=0, ge=0),+ session: AsyncSession = Depends(get_db_session),+) -> ExternalSystemImportingFilesResponse:+ """Paginate importing files only after a relationship aggregate is opened."""+ try:+ response = await build_external_system_importing_files(+ session,+ repo_id,+ package_key,+ aggregate_key,+ scope=scope,+ limit=limit,+ offset=offset,+ )+ except ValueError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc+ if response is None:+ raise HTTPException(status_code=404, detail="Declared package not found in this scope")+ return response+++ "/{repo_id}/external-systems/{package_key:path}/graph",+ response_model=ExternalSystemRelationshipGraphResponse,+)+async def external_system_relationship_graph(+ repo_id: str,+ package_key: str,+ scope: Literal["primary", "all"] = "primary",+ node_limit: int = Query(+ default=DEFAULT_RELATIONSHIP_NODE_LIMIT, ge=1, le=MAX_RELATIONSHIP_NODE_LIMIT+ ),+ edge_limit: int = Query(+ default=DEFAULT_RELATIONSHIP_EDGE_LIMIT, ge=1, le=MAX_RELATIONSHIP_EDGE_LIMIT+ ),+ session: AsyncSession = Depends(get_db_session),+) -> ExternalSystemRelationshipGraphResponse:+ """Show bounded first-party communities related to one declared package."""+ try:+ response = await build_external_system_relationship_graph(+ session,+ repo_id,+ package_key,+ scope=scope,+ node_limit=node_limit,+ edge_limit=edge_limit,+ )+ except ValueError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc+ if response is None:+ raise HTTPException(status_code=404, detail="Declared package not found in this scope")+ return response++@router.get("/{repo_id}/external-systems", response_model=ExternalSystemsResponse)async def list_external_systems(repo_id: str,diff --git a/packages/server/src/repowise/server/schemas/external_systems.py b/packages/server/src/repowise/server/schemas/external_systems.pyindex ff9c90fd2..3e09a7c22 100644--- a/packages/server/src/repowise/server/schemas/external_systems.py+++ b/packages/server/src/repowise/server/schemas/external_systems.py@@ -33,6 +33,7 @@ class ExternalSystemsResponse(BaseModel):ExternalSystemLinkState = Literal["linked", "unlinked"]ExternalSystemsSummaryScope = Literal["primary", "all"]+ExternalSystemMatchBasis = Literal["exact", "subpath", "mapped", "mixed", "unresolved"]class ExternalSystemSummaryEntry(BaseModel):@@ -78,3 +79,74 @@ class ExternalSystemsSummaryResponse(BaseModel):linked_without_imports: intecosystems: list[str]manifest_count: int+++class ExternalSystemGraphTarget(BaseModel):+ """One persisted external graph node linked to the selected package."""++ node_id: str+ match_basis: Literal["exact", "subpath", "mapped"]+++class ExternalSystemRelationshipNode(BaseModel):+ """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 = None+++class ExternalSystemRelationshipEdge(BaseModel):+ source: str+ target: str+ import_edge_count: int+++class ExternalSystemRelationshipGraphResponse(BaseModel):+ """Bounded aggregate-first relationship graph for one declared package."""++ package_key: str+ package_name: str+ package_node_id: str+ match_basis: ExternalSystemMatchBasis+ matched_external_nodes: list[ExternalSystemGraphTarget]+ matched_external_nodes_total: int+ matched_external_nodes_truncated: bool+ evidence_target_limit: int+ evidence_truncated: bool+ nodes: list[ExternalSystemRelationshipNode]+ edges: list[ExternalSystemRelationshipEdge]+ 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: ExternalSystemsSummaryScope+++class ExternalSystemImportingFile(BaseModel):+ path: str+ language: str+ import_edge_count: int+ matched_external_node_count: int+++class ExternalSystemImportingFilesResponse(BaseModel):+ """One independently bounded page of files behind an aggregate node."""++ package_key: str+ aggregate_key: str+ items: list[ExternalSystemImportingFile]+ total: int+ returned: int+ limit: int+ offset: int+ truncated: bool+ scope: ExternalSystemsSummaryScopediff --git a/packages/server/src/repowise/server/services/external_system_relationships.py b/packages/server/src/repowise/server/services/external_system_relationships.pynew file mode 100644index 000000000..1c5cdca01--- /dev/null+++ b/packages/server/src/repowise/server/services/external_system_relationships.py@@ -0,0 +1,370 @@+"""Bounded, aggregate-first reads for one external package's relationships."""++from __future__ import annotations++import json+from typing import Literal++from sqlalchemy import and_, case, distinct, func, literal, not_, or_, select+from sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.orm import aliased++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+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_(+ ExternalSystem.repository_id == repository_id,+ ExternalSystem.ecosystem == declared.c.ecosystem,+ ExternalSystem.name == declared.c.name,+ ),+ )+ .outerjoin(+ GraphNode,+ and_(+ GraphNode.repository_id == repository_id,+ GraphNode.external_system_id == ExternalSystem.id,+ ),+ )+ .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+++async def build_external_system_relationship_graph(+ session: AsyncSession,+ repository_id: str,+ package_key: str,+ *,+ scope: RelationshipScope = "primary",+ 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:+ 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,+ node_limit=node_limit,+ edge_limit=edge_limit,+ truncated=aggregate_total > len(nodes) or evidence_truncated,+ scope=scope,+ )+++async def build_external_system_importing_files(+ session: AsyncSession,+ repository_id: str,+ package_key: str,+ aggregate_key: str,+ *,+ scope: RelationshipScope = "primary",+ 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:+ 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),+ limit=limit,+ offset=offset,+ truncated=offset + len(items) < total,+ scope=scope,+ )diff --git a/packages/types/src/external-systems.ts b/packages/types/src/external-systems.tsindex 6296ca06d..a8e021b14 100644--- a/packages/types/src/external-systems.ts+++ b/packages/types/src/external-systems.ts@@ -93,3 +93,68 @@ export interface ExternalSystemsSummary {ecosystems: string[];manifest_count: number;}++export type ExternalSystemMatchBasis = "exact" | "subpath" | "mapped" | "mixed" | "unresolved";++export interface ExternalSystemGraphTarget {+ node_id: string;+ match_basis: Exclude<ExternalSystemMatchBasis, "mixed" | "unresolved">;+}++export interface ExternalSystemRelationshipNode {+ aggregate_key: string;+ label: string;+ community_id: number;+ importing_file_count: number;+ import_edge_count: number;+ top_file: string | null;+}++export interface ExternalSystemRelationshipEdge {+ source: string;+ target: string;+ import_edge_count: number;+}++export interface ExternalSystemRelationshipGraph {+ package_key: string;+ package_name: string;+ package_node_id: string;+ match_basis: ExternalSystemMatchBasis;+ matched_external_nodes: ExternalSystemGraphTarget[];+ matched_external_nodes_total: number;+ matched_external_nodes_truncated: boolean;+ evidence_target_limit: number;+ evidence_truncated: boolean;+ nodes: ExternalSystemRelationshipNode[];+ edges: ExternalSystemRelationshipEdge[];+ aggregate_total: number;+ aggregate_returned: number;+ edge_total: number;+ edge_returned: number;+ importing_file_total: number;+ import_edge_total: number;+ node_limit: number;+ edge_limit: number;+ truncated: boolean;+ scope: ExternalSystemsSummaryScope;+}++export interface ExternalSystemImportingFile {+ path: string;+ language: string;+ import_edge_count: number;+ matched_external_node_count: number;+}++export interface ExternalSystemImportingFiles {+ package_key: string;+ aggregate_key: string;+ items: ExternalSystemImportingFile[];+ total: number;+ returned: number;+ limit: number;+ offset: number;+ truncated: boolean;+ scope: ExternalSystemsSummaryScope;+}diff --git a/packages/ui/__tests__/dependencies/external-dependencies-table.test.tsx b/packages/ui/__tests__/dependencies/external-dependencies-table.test.tsxindex bd4ac19b5..c3bf4073e 100644--- a/packages/ui/__tests__/dependencies/external-dependencies-table.test.tsx+++ b/packages/ui/__tests__/dependencies/external-dependencies-table.test.tsx@@ -2,12 +2,15 @@ import * as React from "react";import { fireEvent, render, screen, within } from "@testing-library/react";import { describe, expect, it, vi } from "vitest";import type {+ ExternalSystemImportingFiles,+ ExternalSystemRelationshipGraph,ExternalSystemSummaryEntry,ExternalSystemsSummary,} from "@repowise-dev/types/external-systems";import {DEFAULT_EXTERNAL_DEPENDENCY_STATE,ExternalDependenciesTable,+ PackageRelationshipGraph,type ExternalDependencyTableState,} from "../../src/dependencies";@@ -35,6 +38,66 @@ function entry(index: number, overrides: Partial<ExternalSystemSummaryEntry> = {};}+function relationshipGraph(+ overrides: Partial<ExternalSystemRelationshipGraph> = {},+): ExternalSystemRelationshipGraph {+ return {+ package_key: "npm:react",+ package_name: "react",+ package_node_id: "package:npm:react",+ match_basis: "mixed",+ matched_external_nodes: [+ { node_id: "external:react", match_basis: "exact" },+ { node_id: "external:react/jsx-runtime", match_basis: "subpath" },+ ],+ matched_external_nodes_total: 2,+ matched_external_nodes_truncated: false,+ evidence_target_limit: 200,+ evidence_truncated: false,+ nodes: [+ {+ aggregate_key: "community:1",+ label: "Web runtime",+ community_id: 1,+ importing_file_count: 2,+ import_edge_count: 3,+ top_file: "src/app.tsx",+ },+ ],+ edges: [{ source: "community:1", target: "package:npm:react", import_edge_count: 3 }],+ aggregate_total: 1,+ aggregate_returned: 1,+ edge_total: 1,+ edge_returned: 1,+ importing_file_total: 2,+ import_edge_total: 3,+ node_limit: 50,+ edge_limit: 200,+ truncated: false,+ scope: "primary",+ ...overrides,+ };+}++const importingFiles: ExternalSystemImportingFiles = {+ package_key: "npm:react",+ aggregate_key: "community:1",+ items: [+ {+ path: "src/app.tsx",+ language: "typescript",+ import_edge_count: 2,+ matched_external_node_count: 2,+ },+ ],+ total: 2,+ returned: 1,+ limit: 1,+ offset: 0,+ truncated: true,+ scope: "primary",+};+function summary(items: ExternalSystemSummaryEntry[]): ExternalSystemsSummary {return {items,@@ -111,6 +174,115 @@ describe("ExternalDependenciesTable", () => {expect(within(dialog).getByText(/1 declaration/)).toBeInTheDocument();});+ it("opens relationships from the inspector and exposes loading and error states", () => {+ const onShowRelationships = vi.fn();+ const selected = entry(7, { display_name: "React" });+ const { rerender } = render(+ <ExternalDependenciesTable+ data={summary([selected])}+ state={DEFAULT_EXTERNAL_DEPENDENCY_STATE}+ onStateChange={vi.fn()}+ selected={selected}+ onSelectedChange={vi.fn()}+ onShowRelationships={onShowRelationships}+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: "Show relationships" }));+ expect(onShowRelationships).toHaveBeenCalledOnce();++ rerender(+ <ExternalDependenciesTable+ data={summary([selected])}+ state={DEFAULT_EXTERNAL_DEPENDENCY_STATE}+ onStateChange={vi.fn()}+ selected={selected}+ onSelectedChange={vi.fn()}+ relationshipsOpen+ relationshipsLoading+ onHideRelationships={vi.fn()}+ />,+ );+ expect(screen.getByText("Loading package relationships…")).toBeInTheDocument();++ rerender(+ <ExternalDependenciesTable+ data={summary([selected])}+ state={DEFAULT_EXTERNAL_DEPENDENCY_STATE}+ onStateChange={vi.fn()}+ selected={selected}+ onSelectedChange={vi.fn()}+ relationshipsOpen+ relationshipsError="Relationship request failed"+ onHideRelationships={vi.fn()}+ onRetryRelationships={vi.fn()}+ />,+ );+ expect(screen.getByRole("alert")).toHaveTextContent("Relationship request failed");+ expect(screen.getByRole("button", { name: "Retry" })).toBeInTheDocument();+ });++ it("renders empty and capped relationship evidence honestly", () => {+ const { rerender } = render(+ <PackageRelationshipGraph+ packageLabel="unlinked"+ graph={relationshipGraph({+ match_basis: "unresolved",+ matched_external_nodes: [],+ matched_external_nodes_total: 0,+ nodes: [],+ edges: [],+ aggregate_total: 0,+ aggregate_returned: 0,+ edge_total: 0,+ edge_returned: 0,+ importing_file_total: 0,+ import_edge_total: 0,+ })}+ onBack={vi.fn()}+ onToggleAggregate={vi.fn()}+ onFilesPageChange={vi.fn()}+ />,+ );+ expect(screen.getByText("No relationship evidence")).toBeInTheDocument();+ expect(screen.getByText(/not linked to a persisted external graph target/)).toBeInTheDocument();++ rerender(+ <PackageRelationshipGraph+ packageLabel="React"+ graph={relationshipGraph({ aggregate_total: 74, edge_total: 74, truncated: true })}+ onBack={vi.fn()}+ onToggleAggregate={vi.fn()}+ onFilesPageChange={vi.fn()}+ />,+ );+ expect(screen.getByRole("status")).toHaveTextContent("Showing 1 of 74 areas");+ expect(screen.getByRole("status")).toHaveTextContent("50 areas and 200 edges");+ });++ it("keeps aggregate expansion keyboard-accessible and file pages bounded", () => {+ const onToggleAggregate = vi.fn();+ const onFilesPageChange = vi.fn();+ render(+ <PackageRelationshipGraph+ packageLabel="React"+ graph={relationshipGraph()}+ expandedAggregateKey="community:1"+ files={importingFiles}+ onBack={vi.fn()}+ onToggleAggregate={onToggleAggregate}+ onFilesPageChange={onFilesPageChange}+ />,+ );+ const area = screen.getByRole("button", { name: /Web runtime/ });+ expect(area.tagName).toBe("BUTTON");+ expect(area).toHaveAttribute("aria-expanded", "true");+ fireEvent.click(area);+ expect(onToggleAggregate).toHaveBeenCalledWith(null);+ expect(screen.getAllByText("src/app.tsx")).toHaveLength(1);+ fireEvent.click(screen.getByRole("button", { name: "Next importing files" }));+ expect(onFilesPageChange).toHaveBeenCalledWith(1);+ });+it("renders a repository-level empty state", () => {const onStateChange = vi.fn();render(diff --git a/packages/ui/src/dependencies/external-dependencies-table.tsx b/packages/ui/src/dependencies/external-dependencies-table.tsxindex 1968f2c93..985f21901 100644--- a/packages/ui/src/dependencies/external-dependencies-table.tsx+++ b/packages/ui/src/dependencies/external-dependencies-table.tsx@@ -6,11 +6,12 @@ import {Box,ChevronLeft,ChevronRight,- ExternalLink,- FileCode2,+ Network,Search,} from "lucide-react";import type {+ ExternalSystemImportingFiles,+ ExternalSystemRelationshipGraph,ExternalSystemSummaryEntry,ExternalSystemsSummary,} from "@repowise-dev/types/external-systems";@@ -28,6 +29,7 @@ import {SelectValue,} from "../ui/select";import { Sheet, SheetContent, SheetTitle } from "../ui/sheet";+import { PackageRelationshipGraph } from "./package-relationship-graph";export type ExternalDependencyRole = "all" | "runtime" | "dev-only" | "mixed";export type ExternalDependencyUsage =@@ -65,23 +67,26 @@ export const DEFAULT_EXTERNAL_DEPENDENCY_STATE: ExternalDependencyTableState = {page: 1,};-export interface PackageGraphEvidence {- centerNodeId: string;- importingFiles: string[];- importEdgeCount: number;- totalNodes: number;-}-export interface ExternalDependenciesTableProps {data: ExternalSystemsSummary;state: ExternalDependencyTableState;onStateChange: (state: ExternalDependencyTableState) => void;selected: ExternalSystemSummaryEntry | null;onSelectedChange: (entry: ExternalSystemSummaryEntry | null) => void;- evidence?: PackageGraphEvidence | undefined;- evidenceLoading?: boolean | undefined;- evidenceError?: string | null | undefined;- graphHref?: string | undefined;+ relationshipsOpen?: boolean | undefined;+ relationships?: ExternalSystemRelationshipGraph | undefined;+ relationshipsLoading?: boolean | undefined;+ relationshipsError?: string | null | undefined;+ expandedAggregateKey?: string | null | undefined;+ importingFiles?: ExternalSystemImportingFiles | undefined;+ importingFilesLoading?: boolean | undefined;+ importingFilesError?: string | null | undefined;+ onShowRelationships?: (() => void) | undefined;+ onHideRelationships?: (() => void) | undefined;+ onRetryRelationships?: (() => void) | undefined;+ onToggleAggregate?: ((aggregateKey: string | null) => void) | undefined;+ onFilesPageChange?: ((offset: number) => void) | undefined;+ onRetryImportingFiles?: (() => void) | undefined;renderFileLink?: ((path: string, children: React.ReactNode) => React.ReactNode) | undefined;pageSize?: number | undefined;onLoadMore?: (() => void) | undefined;@@ -174,18 +179,38 @@ function Versions({ entry }: { entry: ExternalSystemSummaryEntry }) {function PackageInspector({entry,- evidence,- evidenceLoading,- evidenceError,- graphHref,+ relationshipsOpen,+ relationships,+ relationshipsLoading,+ relationshipsError,+ expandedAggregateKey,+ importingFiles,+ importingFilesLoading,+ importingFilesError,+ onShowRelationships,+ onHideRelationships,+ onRetryRelationships,+ onToggleAggregate,+ onFilesPageChange,+ onRetryImportingFiles,renderFileLink,onClose,}: {entry: ExternalSystemSummaryEntry | null;- evidence?: PackageGraphEvidence | undefined;- evidenceLoading?: boolean | undefined;- evidenceError?: string | null | undefined;- graphHref?: string | undefined;+ relationshipsOpen?: boolean | undefined;+ relationships?: ExternalSystemRelationshipGraph | undefined;+ relationshipsLoading?: boolean | undefined;+ relationshipsError?: string | null | undefined;+ expandedAggregateKey?: string | null | undefined;+ importingFiles?: ExternalSystemImportingFiles | undefined;+ importingFilesLoading?: boolean | undefined;+ importingFilesError?: string | null | undefined;+ onShowRelationships?: (() => void) | undefined;+ onHideRelationships?: (() => void) | undefined;+ onRetryRelationships?: (() => void) | undefined;+ onToggleAggregate?: ((aggregateKey: string | null) => void) | undefined;+ onFilesPageChange?: ((offset: number) => void) | undefined;+ onRetryImportingFiles?: (() => void) | undefined;renderFileLink?: ExternalDependenciesTableProps["renderFileLink"];onClose: () => void;}) {@@ -210,6 +235,35 @@ function PackageInspector({</header><div className="min-h-0 flex-1 space-y-6 overflow-y-auto px-5 py-5">+ {relationshipsOpen ? (+ relationshipsLoading && !relationships ? (+ <div className="space-y-3" role="status">+ <Button variant="ghost" size="sm" onClick={onHideRelationships}>Back to package details</Button>+ <p className="text-xs text-[var(--color-text-tertiary)]">Loading package relationships…</p>+ </div>+ ) : relationshipsError ? (+ <div className="space-y-3" role="alert">+ <Button variant="ghost" size="sm" onClick={onHideRelationships}>Back to package details</Button>+ <p className="text-xs text-[var(--color-text-secondary)]">{relationshipsError}</p>+ {onRetryRelationships ? <Button variant="outline" size="sm" onClick={onRetryRelationships}>Retry</Button> : null}+ </div>+ ) : relationships ? (+ <PackageRelationshipGraph+ packageLabel={entry.display_name}+ graph={relationships}+ expandedAggregateKey={expandedAggregateKey}+ files={importingFiles}+ filesLoading={importingFilesLoading}+ filesError={importingFilesError}+ renderFileLink={renderFileLink}+ onBack={() => onHideRelationships?.()}+ onToggleAggregate={(key) => onToggleAggregate?.(key)}+ onFilesPageChange={(offset) => onFilesPageChange?.(offset)}+ onRetryFiles={onRetryImportingFiles}+ />+ ) : null+ ) : (+ <><section><h3 className="text-sm font-semibold text-[var(--color-text-primary)]">Declarations</h3><p className="mt-2 text-xs text-[var(--color-text-secondary)]">@@ -225,53 +279,24 @@ function PackageInspector({<section><h3 className="text-sm font-semibold text-[var(--color-text-primary)]">Import graph evidence</h3>- {evidenceLoading && !evidence ? (- <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">Loading focused graph evidence…</p>- ) : evidenceError ? (- <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">{evidenceError}</p>- ) : evidence ? (- <>- <p className="mt-2 text-xs text-[var(--color-text-secondary)]">- {entry.importing_file_count} importing file{entry.importing_file_count === 1 ? "" : "s"} and {entry.import_edge_count} import edge{entry.import_edge_count === 1 ? "" : "s"} in the persisted graph.- </p>- <ul className="mt-3 space-y-1.5">- {evidence.importingFiles.slice(0, 20).map((path) => (- <li key={path} className="flex items-start gap-2 text-xs">- <FileCode2 className="mt-0.5 h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)]" />- <span className="min-w-0 break-all font-mono text-[var(--color-text-secondary)]">- {renderFileLink ? renderFileLink(path, path) : path}- </span>- </li>- ))}- </ul>- {entry.importing_file_count > evidence.importingFiles.length ? (- <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">- Focused evidence returned {evidence.importingFiles.length} of {entry.importing_file_count} importing files.- </p>- ) : null}- {entry.external_node_count > 1 ? (- <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">- This focus shows one of {entry.external_node_count} linked graph targets. Package totals above include all targets.- </p>- ) : null}- </>- ) : (- <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">- {entry.link_state === "unlinked"- ? "This declaration is not linked to a persisted graph node."- : "No import edges were observed for the linked graph node."}- </p>- )}+ <p className="mt-2 text-xs text-[var(--color-text-secondary)]">+ {entry.importing_file_count} importing file{entry.importing_file_count === 1 ? "" : "s"} and {entry.import_edge_count} import edge{entry.import_edge_count === 1 ? "" : "s"} in the persisted graph.+ </p>+ {entry.external_node_count > 1 ? (+ <p className="mt-1 text-xs text-[var(--color-text-tertiary)]">Evidence spans {entry.external_node_count} linked graph targets.</p>+ ) : entry.link_state === "unlinked" ? (+ <p className="mt-1 text-xs text-[var(--color-text-tertiary)]">This declaration has no linked external graph target.</p>+ ) : null}</section>+ </>+ )}</div>- {graphHref ? (+ {!relationshipsOpen && onShowRelationships ? (<footer className="border-t border-[var(--color-border-default)] p-4">- <Button asChild className="w-full">- <a href={graphHref}>- Open focused package in graph- <ExternalLink className="h-4 w-4" />- </a>+ <Button className="w-full" onClick={onShowRelationships}>+ <Network className="h-4 w-4" />+ Show relationships</Button></footer>) : null}@@ -288,10 +313,20 @@ export function ExternalDependenciesTable({onStateChange,selected,onSelectedChange,- evidence,- evidenceLoading,- evidenceError,- graphHref,+ relationshipsOpen,+ relationships,+ relationshipsLoading,+ relationshipsError,+ expandedAggregateKey,+ importingFiles,+ importingFilesLoading,+ importingFilesError,+ onShowRelationships,+ onHideRelationships,+ onRetryRelationships,+ onToggleAggregate,+ onFilesPageChange,+ onRetryImportingFiles,renderFileLink,pageSize = 25,onLoadMore,@@ -574,10 +609,20 @@ export function ExternalDependenciesTable({<PackageInspectorentry={selected}- evidence={evidence}- evidenceLoading={evidenceLoading}- evidenceError={evidenceError}- graphHref={graphHref}+ relationshipsOpen={relationshipsOpen}+ relationships={relationships}+ relationshipsLoading={relationshipsLoading}+ relationshipsError={relationshipsError}+ expandedAggregateKey={expandedAggregateKey}+ importingFiles={importingFiles}+ importingFilesLoading={importingFilesLoading}+ importingFilesError={importingFilesError}+ onShowRelationships={onShowRelationships}+ onHideRelationships={onHideRelationships}+ onRetryRelationships={onRetryRelationships}+ onToggleAggregate={onToggleAggregate}+ onFilesPageChange={onFilesPageChange}+ onRetryImportingFiles={onRetryImportingFiles}renderFileLink={renderFileLink}onClose={() => onSelectedChange(null)}/>diff --git a/packages/ui/src/dependencies/index.ts b/packages/ui/src/dependencies/index.tsindex 739c6e25b..78f9ff960 100644--- a/packages/ui/src/dependencies/index.ts+++ b/packages/ui/src/dependencies/index.ts@@ -10,5 +10,8 @@ export {type ExternalDependencySort,type ExternalDependencyTableState,type ExternalDependencyUsage,- type PackageGraphEvidence,} from "./external-dependencies-table";+export {+ PackageRelationshipGraph,+ type PackageRelationshipGraphProps,+} from "./package-relationship-graph";diff --git a/packages/ui/src/dependencies/package-relationship-graph.tsx b/packages/ui/src/dependencies/package-relationship-graph.tsxnew file mode 100644index 000000000..30fd60a30--- /dev/null+++ b/packages/ui/src/dependencies/package-relationship-graph.tsx@@ -0,0 +1,178 @@+"use client";++import * as React from "react";+import { ArrowLeft, ArrowRight, ChevronLeft, ChevronRight, FileCode2, Network } from "lucide-react";+import type {+ ExternalSystemImportingFiles,+ ExternalSystemRelationshipGraph as RelationshipGraph,+} from "@repowise-dev/types/external-systems";+import { Button } from "../ui/button";++export interface PackageRelationshipGraphProps {+ packageLabel: string;+ graph: RelationshipGraph;+ expandedAggregateKey?: string | null | undefined;+ files?: ExternalSystemImportingFiles | undefined;+ filesLoading?: boolean | undefined;+ filesError?: string | null | undefined;+ renderFileLink?: ((path: string, children: React.ReactNode) => React.ReactNode) | undefined;+ onBack: () => void;+ onToggleAggregate: (aggregateKey: string | null) => void;+ onFilesPageChange: (offset: number) => void;+ onRetryFiles?: (() => void) | undefined;+}++function matchDescription(graph: RelationshipGraph): string {+ if (graph.match_basis === "unresolved") return "No linked external graph target was found.";+ if (graph.match_basis === "mixed") return "Evidence combines multiple graph match methods.";+ if (graph.match_basis === "mapped") return "Evidence uses a persisted package mapping.";+ if (graph.match_basis === "subpath") return "Evidence matched a package subpath.";+ return "Evidence matched the package exactly.";+}++export function PackageRelationshipGraph({+ packageLabel,+ graph,+ expandedAggregateKey,+ files,+ filesLoading,+ filesError,+ renderFileLink,+ onBack,+ onToggleAggregate,+ onFilesPageChange,+ onRetryFiles,+}: PackageRelationshipGraphProps) {+ return (+ <section aria-labelledby="package-relationship-heading" className="space-y-4">+ <div className="flex items-start gap-3">+ <Button variant="ghost" size="sm" onClick={onBack} aria-label="Back to package details">+ <ArrowLeft className="h-4 w-4" />+ </Button>+ <div className="min-w-0">+ <h3 id="package-relationship-heading" className="text-sm font-semibold text-[var(--color-text-primary)]">+ Package relationships+ </h3>+ <p className="mt-1 text-xs text-[var(--color-text-secondary)]">+ {graph.importing_file_total} importing file{graph.importing_file_total === 1 ? "" : "s"} grouped into {graph.aggregate_total} first-party area{graph.aggregate_total === 1 ? "" : "s"}.+ </p>+ </div>+ </div>++ <div+ className="rounded-lg border border-[var(--color-accent-primary)]/35 bg-[var(--color-accent-fill)] px-3 py-3"+ role="group"+ aria-label={`Focused external package ${packageLabel}`}+ >+ <div className="flex items-center gap-2">+ <Network className="h-4 w-4 text-[var(--color-accent-primary)]" />+ <span className="min-w-0 break-words font-mono text-xs font-semibold text-[var(--color-text-primary)]">+ {packageLabel}+ </span>+ </div>+ <p className="mt-1 text-2xs text-[var(--color-text-tertiary)]">+ External package focus · {matchDescription(graph)}+ </p>+ </div>++ {graph.nodes.length ? (+ <ul className="space-y-2 border-l border-[var(--color-border-default)] pl-3" aria-label="First-party areas">+ {graph.nodes.map((node) => {+ const expanded = expandedAggregateKey === node.aggregate_key;+ return (+ <li key={node.aggregate_key}>+ <button+ type="button"+ aria-expanded={expanded}+ onClick={() => onToggleAggregate(expanded ? null : node.aggregate_key)}+ className="group flex w-full items-center gap-2 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-2.5 text-left hover:border-[var(--color-accent-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] motion-reduce:transition-none"+ >+ <span className="min-w-0 flex-1">+ <span className="block break-words text-xs font-medium text-[var(--color-text-primary)]">{node.label}</span>+ <span className="mt-0.5 block text-2xs text-[var(--color-text-tertiary)]">+ {node.importing_file_count} file{node.importing_file_count === 1 ? "" : "s"} · {node.import_edge_count} edge{node.import_edge_count === 1 ? "" : "s"}+ </span>+ </span>+ <ArrowRight className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)] group-hover:text-[var(--color-accent-primary)]" />+ </button>++ {expanded ? (+ <div className="ml-3 border-l border-[var(--color-border-default)] py-3 pl-3">+ {filesLoading && !files ? (+ <p className="text-xs text-[var(--color-text-tertiary)]" role="status">Loading importing files…</p>+ ) : filesError ? (+ <div className="space-y-2" role="alert">+ <p className="text-xs text-[var(--color-text-secondary)]">{filesError}</p>+ {onRetryFiles ? <Button variant="outline" size="sm" onClick={onRetryFiles}>Retry</Button> : null}+ </div>+ ) : files?.items.length ? (+ <>+ <ul className="space-y-2" aria-label={`Importing files in ${node.label}`}>+ {files.items.map((file) => (+ <li key={file.path} className="flex items-start gap-2 text-xs">+ <FileCode2 className="mt-0.5 h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)]" />+ <span className="min-w-0 flex-1 break-all font-mono text-[var(--color-text-secondary)]">+ {renderFileLink ? renderFileLink(file.path, file.path) : file.path}+ </span>+ <span className="shrink-0 text-2xs text-[var(--color-text-tertiary)]">{file.import_edge_count}</span>+ </li>+ ))}+ </ul>+ <div className="mt-3 flex items-center justify-between gap-2 text-2xs text-[var(--color-text-tertiary)]">+ <span>{files.offset + 1}–{files.offset + files.returned} of {files.total}</span>+ <div className="flex gap-1">+ <Button+ variant="outline"+ size="sm"+ aria-label="Previous importing files"+ disabled={files.offset === 0}+ onClick={() => onFilesPageChange(Math.max(0, files.offset - files.limit))}+ >+ <ChevronLeft className="h-3.5 w-3.5" />+ </Button>+ <Button+ variant="outline"+ size="sm"+ aria-label="Next importing files"+ disabled={!files.truncated}+ onClick={() => onFilesPageChange(files.offset + files.limit)}+ >+ <ChevronRight className="h-3.5 w-3.5" />+ </Button>+ </div>+ </div>+ </>+ ) : (+ <p className="text-xs text-[var(--color-text-tertiary)]">No importing files were returned for this area.</p>+ )}+ </div>+ ) : null}+ </li>+ );+ })}+ </ul>+ ) : (+ <div className="rounded-lg border border-dashed border-[var(--color-border-default)] px-4 py-5 text-center">+ <p className="text-sm font-medium text-[var(--color-text-primary)]">No relationship evidence</p>+ <p className="mt-1 text-xs text-[var(--color-text-tertiary)]">+ {graph.match_basis === "unresolved"+ ? "This declared package is not linked to a persisted external graph target."+ : "The linked graph target has no persisted first-party import edges in this scope."}+ </p>+ </div>+ )}++ {(graph.truncated || graph.matched_external_nodes_truncated) ? (+ <p className="rounded-md bg-[var(--color-bg-elevated)] px-3 py-2 text-xs text-[var(--color-text-secondary)]" role="status">+ Showing {graph.aggregate_returned} of {graph.aggregate_total} areas and {graph.edge_returned} of {graph.edge_total} relationships. Limits: {graph.node_limit} areas and {graph.edge_limit} edges.+ {graph.matched_external_nodes_truncated ? ` Showing ${graph.matched_external_nodes.length} of ${graph.matched_external_nodes_total} matched external targets.` : ""}+ {graph.evidence_truncated ? ` Import evidence is partial because more than ${graph.evidence_target_limit} external targets matched.` : ""}+ </p>+ ) : (+ <p className="text-2xs text-[var(--color-text-tertiary)]">+ {graph.aggregate_returned} area{graph.aggregate_returned === 1 ? "" : "s"} · {graph.edge_returned} relationship{graph.edge_returned === 1 ? "" : "s"} · bounded to {graph.node_limit} areas / {graph.edge_limit} edges+ </p>+ )}+ </section>+ );+}diff --git a/packages/web/src/components/architecture/dependencies-view.integration.test.tsx b/packages/web/src/components/architecture/dependencies-view.integration.test.tsxindex 19ae859fd..a2965646e 100644--- a/packages/web/src/components/architecture/dependencies-view.integration.test.tsx+++ b/packages/web/src/components/architecture/dependencies-view.integration.test.tsx@@ -12,6 +12,11 @@ const mocks = vi.hoisted(() => ({infiniteResult: {} as Record<string, unknown>,focusedResult: {} as Record<string, unknown>,summaryKey: "",+ queryValues: {} as Record<string, unknown>,+ swrCalls: [] as Array<{ key: string | null; fetcher: () => Promise<unknown> }>,+ autoFetchFiles: false,+ tableProps: {} as Record<string, unknown>,+ apiGet: vi.fn(),}));vi.mock("next/link", () => ({@@ -31,10 +36,11 @@ vi.mock("nuqs", () => {parseAsInteger: parser(),parseAsString: parser(),parseAsStringLiteral: () => parser(),- useQueryState: (name: string, value: { defaultValue?: unknown }) => [- value?.defaultValue ?? null,- name === "package" ? mocks.setPackage : mocks.setScope,- ],+ useQueryState: (name: string, value: { defaultValue?: unknown }) => {+ const current = name in mocks.queryValues ? mocks.queryValues[name] : value?.defaultValue ?? null;+ const setter = name === "package" ? mocks.setPackage : name === "scope" ? mocks.setScope : vi.fn();+ return [current, setter];+ },useQueryStates: (config: Record<string, { defaultValue?: unknown }>) => [Object.fromEntries(Object.entries(config).map(([key, value]) => [key, value.defaultValue])),mocks.setQueryStates,@@ -49,8 +55,14 @@ vi.mock("swr/infinite", () => ({},}));-vi.mock("swr", () => ({ default: () => mocks.focusedResult }));-vi.mock("@repowise-dev/api-client", () => ({ apiGet: vi.fn() }));+vi.mock("swr", () => ({+ default: (key: string | null, fetcher: () => Promise<unknown>) => {+ mocks.swrCalls.push({ key, fetcher });+ if (mocks.autoFetchFiles && key?.startsWith("external-system-files:")) void fetcher();+ return mocks.focusedResult;+ },+}));+vi.mock("@repowise-dev/api-client", () => ({ apiGet: mocks.apiGet }));vi.mock("@/lib/api/client", () => ({}));vi.mock("@repowise-dev/ui/dependencies", async () => {@@ -62,8 +74,10 @@ vi.mock("@repowise-dev/ui/dependencies", async () => {ExternalDependenciesTable: (props: {onStateChange: (state: typeof actual.DEFAULT_EXTERNAL_DEPENDENCY_STATE) => void;onSelectedChange: (entry: { package_key: string }) => void;+ onShowRelationships: () => void;+ onToggleAggregate: (key: string) => void;}) => (- <div>+ <div ref={() => { mocks.tableProps = props as unknown as Record<string, unknown>; }}><buttononClick={() => props.onStateChange({ ...actual.DEFAULT_EXTERNAL_DEPENDENCY_STATE, query: "react", page: 2 })}>@@ -72,6 +86,8 @@ vi.mock("@repowise-dev/ui/dependencies", async () => {<button onClick={() => props.onSelectedChange({ package_key: "npm:react" })}>Select package</button>+ <button onClick={props.onShowRelationships}>Show relationships</button>+ <button onClick={() => props.onToggleAggregate("community:1")}>Expand area</button></div>),};@@ -82,20 +98,61 @@ import { DependenciesView } from "./dependencies-view";afterEach(cleanup);const summary: ExternalSystemsSummary = {- items: [],- returned: 0,- total_packages: 1,+ items: [+ {+ package_key: "npm:react",+ name: "react",+ display_name: "React",+ ecosystem: "npm",+ category: "framework",+ io_kind: null,+ runtime_declared: true,+ dev_declared: false,+ declaration_count: 1,+ manifest_count: 1,+ versions: ["19"],+ versions_total: 1,+ versions_truncated: false,+ multiple_versions: false,+ external_node_count: 1,+ import_edge_count: 2,+ importing_file_count: 2,+ link_state: "linked",+ },+ {+ package_key: "npm:next",+ name: "next",+ display_name: "Next",+ ecosystem: "npm",+ category: "framework",+ io_kind: null,+ runtime_declared: true,+ dev_declared: false,+ declaration_count: 1,+ manifest_count: 1,+ versions: ["15"],+ versions_total: 1,+ versions_truncated: false,+ multiple_versions: false,+ external_node_count: 1,+ import_edge_count: 1,+ importing_file_count: 1,+ link_state: "linked",+ },+ ],+ returned: 2,+ total_packages: 2,limit: 400,offset: 0,truncated: false,scope: "primary",excluded_declarations: 0,- total_declarations: 1,- runtime_packages: 1,+ total_declarations: 2,+ runtime_packages: 2,dev_only_packages: 0,- observed_packages: 0,- linked_packages: 0,- unlinked_packages: 1,+ observed_packages: 2,+ linked_packages: 2,+ unlinked_packages: 0,linked_without_imports: 0,ecosystems: ["npm"],manifest_count: 1,@@ -104,6 +161,11 @@ const summary: ExternalSystemsSummary = {describe("DependenciesView wiring", () => {beforeEach(() => {vi.clearAllMocks();+ mocks.queryValues = {};+ mocks.swrCalls = [];+ mocks.autoFetchFiles = false;+ mocks.tableProps = {};+ mocks.apiGet.mockResolvedValue({});mocks.infiniteResult = {data: [summary],error: undefined,@@ -119,7 +181,8 @@ describe("DependenciesView wiring", () => {it("starts from the bounded summary key and does not activate a graph request", () => {render(<DependenciesView repoId="repo-id" />);expect(mocks.summaryKey).toBe("external-systems-summary:repo-id:primary:0");- expect(mocks.focusedResult).toEqual({ data: undefined, error: undefined, isLoading: false });+ expect(mocks.swrCalls.filter((call) => call.key !== null)).toHaveLength(0);+ expect(mocks.apiGet).not.toHaveBeenCalled();});it("renders loading and error states", () => {@@ -140,4 +203,69 @@ describe("DependenciesView wiring", () => {fireEvent.click(screen.getByRole("button", { name: "Select package" }));expect(mocks.setPackage).toHaveBeenCalledWith("npm:react");});++ it("restores URL-backed package focus and issues one focused request after interaction", async () => {+ mocks.queryValues = { package: "npm:react", focus: "relationships" };+ render(<DependenciesView repoId="repo-id" />);++ expect(mocks.tableProps.selected).toEqual(expect.objectContaining({ package_key: "npm:react" }));+ expect(mocks.tableProps.relationshipsOpen).toBe(true);+ const active = mocks.swrCalls.filter((call) => call.key?.startsWith("external-system-relationships:"));+ expect(active).toHaveLength(1);+ await active[0]!.fetcher();+ expect(mocks.apiGet).toHaveBeenCalledTimes(1);+ expect(mocks.apiGet.mock.calls[0]![0]).toContain("/external-systems/npm%3Areact/graph");+ expect(mocks.apiGet.mock.calls[0]![0]).not.toContain("/api/graph/");+ });++ it("cancels a stale focused request when package identity changes", () => {+ mocks.queryValues = { package: "npm:react", focus: "relationships" };+ const { rerender } = render(<DependenciesView repoId="repo-id" />);+ const firstFetcher = mocks.swrCalls.find((call) => call.key?.includes("npm:react"))!.fetcher;+ void firstFetcher();+ const firstSignal = (mocks.apiGet.mock.calls[0]![2] as { signal: AbortSignal }).signal;+ expect(firstSignal.aborted).toBe(false);++ mocks.queryValues = { package: "npm:next", focus: "relationships" };+ mocks.swrCalls = [];+ rerender(<DependenciesView repoId="repo-id" />);+ expect(firstSignal.aborted).toBe(true);+ expect(mocks.swrCalls.some((call) => call.key?.includes("npm:next"))).toBe(true);+ });++ it("keeps importing-file requests independently bounded", async () => {+ mocks.queryValues = {+ package: "npm:react",+ focus: "relationships",+ area: "community:1",+ fileOffset: 25,+ };+ render(<DependenciesView repoId="repo-id" />);+ const files = mocks.swrCalls.find((call) => call.key?.startsWith("external-system-files:"));+ expect(files).toBeDefined();+ await files!.fetcher();+ expect(mocks.apiGet).toHaveBeenCalledWith(+ expect.stringContaining("/graph/files"),+ expect.objectContaining({ aggregate_key: "community:1", limit: 25, offset: 25 }),+ expect.objectContaining({ signal: expect.any(AbortSignal) }),+ );+ });++ it("does not cancel a newly started file request when an area is expanded", () => {+ mocks.queryValues = { package: "npm:react", focus: "relationships" };+ const { rerender } = render(<DependenciesView repoId="repo-id" />);++ mocks.autoFetchFiles = true;+ mocks.queryValues = {+ package: "npm:react",+ focus: "relationships",+ area: "community:1",+ };+ rerender(<DependenciesView repoId="repo-id" />);++ const fileCall = mocks.apiGet.mock.calls.find(([path]) => String(path).includes("/graph/files"));+ expect(fileCall).toBeDefined();+ const signal = (fileCall![2] as { signal: AbortSignal }).signal;+ expect(signal.aborted).toBe(false);+ });});diff --git a/packages/web/src/components/architecture/dependencies-view.test.ts b/packages/web/src/components/architecture/dependencies-view.test.tsindex a8c210f32..07586e2f1 100644--- a/packages/web/src/components/architecture/dependencies-view.test.ts+++ b/packages/web/src/components/architecture/dependencies-view.test.ts@@ -1,7 +1,5 @@import { describe, expect, it } from "vitest";-import type { NodeSearchResult } from "../../lib/api/types";import {- chooseExternalPackageNode,packageSummaryRequest,PACKAGE_SUMMARY_LIMIT,} from "./package-graph";@@ -11,38 +9,6 @@ import {tableStateFromQuery,} from "./package-query-state";-function candidate(node_id: string): NodeSearchResult {- return { node_id, language: "", symbol_count: 0 };-}--describe("chooseExternalPackageNode", () => {- it("prefers the exact package node over subpaths and fuzzy matches", () => {- expect(- chooseExternalPackageNode(- [candidate("external:react-dom"), candidate("external:react/jsx-runtime"), candidate("external:react")],- "react",- ),- ).toBe("external:react");- });-- it("falls back to a package subpath and ignores repository files", () => {- expect(- chooseExternalPackageNode(- [candidate("packages/react/index.ts"), candidate("external:@scope/pkg/subpath")],- "@scope/pkg",- ),- ).toBe("external:@scope/pkg/subpath");- });-- it("returns null when node search has no external match", () => {- expect(chooseExternalPackageNode([candidate("src/pkg.py")], "pkg")).toBeNull();- });-- it("does not fuzzy-focus a sibling package", () => {- expect(chooseExternalPackageNode([candidate("external:react-dom")], "react")).toBeNull();- });-});-describe("package query state", () => {it("round-trips shareable filter, sort, and page state", () => {const state = tableStateFromQuery({diff --git a/packages/web/src/components/architecture/dependencies-view.tsx b/packages/web/src/components/architecture/dependencies-view.tsxindex 93d625976..b108cb243 100644--- a/packages/web/src/components/architecture/dependencies-view.tsx+++ b/packages/web/src/components/architecture/dependencies-view.tsx@@ -15,21 +15,20 @@ import {import {ExternalDependenciesTable,type ExternalDependencyTableState,- type PackageGraphEvidence,} from "@repowise-dev/ui/dependencies";import { ApiError } from "@repowise-dev/ui/shared/api-error";import { fileEntityPath } from "@repowise-dev/ui/shared/entity";import { Skeleton } from "@repowise-dev/ui/ui/skeleton";import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";import type {+ ExternalSystemImportingFiles,+ ExternalSystemRelationshipGraph,ExternalSystemSummaryEntry,ExternalSystemsSummary,} from "@repowise-dev/types/external-systems";import { apiGet } from "@repowise-dev/api-client";-import type { EgoGraphResponse, NodeSearchResult } from "@/lib/api/types";import "@/lib/api/client";import {- chooseExternalPackageNode,packageSummaryRequest,PACKAGE_SUMMARY_LIMIT,} from "./package-graph";@@ -40,49 +39,26 @@ const USAGE_STATES = ["all", "observed", "linked-unobserved", "unlinked"] as conconst SORTS = ["importers", "edges", "name", "declarations", "manifests", "versions"] as const;const ORDERS = ["asc", "desc"] as const;const SCOPES = ["primary", "all"] as const;+const FOCUSES = ["relationships"] as const;+const FILE_PAGE_LIMIT = 25;-async function getFocusedPackageEvidence(- repoId: string,- entry: ExternalSystemSummaryEntry,- signal: AbortSignal,-): Promise<PackageGraphEvidence> {- const candidates = await apiGet<NodeSearchResult[]>(- `/api/graph/${repoId}/nodes/search`,- { q: entry.name, limit: 20 },- { signal },- );- const centerNodeId = chooseExternalPackageNode(candidates, entry.name);- if (!centerNodeId) throw new Error("No matching external graph node was returned for this package.");-- const ego = await apiGet<EgoGraphResponse>(- `/api/graph/${repoId}/ego`,- { node_id: centerNodeId, hops: 1 },- { signal },- );- const importingFiles = [- ...new Set(- ego.links- .filter((link) => link.target === centerNodeId && link.source !== centerNodeId)- .map((link) => link.source),- ),- ].sort();-- return {- centerNodeId,- importingFiles,- importEdgeCount: ego.links.filter((link) => link.target === centerNodeId).length,- totalNodes: ego.nodes.length,- };+interface ActiveRequest {+ identity: string;+ controller: AbortController;}export function DependenciesView({ repoId }: { repoId: string }) {const summaryAbortRef = useRef<AbortController | null>(null);- const evidenceAbortRef = useRef<AbortController | null>(null);+ const relationshipsAbortRef = useRef<ActiveRequest | null>(null);+ const filesAbortRef = useRef<ActiveRequest | null>(null);const [scope, setScope] = useQueryState("scope",parseAsStringLiteral(SCOPES).withDefault("primary"),);const [selectedKey, setSelectedKey] = useQueryState("package", parseAsString);+ const [focus, setFocus] = useQueryState("focus", parseAsStringLiteral(FOCUSES));+ const [aggregateKey, setAggregateKey] = useQueryState("area", parseAsString);+ const [fileOffset, setFileOffset] = useQueryState("fileOffset", parseAsInteger.withDefault(0));const [queryState, setQueryState] = useQueryStates({q: parseAsString.withDefault(""),ecosystem: parseAsString.withDefault("all"),@@ -145,33 +121,94 @@ export function DependenciesView({ repoId }: { repoId: string }) {[data?.items, selectedKey],);- // Focused graph evidence is deliberately dormant on the initial page.- // Selecting a linked row activates node search plus a one-hop ego request.- const fetchEvidence = useCallback(() => {- evidenceAbortRef.current?.abort();+ // A shared URL can point at a package beyond the first bounded summary page.+ // Walk only the existing summary pages until it is found; relationship data+ // remains dormant until both package and focus have been restored.+ useEffect(() => {+ if (selectedKey && data && !selected && data.truncated && !summaryValidating) {+ void setSize(size + 1);+ }+ }, [data, selected, selectedKey, setSize, size, summaryValidating]);++ const relationshipRequestIdentity =+ selected && focus === "relationships" ? `${repoId}:${scope}:${selected.package_key}` : null;++ // Relationship reads stay dormant until the inspector's explicit action.+ const fetchRelationships = useCallback(() => {+ relationshipsAbortRef.current?.controller.abort();const controller = new AbortController();- evidenceAbortRef.current = controller;- return getFocusedPackageEvidence(repoId, selected!, controller.signal);- }, [repoId, selected]);+ relationshipsAbortRef.current = { identity: relationshipRequestIdentity!, controller };+ return apiGet<ExternalSystemRelationshipGraph>(+ `/api/repos/${repoId}/external-systems/${encodeURIComponent(selected!.package_key)}/graph`,+ { scope, node_limit: 50, edge_limit: 200 },+ { signal: controller.signal },+ );+ }, [relationshipRequestIdentity, repoId, scope, selected]);const {- data: evidence,- error: evidenceError,- isLoading: evidenceLoading,+ data: relationships,+ error: relationshipsError,+ isLoading: relationshipsLoading,+ mutate: retryRelationships,} = useSWR(- selected?.link_state === "linked"- ? `external-system-evidence:${repoId}:${selected.package_key}`+ selected && focus === "relationships"+ ? `external-system-relationships:${repoId}:${scope}:${selected.package_key}`: null,- fetchEvidence,+ fetchRelationships,{ revalidateOnFocus: false, revalidateOnReconnect: false },);- useEffect(() => {- if (!selected || selected.link_state !== "linked") evidenceAbortRef.current?.abort();- }, [selected]);+ const fileRequestIdentity =+ relationshipRequestIdentity && aggregateKey+ ? `${relationshipRequestIdentity}:${aggregateKey}:${fileOffset}`+ : null;++ const fetchImportingFiles = useCallback(() => {+ filesAbortRef.current?.controller.abort();+ const controller = new AbortController();+ filesAbortRef.current = { identity: fileRequestIdentity!, controller };+ return apiGet<ExternalSystemImportingFiles>(+ `/api/repos/${repoId}/external-systems/${encodeURIComponent(selected!.package_key)}/graph/files`,+ {+ scope,+ aggregate_key: aggregateKey!,+ limit: FILE_PAGE_LIMIT,+ offset: fileOffset,+ },+ { signal: controller.signal },+ );+ }, [aggregateKey, fileOffset, fileRequestIdentity, repoId, scope, selected]);+ const {+ data: importingFiles,+ error: importingFilesError,+ isLoading: importingFilesLoading,+ mutate: retryImportingFiles,+ } = useSWR(+ selected && focus === "relationships" && aggregateKey+ ? `external-system-files:${repoId}:${scope}:${selected.package_key}:${aggregateKey}:${fileOffset}`+ : null,+ fetchImportingFiles,+ { revalidateOnFocus: false, revalidateOnReconnect: false },+ );++ useEffect(() => () => {+ const active = relationshipsAbortRef.current;+ if (active?.identity === relationshipRequestIdentity) {+ active.controller.abort();+ relationshipsAbortRef.current = null;+ }+ }, [relationshipRequestIdentity]);+ useEffect(() => () => {+ const active = filesAbortRef.current;+ if (active?.identity === fileRequestIdentity) {+ active.controller.abort();+ filesAbortRef.current = null;+ }+ }, [fileRequestIdentity]);useEffect(() => () => {summaryAbortRef.current?.abort();- evidenceAbortRef.current?.abort();+ relationshipsAbortRef.current?.controller.abort();+ filesAbortRef.current?.controller.abort();},[],);@@ -202,6 +239,8 @@ export function DependenciesView({ repoId }: { repoId: string }) {onChange={(event) => {void setScope(event.target.checked ? "all" : "primary");void setSelectedKey(null);+ void setFocus(null);+ void setAggregateKey(null);handleTableStateChange({ ...tableState, page: 1 });}}className="h-4 w-4 rounded border-[var(--color-border-default)] accent-[var(--color-accent-primary)]"@@ -236,19 +275,41 @@ export function DependenciesView({ repoId }: { repoId: string }) {state={tableState}onStateChange={handleTableStateChange}selected={selected}- onSelectedChange={(entry) => void setSelectedKey(entry?.package_key ?? null)}- evidence={evidence}- evidenceLoading={evidenceLoading}- evidenceError={- evidenceError- ? `Focused graph evidence couldn't be loaded: ${toFriendlyMessage(evidenceError)}`+ onSelectedChange={(entry) => {+ void setSelectedKey(entry?.package_key ?? null);+ void setFocus(null);+ void setAggregateKey(null);+ void setFileOffset(0);+ }}+ relationshipsOpen={focus === "relationships"}+ relationships={relationships}+ relationshipsLoading={relationshipsLoading}+ relationshipsError={+ relationshipsError+ ? `Package relationships couldn't be loaded: ${toFriendlyMessage(relationshipsError)}`: null}- graphHref={- evidence- ? `/repos/${repoId}/architecture?view=files&node=${encodeURIComponent(evidence.centerNodeId)}`- : undefined+ expandedAggregateKey={aggregateKey}+ importingFiles={importingFiles}+ importingFilesLoading={importingFilesLoading}+ importingFilesError={+ importingFilesError+ ? `Importing files couldn't be loaded: ${toFriendlyMessage(importingFilesError)}`+ : null}+ onShowRelationships={() => void setFocus("relationships")}+ onHideRelationships={() => {+ void setFocus(null);+ void setAggregateKey(null);+ void setFileOffset(0);+ }}+ onRetryRelationships={() => void retryRelationships()}+ onToggleAggregate={(key) => {+ void setAggregateKey(key);+ void setFileOffset(0);+ }}+ onFilesPageChange={(offset) => void setFileOffset(offset)}+ onRetryImportingFiles={() => void retryImportingFiles()}renderFileLink={(path, children) => (<Linkhref={fileEntityPath(`/repos/${repoId}`, path)}diff --git a/packages/web/src/components/architecture/package-graph.ts b/packages/web/src/components/architecture/package-graph.tsindex 26db4e5e5..710770f24 100644--- a/packages/web/src/components/architecture/package-graph.ts+++ b/packages/web/src/components/architecture/package-graph.ts@@ -1,4 +1,3 @@-import type { NodeSearchResult } from "../../lib/api/types";import type { ExternalSystemsSummaryScope } from "@repowise-dev/types/external-systems";export const PACKAGE_SUMMARY_LIMIT = 400;@@ -9,23 +8,3 @@ export function packageSummaryRequest(repoId: string, scope: ExternalSystemsSummparams: { scope, limit: PACKAGE_SUMMARY_LIMIT },} as const;}--function externalCandidateScore(candidate: NodeSearchResult, packageName: string): number {- const nodeId = candidate.node_id.toLowerCase();- const expected = `external:${packageName}`.toLowerCase();- if (nodeId === expected) return 3;- if (nodeId.startsWith(`${expected}/`) || nodeId.startsWith(`${expected}:`)) return 2;- return 0;-}--export function chooseExternalPackageNode(- candidates: NodeSearchResult[],- packageName: string,-): string | null {- return candidates- .filter((candidate) => candidate.node_id.startsWith("external:"))- .map((candidate) => ({ candidate, score: externalCandidateScore(candidate, packageName) }))- .filter(({ score }) => score > 0)- .sort((a, b) => b.score - a.score || a.candidate.node_id.localeCompare(b.candidate.node_id))[0]- ?.candidate.node_id ?? null;-}diff --git a/tests/unit/server/test_external_systems.py b/tests/unit/server/test_external_systems.pyindex 1c312f35d..668a94707 100644--- a/tests/unit/server/test_external_systems.py+++ b/tests/unit/server/test_external_systems.py@@ -131,6 +131,48 @@ async def _seed_summary(session_factory, repo_id: str) -> None:session.add_all([+ GraphNode(+ repository_id=repo_id,+ node_id="src/a.ts",+ language="typescript",+ community_id=1,+ community_meta_json='{"label":"Web runtime"}',+ ),+ GraphNode(+ repository_id=repo_id,+ node_id="src/b.ts",+ language="typescript",+ community_id=2,+ community_meta_json='{"label":"Shared UI"}',+ ),+ GraphNode(+ repository_id=repo_id,+ node_id="src/dialog.ts",+ language="typescript",+ community_id=1,+ community_meta_json='{"label":"Web runtime"}',+ ),+ GraphNode(+ repository_id=repo_id,+ node_id="src/lib.rs",+ language="rust",+ community_id=3,+ community_meta_json='{"label":"Core"}',+ ),+ GraphNode(+ repository_id=repo_id,+ node_id="src/page.ts",+ language="typescript",+ community_id=1,+ community_meta_json='{"label":"Web runtime"}',+ ),+ GraphNode(+ repository_id=repo_id,+ node_id=".claude/worktrees/demo/src/a.ts",+ language="typescript",+ community_id=4,+ community_meta_json='{"label":"Auxiliary"}',+ ),GraphNode(repository_id=repo_id,node_id="external:react",@@ -516,3 +558,219 @@ async def test_summary_empty(client: AsyncClient) -> None:"ecosystems": [],"manifest_count": 0,}+++async def test_relationship_graph_is_aggregate_first_bounded_and_honest(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ await _seed_summary(app.state.session_factory, repo["id"])++ response = await client.get(+ f"/api/repos/{repo['id']}/external-systems/npm:react/graph?node_limit=1&edge_limit=1"+ )++ assert response.status_code == 200+ data = response.json()+ assert data["package_key"] == "npm:react"+ assert data["package_node_id"] == "package:npm:react"+ assert data["match_basis"] == "mixed"+ assert data["matched_external_nodes_total"] == 2+ assert data["evidence_target_limit"] == 200+ assert data["evidence_truncated"] is False+ assert {target["match_basis"] for target in data["matched_external_nodes"]} == {+ "exact",+ "subpath",+ }+ assert data["aggregate_total"] == 2+ assert data["aggregate_returned"] == 1+ assert data["edge_total"] == 2+ assert data["edge_returned"] == 1+ assert data["importing_file_total"] == 2+ assert data["import_edge_total"] == 3+ assert data["truncated"] is True+ assert data["nodes"][0] == {+ "aggregate_key": "community:1",+ "label": "Web runtime",+ "community_id": 1,+ "importing_file_count": 1,+ "import_edge_count": 2,+ "top_file": "src/a.ts",+ }+ assert data["edges"] == [+ {+ "source": "community:1",+ "target": "package:npm:react",+ "import_edge_count": 2,+ }+ ]+++async def test_relationship_graph_handles_unresolved_missing_and_scoped_packages(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ await _seed_summary(app.state.session_factory, repo["id"])++ unresolved = (+ await client.get(f"/api/repos/{repo['id']}/external-systems/npm:vitest/graph")+ ).json()+ assert unresolved["match_basis"] == "unresolved"+ assert unresolved["matched_external_nodes"] == []+ assert unresolved["nodes"] == []+ assert unresolved["importing_file_total"] == 0+ assert unresolved["truncated"] is False++ scoped = await client.get(+ f"/api/repos/{repo['id']}/external-systems/npm:%40radix-ui%2Freact-dialog/graph"+ )+ assert scoped.status_code == 200+ assert scoped.json()["package_key"] == "npm:@radix-ui/react-dialog"+ assert scoped.json()["match_basis"] == "subpath"++ missing = await client.get(f"/api/repos/{repo['id']}/external-systems/npm:not-declared/graph")+ assert missing.status_code == 404+++async def test_relationship_file_expansion_is_independently_bounded_and_paginated(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ await _seed_summary(app.state.session_factory, repo["id"])++ first = (+ await client.get(+ f"/api/repos/{repo['id']}/external-systems/npm:react/graph/files",+ params={"aggregate_key": "community:1", "limit": 1},+ )+ ).json()+ assert first["total"] == 1+ assert first["returned"] == 1+ assert first["items"][0] == {+ "path": "src/a.ts",+ "language": "typescript",+ "import_edge_count": 2,+ "matched_external_node_count": 2,+ }+ assert first["truncated"] is False++ second = (+ await client.get(+ f"/api/repos/{repo['id']}/external-systems/npm:react/graph/files",+ params={"aggregate_key": "community:2", "limit": 1, "offset": 1},+ )+ ).json()+ assert second["total"] == 1+ assert second["items"] == []+ assert second["truncated"] is False++ invalid = await client.get(+ f"/api/repos/{repo['id']}/external-systems/npm:react/graph/files",+ params={"aggregate_key": "directory:src"},+ )+ assert invalid.status_code == 422+ too_large = await client.get(+ f"/api/repos/{repo['id']}/external-systems/npm:react/graph/files",+ params={"aggregate_key": "community:1", "limit": 101},+ )+ assert too_large.status_code == 422++ missing = await client.get(+ f"/api/repos/{repo['id']}/external-systems/npm:not-declared/graph/files",+ params={"aggregate_key": "community:1"},+ )+ assert missing.status_code == 404+++async def test_relationship_graph_and_expansion_share_the_same_capped_target_evidence(+ client: AsyncClient, app+) -> None:+ repo = await create_test_repo(client)+ async with get_session(app.state.session_factory) as session:+ package = ExternalSystem(+ repository_id=repo["id"],+ name="many-targets",+ display_name="Many targets",+ ecosystem="npm",+ category="library",+ declared_in="package.json",+ is_dev_dep=False,+ )+ session.add(package)+ await session.flush()+ session.add_all(+ [+ GraphNode(+ repository_id=repo["id"],+ node_id=f"external:many-targets/{index:03}",+ node_type="external",+ language="external",+ external_system_id=package.id,+ )+ for index in range(201)+ ]+ + [+ GraphNode(+ repository_id=repo["id"],+ node_id=f"src/file-{index:03}.ts",+ language="typescript",+ community_id=9,+ community_meta_json='{"label":"Many consumers"}',+ )+ for index in range(201)+ ]+ )+ session.add_all(+ GraphEdge(+ repository_id=repo["id"],+ source_node_id=f"src/file-{index:03}.ts",+ target_node_id=f"external:many-targets/{index:03}",+ edge_type="imports",+ )+ for index in range(201)+ )+ await session.flush()++ graph = (+ await client.get(f"/api/repos/{repo['id']}/external-systems/npm:many-targets/graph")+ ).json()+ assert graph["matched_external_nodes_total"] == 201+ assert graph["evidence_target_limit"] == 200+ assert graph["evidence_truncated"] is True+ assert graph["importing_file_total"] == 200++ files = (+ await client.get(+ f"/api/repos/{repo['id']}/external-systems/npm:many-targets/graph/files",+ params={"aggregate_key": "community:9", "limit": 100},+ )+ ).json()+ assert files["total"] == 200+ assert files["returned"] == 100+ assert files["truncated"] is True+++async def test_relationship_graph_query_count_is_constant(+ client: AsyncClient, app, test_engine+) -> None:+ repo = await create_test_repo(client)+ await _seed_summary(app.state.session_factory, repo["id"])+ statements: list[str] = []++ def record(_conn, _cursor, statement, _parameters, _context, _executemany) -> None:+ statements.append(statement)++ event.listen(test_engine.sync_engine, "before_cursor_execute", record)+ try:+ response = await client.get(f"/api/repos/{repo['id']}/external-systems/npm:react/graph")+ finally:+ event.remove(test_engine.sync_engine, "before_cursor_execute", record)++ assert response.status_code == 200+ selects = [statement for statement in statements if statement.lstrip().startswith("SELECT")]+ assert len(selects) == 2