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.

fix(ingestion): ignore TypeScript type-only imports in dependency cycle detection (#2803)

Rishabh Mishra4d0e4163c7a5
diff --git a/packages/core/alembic/versions/0096_graph_edge_type_only.py b/packages/core/alembic/versions/0096_graph_edge_type_only.py
new file mode 100644
index 000000000..8b8e3a240
--- /dev/null
+++ b/packages/core/alembic/versions/0096_graph_edge_type_only.py
@@ -0,0 +1,46 @@
+"""Persist ``graph_edges.type_only`` so type-only import cycles stay suppressed.
+
+TypeScript ``import type`` and type-only re-exports are stripped by the compiler
+and cannot cause runtime module evaluation deadlocks. Cycle detection drops
+these edges to avoid reporting harmless type-level cycles.
+
+Persisting ``type_only`` ensures that a graph rehydrated from SQL (e.g. during
+incremental update or rescoring) maintains the type-only mark rather than
+re-reporting false positive cycles.
+
+Local SQLite stores get the column from ``init_db``'s additive reconciler; this
+migration covers managed Postgres.
+
+Revision ID: 0096
+Revises: 0095
+Create Date: 2026-10-03
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0096"
+down_revision: str | None = "0095"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "graph_edges",
+ sa.Column(
+ "type_only",
+ sa.Boolean(),
+ nullable=False,
+ server_default=sa.text("false"),
+ ),
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("graph_edges", "type_only")
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py b/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py
index 65782e5d7..2bb0c444f 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py
@@ -46,7 +46,11 @@ _CYCLE_EDGE_TYPES = FILE_DEPENDENCY_EDGE_TYPES
def _is_cycle_edge(data: Any) -> bool:
"""True if *data* is a file-level edge that can legitimately close a cycle."""
- return data.get("edge_type") in _CYCLE_EDGE_TYPES and not is_cohesion_edge(data)
+ return (
+ data.get("edge_type") in _CYCLE_EDGE_TYPES
+ and not is_cohesion_edge(data)
+ and not data.get("type_only")
+ )
def build_file_scc_index(graph: Any) -> dict[str, tuple[str, ...]]:
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py
index 1dbac76df..c27a8149e 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py
@@ -414,3 +414,47 @@ def cjs_statement_is_reexport(stmt_node: Node, src: str) -> bool:
head = node_text(ctx, src).split("require", 1)[0]
stripped = head.lstrip()
return "module.exports" in head or stripped.startswith("exports.")
+
+
+def is_type_only_ts_js_import(stmt_node: Node, src: str) -> bool:
+ """True if a TypeScript import or re-export is purely type-level.
+
+ Handles:
+ - Statement-level: ``import type { X } from '...'``, ``export type { X } from '...'``
+ - Clause-level / Specifier-level: ``import { type A, type B } from '...'``
+ Mixed statements with value imports (``import { type A, B } from '...'``) return False.
+ """
+ if any(
+ child.type == "type"
+ or (child.type in ("identifier", "ERROR") and node_text(child, src) == "type")
+ for child in stmt_node.children
+ ):
+ return True
+
+ specifiers: list[Node] = []
+ has_non_specifier_import = False
+
+ for child in stmt_node.children:
+ if child.type == "import_clause":
+ for sub in child.children:
+ if sub.type in ("identifier", "namespace_import"):
+ has_non_specifier_import = True
+ elif sub.type == "named_imports":
+ for spec in sub.children:
+ if spec.type == "import_specifier":
+ specifiers.append(spec)
+ elif child.type == "export_clause":
+ for spec in child.children:
+ if spec.type == "export_specifier":
+ specifiers.append(spec)
+ elif child.type == "namespace_export":
+ has_non_specifier_import = True
+
+ if has_non_specifier_import or not specifiers:
+ return False
+
+ return all(
+ any(c.type == "type" or node_text(c, src) == "type" for c in spec.children)
+ for spec in specifiers
+ )
+
diff --git a/packages/core/src/repowise/core/ingestion/graph/_metrics.py b/packages/core/src/repowise/core/ingestion/graph/_metrics.py
index 56ac383bb..761b87bc0 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_metrics.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_metrics.py
@@ -150,7 +150,8 @@ class MetricsMixin:
only ever read. Callers must treat the result as read-only.
"""
return self._file_edge_view(
- "_cycle_subgraph_cache", lambda base, u, v, d: is_cohesion_edge(d)
+ "_cycle_subgraph_cache",
+ lambda base, u, v, d: is_cohesion_edge(d) or d.get("type_only") is True,
)
def centrality_subgraph(self) -> nx.DiGraph:
diff --git a/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py b/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
index eb7d28452..7ed2a9758 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
@@ -122,6 +122,8 @@ class RehydrateMixin:
supplied_props = edge.get("supplied_props")
if supplied_props is not None:
edge_attrs["supplied_props"] = frozenset(supplied_props)
+ if edge.get("type_only"):
+ edge_attrs["type_only"] = True
graph.add_edge(source, target, **edge_attrs)
edge_count += 1
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index da99f99b8..2883a695a 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -477,10 +477,15 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
self._graph[path][target]["imported_names"] = merged
if not imp.is_module_declaration:
withdraw_declaration_hint(self._graph[path][target])
+ self._graph[path][target]["type_only"] = (
+ bool(self._graph[path][target].get("type_only", False))
+ and imp.type_only
+ )
else:
edge_attrs: dict[str, Any] = {
"edge_type": "imports",
"imported_names": list(imp.imported_names),
+ "type_only": imp.type_only,
}
# ``external:`` targets are excluded before the
# directory test, not after: an external node id has no
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index bbb5c1587..3f7a03a7a 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -267,6 +267,7 @@ class Import:
is_reexport: bool = False # True for `pub use` (Rust) or re-export patterns
# Rust ``mod child;``: declares the child module, uses nothing from it.
is_module_declaration: bool = False
+ type_only: bool = False # True when the statement is purely type-level (e.g. TypeScript import type)
@property
def local_names(self) -> list[str]:
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index fd1d3343e..c71b10f70 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -1201,6 +1201,12 @@ def _generic_import(
or module_text.startswith("./")
or module_text.startswith(("self::", "super::", "crate::"))
)
+ type_only = False
+ if language in _TS_JS_LANGUAGES:
+ from .extractors.bindings.ts_js import is_type_only_ts_js_import
+
+ type_only = is_type_only_ts_js_import(stmt_node, src)
+
return Import(
raw_statement=raw,
module_path=module_text,
@@ -1210,6 +1216,7 @@ def _generic_import(
bindings=bindings,
is_reexport=_is_reexport_import(stmt_node, raw, language),
is_module_declaration=is_module_declaration,
+ type_only=type_only,
)
diff --git a/packages/core/src/repowise/core/persistence/crud/graph.py b/packages/core/src/repowise/core/persistence/crud/graph.py
index 19f38cc66..b79e5345d 100644
--- a/packages/core/src/repowise/core/persistence/crud/graph.py
+++ b/packages/core/src/repowise/core/persistence/crud/graph.py
@@ -92,6 +92,9 @@ def _update_graph_edge(existing: GraphEdge, edge_data: dict) -> None:
call_lines = edge_data.get("call_lines_json")
if call_lines is not None:
existing.call_lines_json = call_lines
+ type_only = edge_data.get("type_only")
+ if type_only is not None:
+ existing.type_only = bool(type_only)
confidence = edge_data.get("confidence")
if confidence is not None:
# Keep the max on collision, mirroring the in-memory resolver
@@ -118,6 +121,7 @@ def _edge_values(repository_id: str, e: dict) -> dict:
"hint_source": e.get("hint_source"),
"resolution_origin": e.get("resolution_origin"),
"call_lines_json": e.get("call_lines_json", "[]"),
+ "type_only": bool(e.get("type_only", False)),
}
@@ -527,6 +531,7 @@ async def get_all_graph_edges(
"hint_source": row.hint_source,
"resolution_origin": row.resolution_origin,
"call_lines": call_lines,
+ "type_only": bool(row.type_only),
}
)
return edges
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index b0b02e024..d9d38e0fa 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -404,6 +404,12 @@ class GraphEdge(Base):
call_lines_json: Mapped[str] = mapped_column(
Text, nullable=False, default="[]", server_default="[]"
)
+ # True when an import edge is purely type-level (e.g. TypeScript `import type`).
+ # Cycle detection skips these edges so mutual type imports are not flagged.
+ # Persisted so graphs rehydrated on incremental updates or rescores preserve it.
+ type_only: Mapped[bool] = mapped_column(
+ Boolean, nullable=False, default=False, server_default=false()
+ )
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=_now_utc
)
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index 5e3cab2cf..15a4dec62 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -666,6 +666,7 @@ def _changed_file_edges(
"hint_source": data.get("hint_source"),
"resolution_origin": data.get("resolution_origin"),
"call_lines_json": json.dumps(data.get("call_lines", [])),
+ "type_only": bool(data.get("type_only", False)),
}
)
return sorted(reconcile), edges
@@ -1616,6 +1617,7 @@ async def persist_ingestion(result: Any, session: Any, repo_id: str) -> int:
"hint_source": data.get("hint_source"),
"resolution_origin": data.get("resolution_origin"),
"call_lines_json": json.dumps(data.get("call_lines", [])),
+ "type_only": bool(data.get("type_only", False)),
}
)
if edges:
diff --git a/tests/unit/health/test_refactoring_break_cycle.py b/tests/unit/health/test_refactoring_break_cycle.py
index 3ea69821a..5f252f185 100644
--- a/tests/unit/health/test_refactoring_break_cycle.py
+++ b/tests/unit/health/test_refactoring_break_cycle.py
@@ -271,3 +271,16 @@ def test_same_directory_python_cycle_is_not_demoted():
# A Python import cycle fails at import time; it is never an idiom.
out = _detect_lang(_import_graph([("pkg/a.py", "pkg/b.py"), ("pkg/b.py", "pkg/a.py")]), "pkg/a.py", "python")
assert out[0].confidence == "high"
+
+
+def test_type_only_import_edges_suppress_break_cycle():
+ g = nx.DiGraph()
+ g.add_node("a.ts", node_type="file")
+ g.add_node("b.ts", node_type="file")
+ # Mutually type-only imports
+ g.add_edge("a.ts", "b.ts", edge_type="imports", type_only=True)
+ g.add_edge("b.ts", "a.ts", edge_type="imports", type_only=True)
+
+ assert build_file_scc_index(g) == {}
+ assert _detect(g, "a.ts") == []
+ assert _detect(g, "b.ts") == []
diff --git a/tests/unit/ingestion/test_cohesion_cycles.py b/tests/unit/ingestion/test_cohesion_cycles.py
index 3d5b9fa9c..68407dd36 100644
--- a/tests/unit/ingestion/test_cohesion_cycles.py
+++ b/tests/unit/ingestion/test_cohesion_cycles.py
@@ -461,3 +461,13 @@ class TestGoImportSurfaceExcludesTestFiles:
assert "store/store_test.go" in pkg.files
# The import surface does not.
assert index.files_for_import("example.com/app/store") == ("store/store.go",)
+
+
+def test_typescript_type_only_imports_excluded_from_cycle_subgraph() -> None:
+ builder = _pair_builder(type_only=True)
+
+ cycle_sub = builder.cycle_subgraph()
+ assert cycle_sub.number_of_edges() == 0
+ assert _cycles(cycle_sub) == []
+
+
diff --git a/tests/unit/ingestion/test_graph_rehydrate.py b/tests/unit/ingestion/test_graph_rehydrate.py
index 63887a9e9..1d5844494 100644
--- a/tests/unit/ingestion/test_graph_rehydrate.py
+++ b/tests/unit/ingestion/test_graph_rehydrate.py
@@ -91,6 +91,7 @@ def _serialize(builder: GraphBuilder) -> tuple[list[dict], list[dict]]:
"hint_source": data.get("hint_source"),
"resolution_origin": data.get("resolution_origin"),
"call_lines": data.get("call_lines", []),
+ "type_only": bool(data.get("type_only", False)),
}
)
return nodes, edges
@@ -227,3 +228,21 @@ def test_parse_only_symbol_attrs_come_back_from_the_reparse():
node = hydrated.graph().nodes[sym.id]
assert node["modifiers"] == ("override",)
assert node["decorators"] == ["@override"]
+
+
+def test_type_only_edges_survive_rehydration_and_suppress_cycles():
+ builder = GraphBuilder()
+ builder.add_file(_parsed("a.py", [_imp("b")]))
+ builder.add_file(_parsed("b.py", [_imp("a")]))
+ builder.build()
+ builder.graph()["a.py"]["b.py"]["type_only"] = True
+ builder.graph()["b.py"]["a.py"]["type_only"] = True
+
+ nodes, edges = _serialize(builder)
+ assert any(e.get("type_only") for e in edges)
+
+ hydrated = GraphBuilder.from_persisted(nodes, edges, builder.file_metrics_snapshot())
+ assert hydrated.graph()["a.py"]["b.py"]["type_only"] is True
+ assert hydrated.graph()["b.py"]["a.py"]["type_only"] is True
+ assert hydrated.cycle_subgraph().number_of_edges() == 0
+
diff --git a/tests/unit/ingestion/test_ts_type_imports.py b/tests/unit/ingestion/test_ts_type_imports.py
new file mode 100644
index 000000000..67fc77600
--- /dev/null
+++ b/tests/unit/ingestion/test_ts_type_imports.py
@@ -0,0 +1,115 @@
+"""Tests for TypeScript type-only imports and cycle suppression."""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+import pytest
+
+from repowise.core.analysis.health.refactoring.graph_signals import build_file_scc_index
+from repowise.core.ingestion.graph import GraphBuilder
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+
+def _file_info(path: str) -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=f"/repo/{path}",
+ language="typescript",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+ ("source", "expected_type_only"),
+ [
+ ('import type { User } from "./user";', True),
+ ('import type User from "./user";', True),
+ ('import type * as User from "./user";', True),
+ ('export type { User } from "./user";', True),
+ ('export type * from "./user";', True),
+ ('export type * as User from "./user";', True),
+ ('import { type User, type Account } from "./user";', True),
+ ('export { type User, type Account } from "./user";', True),
+ ('import { type User, getUser } from "./user";', False),
+ ('export { type User, getUser } from "./user";', False),
+ ('import { User, Account } from "./user";', False),
+ ('export { User, Account } from "./user";', False),
+ ('import User from "./user";', False),
+ ('import * as User from "./user";', False),
+ ('export * from "./user";', False),
+ ],
+)
+def test_ts_type_only_import_parsing(source: str, expected_type_only: bool) -> None:
+ parser = ASTParser()
+ parsed = parser.parse_file(_file_info("app.ts"), source.encode("utf-8"))
+ assert len(parsed.imports) >= 1
+ assert parsed.imports[0].type_only is expected_type_only
+
+
+def test_ts_mutually_type_only_cycle_suppressed() -> None:
+ parser = ASTParser()
+ builder = GraphBuilder()
+
+ a_src = 'import type { B } from "./b";\nexport type A = { b: B };\n'
+ b_src = 'import type { A } from "./a";\nexport type B = { a: A };\n'
+
+ builder.add_file(parser.parse_file(_file_info("a.ts"), a_src.encode("utf-8")))
+ builder.add_file(parser.parse_file(_file_info("b.ts"), b_src.encode("utf-8")))
+ graph = builder.build()
+
+ # Graph retains the import edge for reachability
+ assert graph.has_edge("a.ts", "b.ts")
+ assert graph["a.ts"]["b.ts"]["type_only"] is True
+ assert graph.has_edge("b.ts", "a.ts")
+ assert graph["b.ts"]["a.ts"]["type_only"] is True
+
+ # Cycle subgraph and SCC index suppress the cycle
+ assert builder.cycle_subgraph().number_of_edges() == 0
+ assert build_file_scc_index(graph) == {}
+
+
+def test_ts_mixed_runtime_and_type_cycle_detected() -> None:
+ parser = ASTParser()
+ builder = GraphBuilder()
+
+ # a -> b is value import, b -> a is value import
+ a_src = 'import { bVal } from "./b";\nexport const aVal = bVal + 1;\n'
+ b_src = 'import { aVal } from "./a";\nexport const bVal = aVal + 1;\n'
+
+ builder.add_file(parser.parse_file(_file_info("a.ts"), a_src.encode("utf-8")))
+ builder.add_file(parser.parse_file(_file_info("b.ts"), b_src.encode("utf-8")))
+ graph = builder.build()
+
+ assert builder.cycle_subgraph().number_of_edges() == 2
+ scc = build_file_scc_index(graph)
+ assert "a.ts" in scc and "b.ts" in scc
+
+
+def test_ts_parallel_edges_merging() -> None:
+ parser = ASTParser()
+ builder = GraphBuilder()
+
+ # File a imports b twice: once type-only, once runtime value
+ a_src = (
+ 'import type { BType } from "./b";\n'
+ 'import { bValue } from "./b";\n'
+ 'export const a = 1;\n'
+ )
+ b_src = 'export type BType = number;\nexport const bValue = 2;\n'
+
+ builder.add_file(parser.parse_file(_file_info("a.ts"), a_src.encode("utf-8")))
+ builder.add_file(parser.parse_file(_file_info("b.ts"), b_src.encode("utf-8")))
+ graph = builder.build()
+
+ # The edge must NOT be type_only because a runtime value is imported
+ assert graph["a.ts"]["b.ts"]["type_only"] is False
+ assert set(graph["a.ts"]["b.ts"]["imported_names"]) == {"BType", "bValue"}
+
diff --git a/tests/unit/persistence/test_graph_edge_type_only.py b/tests/unit/persistence/test_graph_edge_type_only.py
new file mode 100644
index 000000000..c01b15e63
--- /dev/null
+++ b/tests/unit/persistence/test_graph_edge_type_only.py
@@ -0,0 +1,55 @@
+"""Tests for graph_edges.type_only column persistence and rehydration."""
+
+from __future__ import annotations
+
+from repowise.core.analysis.health.refactoring.graph_signals import build_file_scc_index
+from repowise.core.ingestion.graph import GraphBuilder
+from repowise.core.persistence.crud import (
+ batch_upsert_graph_edges,
+ batch_upsert_graph_nodes,
+ get_all_graph_edges,
+ get_all_graph_nodes,
+)
+from tests.unit.persistence.helpers import insert_repo
+
+
+async def test_graph_edge_type_only_round_trips_through_database(async_session) -> None:
+ repo = await insert_repo(async_session)
+
+ nodes = [
+ {"node_id": "a.ts", "node_type": "file", "language": "typescript"},
+ {"node_id": "b.ts", "node_type": "file", "language": "typescript"},
+ ]
+ edges = [
+ {
+ "source_node_id": "a.ts",
+ "target_node_id": "b.ts",
+ "imported_names_json": '["B"]',
+ "edge_type": "imports",
+ "type_only": True,
+ },
+ {
+ "source_node_id": "b.ts",
+ "target_node_id": "a.ts",
+ "imported_names_json": '["A"]',
+ "edge_type": "imports",
+ "type_only": True,
+ },
+ ]
+
+ await batch_upsert_graph_nodes(async_session, repo.id, nodes)
+ await batch_upsert_graph_edges(async_session, repo.id, edges)
+ await async_session.commit()
+
+ loaded_nodes = await get_all_graph_nodes(async_session, repo.id)
+ loaded_edges = await get_all_graph_edges(async_session, repo.id)
+
+ assert len(loaded_edges) == 2
+ for e in loaded_edges:
+ assert e["type_only"] is True
+
+ rehydrated = GraphBuilder.from_persisted(loaded_nodes, loaded_edges)
+ assert rehydrated.graph()["a.ts"]["b.ts"]["type_only"] is True
+ assert rehydrated.graph()["b.ts"]["a.ts"]["type_only"] is True
+ assert rehydrated.cycle_subgraph().number_of_edges() == 0
+ assert build_file_scc_index(rehydrated.graph()) == {}