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.

test: split the three largest test modules into themed packages (#265)

Raghav Chamadiya968fb4a8b6a2
diff --git a/tests/unit/dead_code/__init__.py b/tests/unit/dead_code/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/unit/dead_code/_helpers.py b/tests/unit/dead_code/_helpers.py
new file mode 100644
index 000000000..95f1cef1c
--- /dev/null
+++ b/tests/unit/dead_code/_helpers.py
@@ -0,0 +1,53 @@
+"""Unit tests for DeadCodeAnalyzer."""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+
+import networkx as nx
+
+
+def _now() -> datetime:
+ return datetime.now(UTC)
+
+
+def _old_date(days: int = 365) -> datetime:
+ """Return a datetime `days` ago (timezone-aware)."""
+ return _now() - timedelta(days=days)
+
+
+def _build_graph(
+ nodes: dict[str, dict],
+ edges: list[tuple[str, str]] | None = None,
+) -> nx.DiGraph:
+ """Create a DiGraph with the given node attributes and edges.
+
+ ``nodes`` maps node-id to its attribute dict. If a node has a
+ ``symbols`` list, each entry is promoted to a proper symbol node
+ connected to the file via a ``defines`` edge (matching the real
+ GraphBuilder layout).
+ ``edges`` is a list of (src, dst) pairs; edge data can be
+ supplied as a 3-tuple (src, dst, data_dict).
+ """
+ g = nx.DiGraph()
+ for name, attrs in nodes.items():
+ attrs.setdefault("language", "python")
+ # Extract symbols before adding the file node
+ sym_list = attrs.pop("symbols", [])
+ g.add_node(name, **attrs)
+ # Create symbol nodes + defines edges (mirrors GraphBuilder.add_file)
+ for sym in sym_list:
+ sym_id = f"{name}::{sym['name']}"
+ g.add_node(
+ sym_id,
+ node_type="symbol",
+ file_path=name,
+ **sym,
+ )
+ g.add_edge(name, sym_id, edge_type="defines")
+ for edge in edges or []:
+ if len(edge) == 3:
+ g.add_edge(edge[0], edge[1], **(edge[2]))
+ else:
+ g.add_edge(edge[0], edge[1])
+ return g
diff --git a/tests/unit/dead_code/test_alembic.py b/tests/unit/dead_code/test_alembic.py
new file mode 100644
index 000000000..d49cf1a86
--- /dev/null
+++ b/tests/unit/dead_code/test_alembic.py
@@ -0,0 +1,83 @@
+"""Unit tests for DeadCodeAnalyzer."""
+
+from __future__ import annotations
+
+from repowise.core.analysis.dead_code import (
+ DeadCodeAnalyzer,
+ DeadCodeKind,
+)
+from tests.unit.dead_code._helpers import _build_graph
+
+
+def test_alembic_versions_never_flagged_as_unreachable():
+ """Files under <root>/alembic/versions/*.py are loaded reflectively by
+ Alembic at runtime — they have no static importer and must not be
+ surfaced as unreachable on any Alembic-using repo (generic Python
+ convention)."""
+ g = _build_graph(
+ nodes={
+ "myapp/alembic/versions/0001_init.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 2,
+ "symbols": [],
+ },
+ "myapp/alembic/versions/0002_add_users.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 2,
+ "symbols": [],
+ },
+ },
+ edges=[],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze({"detect_unused_exports": False, "detect_zombie_packages": False})
+ paths = {f.file_path for f in report.findings}
+ assert "myapp/alembic/versions/0001_init.py" not in paths
+ assert "myapp/alembic/versions/0002_add_users.py" not in paths
+
+
+def test_alembic_upgrade_downgrade_never_flagged_as_unused():
+ """``upgrade()`` / ``downgrade()`` in Alembic migration scripts are
+ called via reflection by the Alembic runner — the file pattern
+ exemption (``*/alembic/versions/*.py``) already covers them, so the
+ symbols inside must not surface as unused exports either."""
+ g = _build_graph(
+ nodes={
+ "myapp/alembic/versions/0001_init.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 2,
+ "symbols": [
+ {
+ "name": "upgrade",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 5,
+ "complexity_estimate": 1,
+ },
+ {
+ "name": "downgrade",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 7,
+ "end_line": 11,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ },
+ edges=[],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze({"detect_unreachable_files": False, "detect_zombie_packages": False})
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
+ assert "upgrade" not in names
+ assert "downgrade" not in names
diff --git a/tests/unit/dead_code/test_confidence.py b/tests/unit/dead_code/test_confidence.py
new file mode 100644
index 000000000..3a13da164
--- /dev/null
+++ b/tests/unit/dead_code/test_confidence.py
@@ -0,0 +1,85 @@
+"""Unit tests for DeadCodeAnalyzer."""
+
+from __future__ import annotations
+
+from datetime import timedelta
+
+import pytest
+
+from repowise.core.analysis.dead_code import (
+ DeadCodeAnalyzer,
+)
+from tests.unit.dead_code._helpers import _build_graph, _now, _old_date
+
+
+def test_confidence_low_for_recent_files():
+ """Unreachable file with commit_count_90d > 0 should have confidence 0.4."""
+ g = _build_graph(
+ nodes={
+ "pkg/recent.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 5,
+ "symbols": [],
+ },
+ },
+ )
+
+ git_meta = {
+ "pkg/recent.py": {
+ "commit_count_90d": 3,
+ "last_commit_at": _now() - timedelta(days=10),
+ "age_days": 100,
+ "primary_owner_name": "[email protected]",
+ },
+ }
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map=git_meta)
+ report = analyzer.analyze(
+ {
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+
+ findings = [f for f in report.findings if f.file_path == "pkg/recent.py"]
+ assert len(findings) == 1
+ assert findings[0].confidence == pytest.approx(0.4)
+
+
+def test_confidence_high_for_stale_unreachable():
+ """Unreachable file with no commits in 90d and last commit > 6 months ago -> confidence 1.0."""
+ g = _build_graph(
+ nodes={
+ "pkg/stale.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 5,
+ "symbols": [],
+ },
+ },
+ )
+
+ git_meta = {
+ "pkg/stale.py": {
+ "commit_count_90d": 0,
+ "last_commit_at": _old_date(days=365),
+ "age_days": 730,
+ "primary_owner_name": "[email protected]",
+ },
+ }
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map=git_meta)
+ report = analyzer.analyze(
+ {
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ }
+ )
+
+ findings = [f for f in report.findings if f.file_path == "pkg/stale.py"]
+ assert len(findings) == 1
+ assert findings[0].confidence == pytest.approx(1.0)
diff --git a/tests/unit/dead_code/test_decorators_dynamic.py b/tests/unit/dead_code/test_decorators_dynamic.py
new file mode 100644
index 000000000..36b638a14
--- /dev/null
+++ b/tests/unit/dead_code/test_decorators_dynamic.py
@@ -0,0 +1,331 @@
+"""Unit tests for DeadCodeAnalyzer."""
+
+from __future__ import annotations
+
+import networkx as nx
+import pytest
+
+from repowise.core.analysis.dead_code import (
+ DeadCodeAnalyzer,
+ DeadCodeKind,
+)
+from tests.unit.dead_code._helpers import _build_graph, _old_date
+
+
+def test_framework_decorator_excluded():
+ """A symbol decorated with pytest.fixture should NOT be flagged."""
+ g = _build_graph(
+ nodes={
+ "pkg/conftest.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 2,
+ "symbols": [
+ {
+ "name": "db_session",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": ["pytest.fixture"],
+ "start_line": 1,
+ "end_line": 15,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ },
+ )
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_zombie_packages": False,
+ }
+ )
+
+ sym_names = [f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]
+ assert "db_session" not in sym_names
+
+
+def test_dynamic_pattern_excluded():
+ """A symbol matching '*Handler' dynamic pattern should NOT be flagged as unused."""
+ g = _build_graph(
+ nodes={
+ "pkg/events.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 2,
+ "symbols": [
+ {
+ "name": "EventHandler",
+ "kind": "class",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 40,
+ "complexity_estimate": 3,
+ },
+ ],
+ },
+ },
+ )
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_zombie_packages": False,
+ }
+ )
+
+ sym_names = [f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]
+ assert "EventHandler" not in sym_names
+
+
+def test_at_prefixed_decorator_excluded():
+ """Decorators stored with the leading '@' (as the parser emits them)
+ must still match the framework-decorator whitelist."""
+ g = _build_graph(
+ nodes={
+ "pkg/routes.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 2,
+ "symbols": [
+ {
+ "name": "list_items",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": ['@router.get("/items")'],
+ "start_line": 1,
+ "end_line": 8,
+ },
+ {
+ "name": "lifespan",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": ["@asynccontextmanager"],
+ "start_line": 10,
+ "end_line": 20,
+ },
+ ],
+ },
+ },
+ )
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_zombie_packages": False,
+ }
+ )
+ sym_names = [f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]
+ assert "list_items" not in sym_names
+ assert "lifespan" not in sym_names
+
+
+def test_dynamic_edge_clamps_unreachable_confidence():
+ """A file in a package that has dynamic graph edges should have confidence clamped to 0.4."""
+ g = _build_graph(
+ nodes={
+ "pkg/orphan.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 5,
+ "symbols": [],
+ },
+ "pkg/dispatcher.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 3,
+ "symbols": [],
+ },
+ "pkg/handler.py": {
+ "is_entry_point": True,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 3,
+ "symbols": [],
+ },
+ },
+ edges=[
+ ("pkg/dispatcher.py", "pkg/handler.py", {"edge_type": "dynamic"}),
+ ],
+ )
+
+ git_meta = {
+ "pkg/orphan.py": {
+ "commit_count_90d": 0,
+ "last_commit_at": _old_date(days=400),
+ "age_days": 500,
+ },
+ }
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map=git_meta)
+ report = analyzer.analyze(
+ {
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+
+ findings = [f for f in report.findings if f.file_path == "pkg/orphan.py"]
+ assert len(findings) == 1
+ assert findings[0].confidence == pytest.approx(0.4)
+ assert any("dynamic" in e.lower() for e in findings[0].evidence)
+
+
+def test_find_dynamic_edge_files_handles_subtypes():
+ """find_dynamic_edge_files picks up edges with dynamic_* sub-type prefixes."""
+ from repowise.core.analysis.dead_code.dynamic_markers import find_dynamic_edge_files
+
+ g = nx.DiGraph()
+ g.add_node("a.py")
+ g.add_node("b.py")
+ g.add_node("c.py")
+ g.add_node("d.py")
+ g.add_node("external:something")
+ g.add_edge("a.py", "b.py", edge_type="dynamic_uses")
+ g.add_edge("c.py", "d.py", edge_type="dynamic_imports")
+ g.add_edge("a.py", "external:something", edge_type="dynamic")
+ # Non-dynamic edges should not contribute
+ g.add_edge("b.py", "c.py", edge_type="calls")
+
+ files = find_dynamic_edge_files(g)
+ assert {"a.py", "b.py", "c.py", "d.py"} <= files
+ assert "external:something" not in files
+
+
+ "suffix,expected_markers",
+ [
+ (".go", ("plugin.Open(", "reflect.New(", "reflect.TypeOf(", "reflect.ValueOf(")),
+ (
+ ".rb",
+ ("autoload ", "const_get(", "Object.send(", "Kernel.const_get(", ".public_send("),
+ ),
+ (
+ ".php",
+ (
+ "class_exists(",
+ "call_user_func(",
+ "call_user_func_array(",
+ "new $",
+ "ReflectionClass(",
+ ),
+ ),
+ (
+ ".kt",
+ ("Class.forName(", "ServiceLoader.load(", "KClass.createInstance(", "::class.java"),
+ ),
+ (
+ ".swift",
+ ("NSClassFromString(", "Selector(", "#selector(", "NSStringFromClass("),
+ ),
+ (".scala", ("Class.forName(", "runtimeMirror(", "reflect.runtime")),
+ ],
+)
+def test_dynamic_markers_per_language_coverage(suffix, expected_markers):
+ """Each language's marker tuple must contain the documented Phase 2 entries."""
+ from repowise.core.analysis.dead_code.dynamic_markers import _DYNAMIC_IMPORT_MARKERS
+
+ markers = _DYNAMIC_IMPORT_MARKERS.get(suffix, ())
+ for expected in expected_markers:
+ assert expected in markers, f"missing marker {expected!r} for {suffix}"
+
+
+def test_click_group_command_decorator_excluded():
+ """Subcommands registered on a locally-named Click ``Group`` are
+ decorated as e.g. ``@my_cli.command("add")``. The receiver name is
+ project-local, so the matcher needs to recognise the ``.command``
+ suffix rather than a hard-coded ``click.command`` prefix. Same shape
+ covers Typer (``.command``/``.callback``) and any user-named
+ dispatcher."""
+ g = _build_graph(
+ nodes={
+ "pkg/cli.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 3,
+ "symbols": [
+ {
+ "name": "decision_add",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": ["decision_group.command"],
+ "start_line": 1,
+ "end_line": 10,
+ "complexity_estimate": 1,
+ },
+ {
+ "name": "decision_list",
+ "kind": "function",
+ "visibility": "public",
+ # Real-world capture sometimes includes the call
+ # arguments — the matcher must strip them.
+ "decorators": ['my_cli.group("decision")'],
+ "start_line": 12,
+ "end_line": 20,
+ "complexity_estimate": 1,
+ },
+ {
+ "name": "after_cmd",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": ["app.callback"],
+ "start_line": 22,
+ "end_line": 28,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ },
+ edges=[],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze({"detect_unreachable_files": False, "detect_zombie_packages": False})
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
+ assert "decision_add" not in names
+ assert "decision_list" not in names
+ assert "after_cmd" not in names
+
+
+def test_unrelated_dot_command_function_still_flagged():
+ """A decorator suffix-match must not accidentally whitelist symbols
+ with unrelated decorators. ``@functools.lru_cache`` does not end with
+ ``.command/.group/.callback``, so a plain unused public helper with
+ that decorator is still surfaced."""
+ g = _build_graph(
+ nodes={
+ "pkg/helpers.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "expensive_lookup",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": ["functools.lru_cache"],
+ "start_line": 1,
+ "end_line": 20,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ },
+ edges=[],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze({"detect_unreachable_files": False, "detect_zombie_packages": False})
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
+ assert "expensive_lookup" in names
diff --git a/tests/unit/dead_code/test_interfaces.py b/tests/unit/dead_code/test_interfaces.py
new file mode 100644
index 000000000..652ea8c55
--- /dev/null
+++ b/tests/unit/dead_code/test_interfaces.py
@@ -0,0 +1,170 @@
+"""Unit tests for DeadCodeAnalyzer."""
+
+from __future__ import annotations
+
+from repowise.core.analysis.dead_code import (
+ DeadCodeAnalyzer,
+ DeadCodeKind,
+)
+from tests.unit.dead_code._helpers import _build_graph
+
+
+def test_interface_without_implementor_demoted_below_safe_threshold():
+ """Public interfaces with no incoming ``implements`` edges have
+ their unused-export confidence clamped below 0.7 so the demo
+ doesn't ship them as confident dead code. Implementor detection
+ is heuristic — absence is missing-signal, not evidence-of-absence.
+ """
+ g = _build_graph(
+ nodes={
+ "src/IBasketService.cs": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "IBasketService",
+ "kind": "interface",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 5,
+ "complexity_estimate": 1,
+ "language": "csharp",
+ },
+ ],
+ },
+ },
+ edges=[],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ interface_findings = [
+ f
+ for f in report.findings
+ if f.kind == DeadCodeKind.UNUSED_EXPORT and f.symbol_name == "IBasketService"
+ ]
+ # The finding may still surface, but never at safe-to-delete confidence.
+ for f in interface_findings:
+ assert f.confidence <= 0.4, f"interface flagged at unsafe confidence {f.confidence}"
+ assert f.safe_to_delete is False
+
+
+def test_com_contract_method_demoted_below_safe_threshold():
+ """``QueryInterface`` / ``AddRef`` / ``Release`` are reached through
+ a native COM vtable — never via a static caller. The analyzer must
+ not flag them as confident dead code.
+ """
+ g = _build_graph(
+ nodes={
+ "src/CoFoo.cpp": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 3,
+ "symbols": [
+ {
+ "name": "QueryInterface",
+ "kind": "method",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 10,
+ "end_line": 25,
+ "complexity_estimate": 1,
+ "language": "cpp",
+ },
+ {
+ "name": "AddRef",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 27,
+ "end_line": 30,
+ "complexity_estimate": 1,
+ "language": "cpp",
+ },
+ {
+ "name": "Release",
+ "kind": "method",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 32,
+ "end_line": 40,
+ "complexity_estimate": 1,
+ "language": "cpp",
+ },
+ ],
+ },
+ },
+ edges=[],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ com_findings = [
+ f for f in report.findings if f.symbol_name in {"QueryInterface", "AddRef", "Release"}
+ ]
+ for f in com_findings:
+ assert f.confidence <= 0.4, f"COM method flagged at unsafe confidence {f.confidence}"
+ assert f.safe_to_delete is False
+
+
+def test_release_in_non_com_language_not_clamped():
+ """A free function named ``Release`` in TypeScript/Python is *not* a
+ COM contract method — the contract-method clamp must not apply.
+ """
+ g = _build_graph(
+ nodes={
+ "src/foo.ts": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "Release",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 5,
+ "complexity_estimate": 1,
+ "language": "typescript",
+ },
+ ],
+ },
+ },
+ edges=[],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ # TS ``function`` kind is universally skipped from unused-export
+ # detection (functions surface as variables in JS-style modules),
+ # so the strongest assertion is "no spurious COM clamp masked the
+ # real behaviour". The function should still be detectable somehow
+ # downstream; here we just confirm the analyzer didn't crash and
+ # didn't ship it under contract-method semantics.
+ com_findings = [f for f in report.findings if f.symbol_name == "Release"]
+ for f in com_findings:
+ # If it surfaces at all, it must do so under the *normal*
+ # rule — not under the COM clamp specifically. The normal
+ # rule yields 0.7 / 1.0 depending on file-level importers.
+ assert f.confidence >= 0.7 or f.confidence < 0.4
diff --git a/tests/unit/dead_code/test_reachability.py b/tests/unit/dead_code/test_reachability.py
new file mode 100644
index 000000000..d40256c0e
--- /dev/null
+++ b/tests/unit/dead_code/test_reachability.py
@@ -0,0 +1,217 @@
+"""Unit tests for DeadCodeAnalyzer."""
+
+from __future__ import annotations
+
+from repowise.core.analysis.dead_code import (
+ DeadCodeAnalyzer,
+ DeadCodeKind,
+)
+from tests.unit.dead_code._helpers import _build_graph
+
+
+def test_unreachable_file_detected():
+ """A file with in_degree=0, not an entry point, should be flagged as unreachable."""
+ g = _build_graph(
+ nodes={
+ "pkg/orphan.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 5,
+ "symbols": [],
+ },
+ "pkg/main.py": {
+ "is_entry_point": True,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 10,
+ "symbols": [],
+ },
+ },
+ edges=[], # orphan.py has in_degree=0
+ )
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze({"detect_unused_exports": False, "detect_zombie_packages": False})
+
+ unreachable = [f for f in report.findings if f.kind == DeadCodeKind.UNREACHABLE_FILE]
+ paths = [f.file_path for f in unreachable]
+ assert "pkg/orphan.py" in paths
+
+
+def test_entry_point_not_flagged():
+ """A file marked as is_entry_point=True should NOT be flagged even with in_degree=0."""
+ g = _build_graph(
+ nodes={
+ "pkg/main.py": {
+ "is_entry_point": True,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 10,
+ "symbols": [],
+ },
+ },
+ )
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze({"detect_unused_exports": False, "detect_zombie_packages": False})
+
+ assert all(f.file_path != "pkg/main.py" for f in report.findings)
+
+
+def test_test_files_excluded():
+ """A test file (is_test=True) with in_degree=0 should NOT be flagged."""
+ g = _build_graph(
+ nodes={
+ "tests/test_something.py": {
+ "is_entry_point": False,
+ "is_test": True,
+ "is_api_contract": False,
+ "symbol_count": 8,
+ "symbols": [],
+ },
+ },
+ )
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze({"detect_unused_exports": False, "detect_zombie_packages": False})
+
+ assert all(f.file_path != "tests/test_something.py" for f in report.findings)
+
+
+def test_entry_point_names_never_flagged():
+ """Runtime entry points (wWinMain, TEST_METHOD, DllInstall…) are
+ never flagged regardless of incoming-edge counts. The Win32 / COM /
+ MSTest runners reach them by mechanism, not by a `using` import."""
+ g = _build_graph(
+ nodes={
+ "src/main.cpp": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 3,
+ "language": "cpp",
+ "symbols": [
+ {
+ "name": "wWinMain",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 10,
+ "complexity_estimate": 1,
+ },
+ {
+ "name": "TEST_METHOD",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 12,
+ "end_line": 20,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ },
+ edges=[],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze({"detect_unreachable_files": False, "detect_zombie_packages": False})
+ names = [f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]
+ assert "wWinMain" not in names
+ assert "TEST_METHOD" not in names
+
+
+def test_nested_function_not_flagged():
+ """Symbols defined inside another function's body cannot be imported by
+ name and must not be flagged as unused exports."""
+ g = _build_graph(
+ nodes={
+ "pkg/server.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 2,
+ "symbols": [
+ {
+ "name": "chat",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 10,
+ "end_line": 80,
+ },
+ # Nested closure / inner generator — line range strictly
+ # contained inside ``chat``.
+ {
+ "name": "event_stream",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 25,
+ "end_line": 60,
+ },
+ ],
+ },
+ },
+ )
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_zombie_packages": False,
+ }
+ )
+ sym_names = [f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]
+ assert "event_stream" not in sym_names
+
+
+def test_framework_anchor_counts_as_cross_package_importer():
+ """``framework:`` synthetic predecessors should rescue a package from zombie status.
+
+ ``external:`` predecessors don't count (third-party imports), but
+ ``framework:`` anchors model real framework-mediated loading
+ (e.g. TYPO3 core loading every ``Configuration/*.php``) and should.
+ """
+ g = _build_graph(
+ nodes={
+ "Configuration/foo.php": {"is_entry_point": False, "symbol_count": 1, "symbols": []},
+ "src/main.php": {"is_entry_point": False, "symbol_count": 1, "symbols": []},
+ },
+ )
+ g.add_node("framework:typo3-core", language="external")
+ g.add_edge("framework:typo3-core", "Configuration/foo.php", edge_type="framework")
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_exports": False,
+ "min_confidence": 0.0,
+ }
+ )
+
+ zombie_pkgs = [f.package for f in report.findings if f.kind == DeadCodeKind.ZOMBIE_PACKAGE]
+ assert "Configuration" not in zombie_pkgs, (
+ "framework: predecessors should count as cross-package importers"
+ )
+
+
+def test_framework_anchor_node_not_flagged_as_unreachable():
+ """A ``framework:`` synthetic node must not itself be flagged as dead."""
+ g = _build_graph(
+ nodes={
+ "ext_localconf.php": {"is_entry_point": False, "symbol_count": 1, "symbols": []},
+ },
+ )
+ g.add_node("framework:typo3-core", language="external")
+ g.add_edge("framework:typo3-core", "ext_localconf.php", edge_type="framework")
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze({"min_confidence": 0.0})
+
+ paths = [f.file_path for f in report.findings]
+ assert "framework:typo3-core" not in paths
+ # ext_localconf.php should also not be flagged: it has a framework: predecessor.
+ assert "ext_localconf.php" not in paths
diff --git a/tests/unit/dead_code/test_unused_exports.py b/tests/unit/dead_code/test_unused_exports.py
new file mode 100644
index 000000000..d1803737d
--- /dev/null
+++ b/tests/unit/dead_code/test_unused_exports.py
@@ -0,0 +1,274 @@
+"""Unit tests for DeadCodeAnalyzer."""
+
+from __future__ import annotations
+
+from repowise.core.analysis.dead_code import (
+ DeadCodeAnalyzer,
+ DeadCodeKind,
+)
+from tests.unit.dead_code._helpers import _build_graph
+
+
+def test_unused_export_detected():
+ """A public symbol with no importers should be flagged as unused export."""
+ g = _build_graph(
+ nodes={
+ "pkg/utils.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 3,
+ "symbols": [
+ {
+ "name": "helper_func",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 10,
+ "complexity_estimate": 2,
+ },
+ ],
+ },
+ "pkg/main.py": {
+ "is_entry_point": True,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 10,
+ "symbols": [],
+ },
+ },
+ # main.py imports utils.py but does NOT import helper_func by name
+ edges=[("pkg/main.py", "pkg/utils.py", {"imported_names": ["other_func"]})],
+ )
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_zombie_packages": False,
+ }
+ )
+
+ unused = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]
+ sym_names = [f.symbol_name for f in unused]
+ assert "helper_func" in sym_names
+
+
+def test_unused_export_skipped_when_symbol_has_incoming_calls():
+ """A public symbol with no file-level importers but at least one
+ incoming ``calls`` edge on the symbol itself is still in use —
+ typical for C++ intra-file helpers and ``Foo::method`` qualified
+ definitions reached via call resolution rather than headers."""
+ g = _build_graph(
+ nodes={
+ "pkg/utils.cpp": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 2,
+ "language": "cpp",
+ "symbols": [
+ {
+ "name": "helper",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 10,
+ "complexity_estimate": 1,
+ },
+ {
+ "name": "caller",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 12,
+ "end_line": 20,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ },
+ edges=[
+ ("pkg/utils.cpp::caller", "pkg/utils.cpp::helper", {"edge_type": "calls"}),
+ ],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_zombie_packages": False,
+ }
+ )
+ sym_names = [f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]
+ # ``helper`` is called by ``caller`` — must not be flagged.
+ assert "helper" not in sym_names
+ # ``caller`` has no callers — still flagged.
+ assert "caller" in sym_names
+
+
+def test_unused_export_skipped_when_file_imported_as_namespace():
+ """A public symbol in a file that is imported by its module name
+ (``from . import cargo``) is a dispatch-table candidate — the
+ importer holds a binding to the module and can call any public
+ attribute via ``cargo.<attr>(...)``. We cannot tell statically
+ which attribute is used, so every public symbol in the file must
+ be treated as live."""
+ g = _build_graph(
+ nodes={
+ "pkg/external_systems/cargo.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "parse",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 12,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ "pkg/external_systems/__init__.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 0,
+ "symbols": [],
+ },
+ },
+ edges=[
+ (
+ "pkg/external_systems/__init__.py",
+ "pkg/external_systems/cargo.py",
+ {"edge_type": "imports", "imported_names": ["cargo"]},
+ ),
+ ],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_internals": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
+ assert "parse" not in names
+
+
+def test_unused_export_still_flagged_when_namespace_name_differs():
+ """Negative test for the namespace-import rescue: if the importer
+ pulls a *different* sibling module, the public symbol's file is
+ still effectively orphan and the symbol must be flagged."""
+ g = _build_graph(
+ nodes={
+ "pkg/external_systems/cargo.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "parse",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 12,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ "pkg/external_systems/__init__.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 0,
+ "symbols": [],
+ },
+ },
+ edges=[
+ # importer pulled "npm" only — does NOT mention "cargo"
+ (
+ "pkg/external_systems/__init__.py",
+ "pkg/external_systems/cargo.py",
+ {"edge_type": "imports", "imported_names": ["npm"]},
+ ),
+ ],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_internals": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
+ assert "parse" in names
+
+
+def test_unused_export_not_rescued_for_index_stem():
+ """``index.ts`` is the barrel filename in JS/TS package layouts —
+ every workspace package's source root has one, and most imports of
+ a package land on it. We must not over-rescue every public export
+ of every ``index.ts`` just because a downstream importer happens
+ to use the literal name ``index``. Same applies to Python
+ ``__init__`` (already covered by the global never-flag list)."""
+ g = _build_graph(
+ nodes={
+ "pkg/ui/src/index.ts": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "language": "typescript",
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "stranded_export",
+ "kind": "function",
+ "visibility": "public",
+ "language": "typescript",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 5,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ "pkg/web/src/page.ts": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "language": "typescript",
+ "symbol_count": 0,
+ "symbols": [],
+ },
+ },
+ edges=[
+ (
+ "pkg/web/src/page.ts",
+ "pkg/ui/src/index.ts",
+ {"edge_type": "imports", "imported_names": ["index"]},
+ ),
+ ],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_internals": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
+ assert "stranded_export" in names
diff --git a/tests/unit/dead_code/test_unused_internal.py b/tests/unit/dead_code/test_unused_internal.py
new file mode 100644
index 000000000..f0f7753ee
--- /dev/null
+++ b/tests/unit/dead_code/test_unused_internal.py
@@ -0,0 +1,193 @@
+"""Unit tests for DeadCodeAnalyzer."""
+
+from __future__ import annotations
+
+from repowise.core.analysis.dead_code import (
+ DeadCodeAnalyzer,
+ DeadCodeKind,
+)
+from tests.unit.dead_code._helpers import _build_graph
+
+
+def test_unused_internal_default_on():
+ """detect_unused_internals defaults to True; private symbols with no callers are flagged."""
+ g = _build_graph(
+ nodes={
+ "pkg/utils.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "_helper",
+ "kind": "function",
+ "visibility": "private",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 12,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ },
+ )
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+
+ internals = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL]
+ assert any(f.symbol_name == "_helper" for f in internals)
+ assert all(f.safe_to_delete is False for f in internals)
+
+
+def test_unused_internal_explicit_opt_out():
+ """Setting detect_unused_internals=False disables the detector."""
+ g = _build_graph(
+ nodes={
+ "pkg/utils.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "_helper",
+ "kind": "function",
+ "visibility": "private",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 12,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ },
+ )
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "detect_unused_internals": False,
+ "min_confidence": 0.0,
+ }
+ )
+
+ internals = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL]
+ assert internals == []
+
+
+def test_unused_internal_skipped_when_imported_by_name():
+ """A private helper imported by name into a sibling module (typical
+ dispatch-table pattern: ``HANDLERS = {"python": _extract_py, ...}``)
+ is reached at runtime via dict lookup — no direct ``calls`` edge
+ will exist, but the ``imports`` edge carries the symbol name. Such
+ helpers must not be flagged as unused internals."""
+ g = _build_graph(
+ nodes={
+ "pkg/python_handler.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "_extract_python",
+ "kind": "function",
+ "visibility": "private",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 15,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ "pkg/dispatch.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 0,
+ "symbols": [],
+ },
+ },
+ edges=[
+ (
+ "pkg/dispatch.py",
+ "pkg/python_handler.py",
+ {"edge_type": "imports", "imported_names": ["_extract_python"]},
+ ),
+ ],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL}
+ assert "_extract_python" not in names
+
+
+def test_unused_internal_still_flagged_when_imports_dont_carry_name():
+ """Sanity check: an ``imports`` edge that does NOT list the private
+ symbol's name (e.g. the importer pulls a different sibling symbol)
+ must not rescue the helper from the unused-internal pass."""
+ g = _build_graph(
+ nodes={
+ "pkg/helpers.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 2,
+ "symbols": [
+ {
+ "name": "_unused_helper",
+ "kind": "function",
+ "visibility": "private",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 8,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ "pkg/consumer.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 0,
+ "symbols": [],
+ },
+ },
+ edges=[
+ (
+ "pkg/consumer.py",
+ "pkg/helpers.py",
+ {"edge_type": "imports", "imported_names": ["something_else"]},
+ ),
+ ],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL}
+ assert "_unused_helper" in names
diff --git a/tests/unit/dead_code/test_web_factory.py b/tests/unit/dead_code/test_web_factory.py
new file mode 100644
index 000000000..f1e3525fa
--- /dev/null
+++ b/tests/unit/dead_code/test_web_factory.py
@@ -0,0 +1,57 @@
+"""Unit tests for DeadCodeAnalyzer."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.dead_code import (
+ DeadCodeAnalyzer,
+ DeadCodeKind,
+)
+from tests.unit.dead_code._helpers import _build_graph
+
+
+ "factory_name",
+ [
+ "create_app",
+ "make_app",
+ "application",
+ "asgi_app",
+ "wsgi_app",
+ "get_asgi_application",
+ "get_wsgi_application",
+ ],
+)
+def test_python_web_factory_not_flagged(factory_name):
+ """FastAPI / Flask / Tornado / aiohttp / Django entry symbols are
+ loaded by an external server via dotted-path string
+ (``module:create_app`` / ``module:application``) — no graph edge
+ exists from the launching server. These conventional names must be
+ in the entry-point allowlist so the unused-export pass skips them."""
+ g = _build_graph(
+ nodes={
+ "myapp/server.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": factory_name,
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 20,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ },
+ edges=[],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze({"detect_unreachable_files": False, "detect_zombie_packages": False})
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
+ assert factory_name not in names
diff --git a/tests/unit/dead_code/test_whitelist_safety.py b/tests/unit/dead_code/test_whitelist_safety.py
new file mode 100644
index 000000000..e2918479c
--- /dev/null
+++ b/tests/unit/dead_code/test_whitelist_safety.py
@@ -0,0 +1,171 @@
+"""Unit tests for DeadCodeAnalyzer."""
+
+from __future__ import annotations
+
+from datetime import timedelta
+
+from repowise.core.analysis.dead_code import (
+ DeadCodeAnalyzer,
+)
+from tests.unit.dead_code._helpers import _build_graph, _now, _old_date
+
+
+def test_whitelist_respected():
+ """A file in the whitelist should NOT be flagged even if it is unreachable."""
+ g = _build_graph(
+ nodes={
+ "pkg/legacy.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 20,
+ "symbols": [],
+ },
+ },
+ )
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "whitelist": ["pkg/legacy.py"],
+ }
+ )
+
+ assert all(f.file_path != "pkg/legacy.py" for f in report.findings)
+
+
+def test_safe_to_delete_conservative():
+ """safe_to_delete is True only when confidence >= 0.7 AND file does not match dynamic patterns."""
+ g = _build_graph(
+ nodes={
+ # High confidence, no dynamic pattern match -> safe
+ "pkg/old_unused.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 5,
+ "symbols": [],
+ },
+ # High confidence, but file stem matches *Handler -> NOT safe
+ "pkg/RequestHandler.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 5,
+ "symbols": [],
+ },
+ # Low confidence (recently touched) -> NOT safe
+ "pkg/fresh.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 5,
+ "symbols": [],
+ },
+ },
+ )
+
+ git_meta = {
+ "pkg/old_unused.py": {
+ "commit_count_90d": 0,
+ "last_commit_at": _old_date(days=365),
+ "age_days": 500,
+ },
+ "pkg/RequestHandler.py": {
+ "commit_count_90d": 0,
+ "last_commit_at": _old_date(days=365),
+ "age_days": 500,
+ },
+ "pkg/fresh.py": {
+ "commit_count_90d": 5,
+ "last_commit_at": _now() - timedelta(days=3),
+ "age_days": 60,
+ },
+ }
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map=git_meta)
+ report = analyzer.analyze(
+ {
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+
+ by_path = {f.file_path: f for f in report.findings}
+ # High confidence + no dynamic pattern -> safe
+ assert by_path["pkg/old_unused.py"].safe_to_delete is True
+ # High confidence but matches *Handler -> not safe
+ assert by_path["pkg/RequestHandler.py"].safe_to_delete is False
+ # Low confidence (0.4) -> not safe
+ assert by_path["pkg/fresh.py"].safe_to_delete is False
+
+
+def test_report_deletable_lines_sum():
+ """report.deletable_lines should equal the sum of lines for safe_to_delete findings."""
+ g = _build_graph(
+ nodes={
+ "pkg/dead1.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 10, # lines = 10 * 10 = 100
+ "symbols": [],
+ },
+ "pkg/dead2.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 20, # lines = 20 * 10 = 200
+ "symbols": [],
+ },
+ "pkg/alive.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 15, # lines = 15 * 10 = 150, but NOT safe
+ "symbols": [],
+ },
+ },
+ )
+
+ git_meta = {
+ "pkg/dead1.py": {
+ "commit_count_90d": 0,
+ "last_commit_at": _old_date(days=365),
+ "age_days": 400,
+ },
+ "pkg/dead2.py": {
+ "commit_count_90d": 0,
+ "last_commit_at": _old_date(days=365),
+ "age_days": 400,
+ },
+ # Recently touched -> confidence 0.4, safe_to_delete=False
+ "pkg/alive.py": {
+ "commit_count_90d": 5,
+ "last_commit_at": _now() - timedelta(days=2),
+ "age_days": 60,
+ },
+ }
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map=git_meta)
+ report = analyzer.analyze(
+ {
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+
+ safe_findings = [f for f in report.findings if f.safe_to_delete]
+ expected_lines = sum(f.lines for f in safe_findings)
+ assert report.deletable_lines == expected_lines
+ # Verify that the safe findings include the two stale files
+ safe_paths = {f.file_path for f in safe_findings}
+ assert "pkg/dead1.py" in safe_paths
+ assert "pkg/dead2.py" in safe_paths
+ assert "pkg/alive.py" not in safe_paths
+ # Verify the actual sum
+ assert report.deletable_lines == 100 + 200
diff --git a/tests/unit/dead_code/test_zombie_packages.py b/tests/unit/dead_code/test_zombie_packages.py
new file mode 100644
index 000000000..83aaa6fa2
--- /dev/null
+++ b/tests/unit/dead_code/test_zombie_packages.py
@@ -0,0 +1,59 @@
+"""Unit tests for DeadCodeAnalyzer."""
+
+from __future__ import annotations
+
+from repowise.core.analysis.dead_code import (
+ DeadCodeAnalyzer,
+ DeadCodeKind,
+)
+from tests.unit.dead_code._helpers import _build_graph
+
+
+def test_zombie_package_detected():
+ """A package with no incoming inter-package imports should be flagged as zombie."""
+ g = _build_graph(
+ nodes={
+ "pkgA/mod1.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 5,
+ "symbols": [],
+ },
+ "pkgA/mod2.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 3,
+ "symbols": [],
+ },
+ "pkgB/mod1.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 7,
+ "symbols": [],
+ },
+ },
+ edges=[
+ # pkgA/mod1 imports from pkgA/mod2 (intra-package only)
+ ("pkgA/mod1.py", "pkgA/mod2.py"),
+ # pkgB has no inter-package importers either, but we focus on pkgA
+ # having NO imports from pkgB -> pkgA
+ ],
+ )
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_exports": False,
+ "min_confidence": 0.0,
+ }
+ )
+
+ zombie = [f for f in report.findings if f.kind == DeadCodeKind.ZOMBIE_PACKAGE]
+ pkgs = [f.package for f in zombie]
+ # Both pkgA and pkgB are zombie since neither has inter-package importers
+ assert "pkgA" in pkgs
+ assert "pkgB" in pkgs
diff --git a/tests/unit/ingestion/parser/__init__.py b/tests/unit/ingestion/parser/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/unit/ingestion/parser/_helpers.py b/tests/unit/ingestion/parser/_helpers.py
new file mode 100644
index 000000000..137c286a9
--- /dev/null
+++ b/tests/unit/ingestion/parser/_helpers.py
@@ -0,0 +1,26 @@
+"""Unit tests for the unified ASTParser.
+
+Tests parse inline byte strings so no filesystem I/O is needed.
+Covers Python, TypeScript, Go, Rust, Java, C++ — one test class per language.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+from repowise.core.ingestion.models import FileInfo
+
+
+def _make_file_info(path: str, language: str) -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=f"/tmp/{path}",
+ language=language,
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
diff --git a/tests/unit/ingestion/parser/conftest.py b/tests/unit/ingestion/parser/conftest.py
new file mode 100644
index 000000000..8c5238231
--- /dev/null
+++ b/tests/unit/ingestion/parser/conftest.py
@@ -0,0 +1,16 @@
+"""Unit tests for the unified ASTParser.
+
+Tests parse inline byte strings so no filesystem I/O is needed.
+Covers Python, TypeScript, Go, Rust, Java, C++ — one test class per language.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.ingestion.parser import ASTParser
+
+
[email protected](scope="module")
+def parser() -> ASTParser:
+ return ASTParser()
diff --git a/tests/unit/ingestion/parser/test_cpp.py b/tests/unit/ingestion/parser/test_cpp.py
new file mode 100644
index 000000000..8a6b70732
--- /dev/null
+++ b/tests/unit/ingestion/parser/test_cpp.py
@@ -0,0 +1,75 @@
+"""Unit tests for the unified ASTParser.
+
+Tests parse inline byte strings so no filesystem I/O is needed.
+Covers Python, TypeScript, Go, Rust, Java, C++ — one test class per language.
+"""
+
+from __future__ import annotations
+
+from repowise.core.ingestion.parser import ASTParser
+from tests.unit.ingestion.parser._helpers import _make_file_info
+
+CPP_SOURCE = b"""#include "calculator.hpp"
+#include <stdexcept>
+#include <string>
+
+namespace sample {
+
+double Calculator::add(double x, double y) {
+ return x + y;
+}
+
+double Calculator::divide(double x, double y) {
+ if (y == 0.0) {
+ throw std::invalid_argument("Division by zero");
+ }
+ return x / y;
+}
+
+} // namespace sample
+"""
+
+
+CPP_HEADER_SOURCE = b"""#pragma once
+
+#include <vector>
+#include "models.hpp"
+
+namespace sample {
+
+class Calculator {
+public:
+ double add(double x, double y);
+ double subtract(double x, double y);
+ double divide(double x, double y);
+
+private:
+ std::vector<int> history_;
+};
+
+} // namespace sample
+"""
+
+
+class TestCppParser:
+ def test_finds_class_in_header(self, parser: ASTParser) -> None:
+ fi = _make_file_info("cpp_pkg/calculator.hpp", "cpp")
+ result = parser.parse_file(fi, CPP_HEADER_SOURCE)
+ classes = [s for s in result.symbols if s.kind == "class"]
+ assert any(s.name == "Calculator" for s in classes)
+
+ def test_finds_functions_in_source(self, parser: ASTParser) -> None:
+ fi = _make_file_info("cpp_pkg/calculator.cpp", "cpp")
+ result = parser.parse_file(fi, CPP_SOURCE)
+ # ``Calculator::add`` style qualified definitions now resolve to
+ # ``kind=method`` with ``parent_name=Calculator``; free functions
+ # stay ``kind=function``. Either way we expect symbols to land.
+ callable_symbols = [s for s in result.symbols if s.kind in ("function", "method")]
+ assert len(callable_symbols) >= 1
+
+ def test_parses_includes(self, parser: ASTParser) -> None:
+ fi = _make_file_info("cpp_pkg/calculator.cpp", "cpp")
+ result = parser.parse_file(fi, CPP_SOURCE)
+ assert len(result.imports) >= 2
+ module_paths = [i.module_path for i in result.imports]
+ assert any("calculator.hpp" in p or "stdexcept" in p for p in module_paths)
diff --git a/tests/unit/ingestion/parser/test_csharp.py b/tests/unit/ingestion/parser/test_csharp.py
new file mode 100644
index 000000000..0bc61a9c6
--- /dev/null
+++ b/tests/unit/ingestion/parser/test_csharp.py
@@ -0,0 +1,215 @@
+"""Unit tests for the unified ASTParser.
+
+Tests parse inline byte strings so no filesystem I/O is needed.
+Covers Python, TypeScript, Go, Rust, Java, C++ — one test class per language.
+"""
+
+from __future__ import annotations
+
+from repowise.core.ingestion.parser import ASTParser
+from tests.unit.ingestion.parser._helpers import _make_file_info
+
+CSHARP_SOURCE = b"""\
+using System;
+using Sample.Models;
+
+namespace Sample
+{
+ /// <summary>Calculator for basic arithmetic.</summary>
+ public class Calculator
+ {
+ public double Add(double x, double y)
+ {
+ return x + y;
+ }
+
+ private void Helper() { }
+ }
+
+ public interface IComputable
+ {
+ double Compute();
+ }
+
+ public enum Operation { Add, Subtract }
+
+ public struct Point
+ {
+ public double X;
+ public double Y;
+ }
+}
+"""
+
+
+class TestCSharpParser:
+ def test_finds_class(self, parser: ASTParser) -> None:
+ fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")
+ result = parser.parse_file(fi, CSHARP_SOURCE)
+ classes = [s for s in result.symbols if s.kind == "class"]
+ assert any(s.name == "Calculator" for s in classes)
+
+ def test_finds_interface(self, parser: ASTParser) -> None:
+ fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")
+ result = parser.parse_file(fi, CSHARP_SOURCE)
+ interfaces = [s for s in result.symbols if s.kind == "interface"]
+ assert any(s.name == "IComputable" for s in interfaces)
+
+ def test_finds_enum(self, parser: ASTParser) -> None:
+ fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")
+ result = parser.parse_file(fi, CSHARP_SOURCE)
+ enums = [s for s in result.symbols if s.kind == "enum"]
+ assert any(s.name == "Operation" for s in enums)
+
+ def test_finds_struct(self, parser: ASTParser) -> None:
+ fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")
+ result = parser.parse_file(fi, CSHARP_SOURCE)
+ structs = [s for s in result.symbols if s.kind == "struct"]
+ assert any(s.name == "Point" for s in structs)
+
+ def test_finds_methods(self, parser: ASTParser) -> None:
+ fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")
+ result = parser.parse_file(fi, CSHARP_SOURCE)
+ methods = [s for s in result.symbols if s.kind == "method"]
+ assert any(s.name == "Add" for s in methods)
+
+ def test_parses_imports(self, parser: ASTParser) -> None:
+ fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")
+ result = parser.parse_file(fi, CSHARP_SOURCE)
+ assert len(result.imports) >= 2
+ modules = {imp.module_path for imp in result.imports}
+ assert "System" in modules
+
+ def test_private_visibility(self, parser: ASTParser) -> None:
+ fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")
+ result = parser.parse_file(fi, CSHARP_SOURCE)
+ helper = next((s for s in result.symbols if s.name == "Helper"), None)
+ assert helper is not None
+ assert helper.visibility == "private"
+
+ def test_no_parse_errors(self, parser: ASTParser) -> None:
+ fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")
+ result = parser.parse_file(fi, CSHARP_SOURCE)
+ assert result.parse_errors == []
+
+
+CSHARP_MODERN_SOURCE = b"""\
+global using System;
+global using static System.Math;
+using Foo = Sample.Very.Long.Namespace.Type;
+using static System.Convert;
+
+namespace Sample.Modern;
+
+public delegate int BinaryOp(int x, int y);
+
+public record User(string Name, int Age);
+
+public record struct Coordinate(double X, double Y);
+
+public class EventBus
+{
+ public event EventHandler<string>? MessageReceived;
+ public string Topic = "default";
+ private const int MaxListeners = 100;
+}
+
+public enum Status { Active, Inactive, Pending }
+"""
+
+
+class TestCSharpModernParser:
+ def test_finds_record(self, parser: ASTParser) -> None:
+ fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")
+ result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)
+ names = {s.name for s in result.symbols}
+ assert "User" in names
+
+ def test_finds_record_struct(self, parser: ASTParser) -> None:
+ fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")
+ result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)
+ names = {s.name for s in result.symbols}
+ assert "Coordinate" in names
+
+ def test_finds_delegate(self, parser: ASTParser) -> None:
+ fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")
+ result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)
+ names = {s.name for s in result.symbols}
+ assert "BinaryOp" in names
+
+ def test_finds_event(self, parser: ASTParser) -> None:
+ fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")
+ result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)
+ names = {s.name for s in result.symbols}
+ assert "MessageReceived" in names
+
+ def test_finds_field(self, parser: ASTParser) -> None:
+ fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")
+ result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)
+ names = {s.name for s in result.symbols}
+ assert "Topic" in names
+ assert "MaxListeners" in names
+
+ def test_finds_enum_member(self, parser: ASTParser) -> None:
+ fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")
+ result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)
+ names = {s.name for s in result.symbols}
+ assert "Active" in names
+ assert "Inactive" in names
+
+ def test_finds_file_scoped_namespace(self, parser: ASTParser) -> None:
+ fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")
+ result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)
+ modules = [s for s in result.symbols if s.kind == "module"]
+ assert any("Sample.Modern" in s.name or s.name == "Sample.Modern" for s in modules)
+
+ def test_imports_capture_global_and_static(self, parser: ASTParser) -> None:
+ fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")
+ result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)
+ modules = {imp.module_path for imp in result.imports}
+ # global using and using static still surface as imports — full flag
+ # propagation (is_global / is_static) lives in the binding extractor.
+ assert "System" in modules
+ assert any("Math" in m for m in modules)
+ assert any("Convert" in m for m in modules)
+ # The alias form `using Foo = Long.Namespace.Type` is captured as the
+ # right-hand qualified name; alias propagation is wired in Batch 3.
+ assert len(result.imports) >= 3
+
+ def test_no_parse_errors(self, parser: ASTParser) -> None:
+ fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")
+ result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)
+ assert result.parse_errors == []
+
+
+class TestCSharpRegistryMetadata:
+ def test_csharp_spec_has_manifest_files(self) -> None:
+ from repowise.core.ingestion.languages.registry import REGISTRY
+
+ spec = REGISTRY.get("csharp")
+ assert spec is not None
+ assert "global.json" in spec.manifest_files
+ assert "Directory.Build.props" in spec.manifest_files
+
+ def test_csharp_spec_has_blocked_dirs(self) -> None:
+ from repowise.core.ingestion.languages.registry import REGISTRY
+
+ spec = REGISTRY.get("csharp")
+ assert spec is not None
+ assert "bin" in spec.blocked_dirs
+ assert "obj" in spec.blocked_dirs
+
+ def test_csharp_spec_has_generated_suffixes(self) -> None:
+ from repowise.core.ingestion.languages.registry import REGISTRY
+
+ spec = REGISTRY.get("csharp")
+ assert spec is not None
+ assert ".g.cs" in spec.generated_suffixes
+ assert ".Designer.cs" in spec.generated_suffixes
+
+ def test_csharp_record_in_heritage_node_types(self) -> None:
+ from repowise.core.ingestion.languages.registry import REGISTRY
+
+ spec = REGISTRY.get("csharp")
+ assert spec is not None
+ assert "record_declaration" in spec.heritage_node_types
diff --git a/tests/unit/ingestion/parser/test_go.py b/tests/unit/ingestion/parser/test_go.py
new file mode 100644
index 000000000..230a61226
--- /dev/null
+++ b/tests/unit/ingestion/parser/test_go.py
@@ -0,0 +1,94 @@
+"""Unit tests for the unified ASTParser.
+
+Tests parse inline byte strings so no filesystem I/O is needed.
+Covers Python, TypeScript, Go, Rust, Java, C++ — one test class per language.
+"""
+
+from __future__ import annotations
+
+from repowise.core.ingestion.parser import ASTParser
+from tests.unit.ingestion.parser._helpers import _make_file_info
+
+GO_SOURCE = b"""// Package calculator provides arithmetic with history.
+package calculator
+
+import (
+ "errors"
+ "fmt"
+
+ "github.com/repowise-ai/sample/types"
+)
+
+// ErrDivisionByZero is returned on division by zero.
+var ErrDivisionByZero = errors.New("division by zero")
+
+// Calculator maintains a calculation history.
+type Calculator struct {
+ history []types.CalculationRecord
+}
+
+// New returns a new Calculator.
+func New() *Calculator {
+ return &Calculator{}
+}
+
+// Add returns the sum of the operands.
+func (c *Calculator) Add(ops types.Operands) (float64, error) {
+ result := ops.X + ops.Y
+ return result, nil
+}
+
+// Divide returns ops.X / ops.Y.
+func (c *Calculator) Divide(ops types.Operands) (float64, error) {
+ if ops.Y == 0 {
+ return 0, ErrDivisionByZero
+ }
+ return ops.X / ops.Y, nil
+}
+"""
+
+
+class TestGoParser:
+ def test_finds_struct(self, parser: ASTParser) -> None:
+ fi = _make_file_info("go_pkg/calculator/calculator.go", "go")
+ result = parser.parse_file(fi, GO_SOURCE)
+ structs = [s for s in result.symbols if s.kind == "struct"]
+ assert any(s.name == "Calculator" for s in structs)
+
+ def test_finds_functions(self, parser: ASTParser) -> None:
+ fi = _make_file_info("go_pkg/calculator/calculator.go", "go")
+ result = parser.parse_file(fi, GO_SOURCE)
+ fns = [s for s in result.symbols if s.kind == "function"]
+ assert any(s.name == "New" for s in fns)
+
+ def test_finds_methods_with_receiver(self, parser: ASTParser) -> None:
+ fi = _make_file_info("go_pkg/calculator/calculator.go", "go")
+ result = parser.parse_file(fi, GO_SOURCE)
+ methods = [s for s in result.symbols if s.kind == "method"]
+ method_names = [m.name for m in methods]
+ assert "Add" in method_names
+ assert "Divide" in method_names
+
+ def test_method_has_parent_from_receiver(self, parser: ASTParser) -> None:
+ fi = _make_file_info("go_pkg/calculator/calculator.go", "go")
+ result = parser.parse_file(fi, GO_SOURCE)
+ add_method = next(s for s in result.symbols if s.name == "Add" and s.kind == "method")
+ assert add_method.parent_name == "Calculator"
+
+ def test_go_visibility_by_capitalisation(self, parser: ASTParser) -> None:
+ fi = _make_file_info("go_pkg/calculator/calculator.go", "go")
+ result = parser.parse_file(fi, GO_SOURCE)
+ new_fn = next(s for s in result.symbols if s.name == "New")
+ assert new_fn.visibility == "public"
+
+ def test_parses_imports(self, parser: ASTParser) -> None:
+ fi = _make_file_info("go_pkg/calculator/calculator.go", "go")
+ result = parser.parse_file(fi, GO_SOURCE)
+ module_paths = [i.module_path for i in result.imports]
+ assert any("errors" in p for p in module_paths)
+ assert any("sample/types" in p for p in module_paths)
+
+ def test_no_parse_errors(self, parser: ASTParser) -> None:
+ fi = _make_file_info("go_pkg/calculator/calculator.go", "go")
+ result = parser.parse_file(fi, GO_SOURCE)
+ assert result.parse_errors == []
diff --git a/tests/unit/ingestion/parser/test_java.py b/tests/unit/ingestion/parser/test_java.py
new file mode 100644
index 000000000..c71372ab9
--- /dev/null
+++ b/tests/unit/ingestion/parser/test_java.py
@@ -0,0 +1,59 @@
+"""Unit tests for the unified ASTParser.
+
+Tests parse inline byte strings so no filesystem I/O is needed.
+Covers Python, TypeScript, Go, Rust, Java, C++ — one test class per language.
+"""
+
+from __future__ import annotations
+
+from repowise.core.ingestion.parser import ASTParser
+from tests.unit.ingestion.parser._helpers import _make_file_info
+
+JAVA_SOURCE = b"""package com.repowise.sample;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Stateful calculator with history.
+ */
+public class Calculator {
+
+ private final List<Object> history = new ArrayList<>();
+
+ /**
+ * Adds x and y.
+ */
+ public double add(double x, double y) {
+ return x + y;
+ }
+
+ /** Private helper. */
+ private void record(Object entry) {
+ history.add(entry);
+ }
+}
+"""
+
+
+class TestJavaParser:
+ def test_finds_class(self, parser: ASTParser) -> None:
+ fi = _make_file_info("java_pkg/Calculator.java", "java")
+ result = parser.parse_file(fi, JAVA_SOURCE)
+ classes = [s for s in result.symbols if s.kind == "class"]
+ assert any(s.name == "Calculator" for s in classes)
+
+ def test_finds_methods(self, parser: ASTParser) -> None:
+ fi = _make_file_info("java_pkg/Calculator.java", "java")
+ result = parser.parse_file(fi, JAVA_SOURCE)
+ methods = [s for s in result.symbols if s.kind == "method"]
+ method_names = [m.name for m in methods]
+ assert "add" in method_names
+ assert "record" in method_names
+
+ def test_parses_imports(self, parser: ASTParser) -> None:
+ fi = _make_file_info("java_pkg/Calculator.java", "java")
+ result = parser.parse_file(fi, JAVA_SOURCE)
+ assert len(result.imports) >= 2
+ module_paths = [i.module_path for i in result.imports]
+ assert any("ArrayList" in p for p in module_paths)
diff --git a/tests/unit/ingestion/parser/test_kotlin.py b/tests/unit/ingestion/parser/test_kotlin.py
new file mode 100644
index 000000000..56d92bfc6
--- /dev/null
+++ b/tests/unit/ingestion/parser/test_kotlin.py
@@ -0,0 +1,64 @@
+"""Unit tests for the unified ASTParser.
+
+Tests parse inline byte strings so no filesystem I/O is needed.
+Covers Python, TypeScript, Go, Rust, Java, C++ — one test class per language.
+"""
+
+from __future__ import annotations
+
+from repowise.core.ingestion.parser import ASTParser
+from tests.unit.ingestion.parser._helpers import _make_file_info
+
+KOTLIN_SOURCE = b"""\
+package sample
+
+import sample.models.Operation
+
+/** Calculator for basic arithmetic. */
+class Calculator {
+ fun add(x: Double, y: Double): Double {
+ val result = x + y
+ return result
+ }
+
+ private fun helper() {}
+}
+
+enum class Operation {
+ ADD, SUBTRACT
+}
+"""
+
+
+class TestKotlinParser:
+ def test_finds_class(self, parser: ASTParser) -> None:
+ fi = _make_file_info("kotlin_pkg/Calculator.kt", "kotlin")
+ result = parser.parse_file(fi, KOTLIN_SOURCE)
+ classes = [s for s in result.symbols if s.kind == "class"]
+ assert any(s.name == "Calculator" for s in classes)
+
+ def test_finds_functions(self, parser: ASTParser) -> None:
+ fi = _make_file_info("kotlin_pkg/Calculator.kt", "kotlin")
+ result = parser.parse_file(fi, KOTLIN_SOURCE)
+ # add is inside Calculator so it becomes a method; check both kinds
+ fns = [s for s in result.symbols if s.kind in ("function", "method")]
+ assert any(s.name == "add" for s in fns)
+
+ def test_parses_imports(self, parser: ASTParser) -> None:
+ fi = _make_file_info("kotlin_pkg/Calculator.kt", "kotlin")
+ result = parser.parse_file(fi, KOTLIN_SOURCE)
+ assert len(result.imports) >= 1
+ modules = {imp.module_path for imp in result.imports}
+ assert any("Operation" in m for m in modules)
+
+ def test_no_parse_errors(self, parser: ASTParser) -> None:
+ fi = _make_file_info("kotlin_pkg/Calculator.kt", "kotlin")
+ result = parser.parse_file(fi, KOTLIN_SOURCE)
+ assert result.parse_errors == []
+
+ def test_private_visibility(self, parser: ASTParser) -> None:
+ fi = _make_file_info("kotlin_pkg/Calculator.kt", "kotlin")
+ result = parser.parse_file(fi, KOTLIN_SOURCE)
+ helper = next((s for s in result.symbols if s.name == "helper"), None)
+ assert helper is not None
+ assert helper.visibility == "private"
diff --git a/tests/unit/ingestion/parser/test_luau.py b/tests/unit/ingestion/parser/test_luau.py
new file mode 100644
index 000000000..61d9300d6
--- /dev/null
+++ b/tests/unit/ingestion/parser/test_luau.py
@@ -0,0 +1,51 @@
+"""Unit tests for the unified ASTParser.
+
+Tests parse inline byte strings so no filesystem I/O is needed.
+Covers Python, TypeScript, Go, Rust, Java, C++ — one test class per language.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.ingestion.parser import ASTParser
+from tests.unit.ingestion.parser._helpers import _make_file_info
+
+LUAU_SOURCE = b"""-- Module docstring placeholder.
+
+local Signal = require(script.Parent.Signal)
+local Shared = require(game.ReplicatedStorage.Shared.Util)
+
+type Callback = (value: number) -> ()
+
+function greet(name: string): string
+ return "hello " .. name
+end
+
+function Calculator:add(x: number, y: number): number
+ return x + y
+end
+"""
+
+
+# tree-sitter-luau is a real dep in pyproject.toml, but it is sometimes
+# absent from a partially-synced developer venv (e.g. when an old `uv pip
+# install -e .` ran before the dep was added). Skip explicitly so the
+# failure mode is "go run uv sync" rather than two confusing AssertionErrors.
+pytest.importorskip("tree_sitter_luau", reason="run `uv sync --all-packages`")
+
+
+class TestLuauParser:
+ def test_finds_top_level_function(self, parser: ASTParser) -> None:
+ fi = _make_file_info("luau_pkg/init.luau", "luau")
+ result = parser.parse_file(fi, LUAU_SOURCE)
+ names = [s.name for s in result.symbols]
+ assert "greet" in names
+
+ def test_parses_require_imports(self, parser: ASTParser) -> None:
+ fi = _make_file_info("luau_pkg/init.luau", "luau")
+ result = parser.parse_file(fi, LUAU_SOURCE)
+ raw = [i.module_path for i in result.imports]
+ # The .scm emits the raw argument text; the resolver interprets it.
+ assert any("Signal" in m for m in raw)
+ assert any("ReplicatedStorage" in m for m in raw)
diff --git a/tests/unit/ingestion/parser/test_misc.py b/tests/unit/ingestion/parser/test_misc.py
new file mode 100644
index 000000000..c45e42044
--- /dev/null
+++ b/tests/unit/ingestion/parser/test_misc.py
@@ -0,0 +1,57 @@
+"""Unit tests for the unified ASTParser.
+
+Tests parse inline byte strings so no filesystem I/O is needed.
+Covers Python, TypeScript, Go, Rust, Java, C++ — one test class per language.
+"""
+
+from __future__ import annotations
+
+from repowise.core.ingestion.parser import LANGUAGE_CONFIGS, ASTParser
+from tests.unit.ingestion.parser._helpers import _make_file_info
+
+
+class TestUnsupportedLanguage:
+ def test_returns_empty_parsed_file(self, parser: ASTParser) -> None:
+ """Unsupported languages return an empty ParsedFile with no errors
+ (silent passthrough by design — see parser.py line 354)."""
+ fi = _make_file_info("file.xyz", "unknown")
+ fi.language = "unknown"
+ result = parser.parse_file(fi, b"some content here")
+ assert result.symbols == []
+ assert result.imports == []
+ assert result.parse_errors == []
+
+
+class TestLanguageConfigs:
+ def test_all_supported_languages_have_config(self) -> None:
+ expected = {
+ "python",
+ "typescript",
+ "javascript",
+ "go",
+ "rust",
+ "java",
+ "cpp",
+ "c",
+ "kotlin",
+ "ruby",
+ "csharp",
+ "swift",
+ "scala",
+ "php",
+ "luau",
+ }
+ for lang in expected:
+ assert lang in LANGUAGE_CONFIGS, f"Missing config for {lang}"
+
+ def test_each_config_has_symbol_node_types(self) -> None:
+ for lang, config in LANGUAGE_CONFIGS.items():
+ assert len(config.symbol_node_types) > 0, f"{lang} has no symbol_node_types"
+
+ def test_each_config_has_visibility_fn(self) -> None:
+ for lang, config in LANGUAGE_CONFIGS.items():
+ # Must be callable
+ result = config.visibility_fn("MyClass", [])
+ assert result in ("public", "private", "protected", "internal"), (
+ f"{lang} visibility_fn returned unexpected: {result}"
+ )
diff --git a/tests/unit/ingestion/parser/test_php.py b/tests/unit/ingestion/parser/test_php.py
new file mode 100644
index 000000000..a03ed2e1d
--- /dev/null
+++ b/tests/unit/ingestion/parser/test_php.py
@@ -0,0 +1,83 @@
+"""Unit tests for the unified ASTParser.
+
+Tests parse inline byte strings so no filesystem I/O is needed.
+Covers Python, TypeScript, Go, Rust, Java, C++ — one test class per language.
+"""
+
+from __future__ import annotations
+
+from repowise.core.ingestion.parser import ASTParser
+from tests.unit.ingestion.parser._helpers import _make_file_info
+
+PHP_SOURCE = b"""\
+<?php
+namespace Sample;
+
+use Sample\\Models\\Operation;
+use Sample\\Models\\CalculationRecord;
+
+/** Calculator for basic arithmetic. */
+class Calculator extends BaseCalc implements Computable
+{
+ public function add(float $x, float $y): float
+ {
+ return $x + $y;
+ }
+
+ private function helper(): void {}
+}
+
+interface Computable
+{
+ public function compute(): float;
+}
+
+enum Operation
+{
+ case Add;
+ case Subtract;
+}
+"""
+
+
+class TestPhpParser:
+ def test_finds_class(self, parser: ASTParser) -> None:
+ fi = _make_file_info("php_pkg/Calculator.php", "php")
+ result = parser.parse_file(fi, PHP_SOURCE)
+ classes = [s for s in result.symbols if s.kind == "class"]
+ assert any(s.name == "Calculator" for s in classes)
+
+ def test_finds_interface(self, parser: ASTParser) -> None:
+ fi = _make_file_info("php_pkg/Calculator.php", "php")
+ result = parser.parse_file(fi, PHP_SOURCE)
+ interfaces = [s for s in result.symbols if s.kind == "interface"]
+ assert any(s.name == "Computable" for s in interfaces)
+
+ def test_finds_enum(self, parser: ASTParser) -> None:
+ fi = _make_file_info("php_pkg/Calculator.php", "php")
+ result = parser.parse_file(fi, PHP_SOURCE)
+ enums = [s for s in result.symbols if s.kind == "enum"]
+ assert any(s.name == "Operation" for s in enums)
+
+ def test_finds_methods(self, parser: ASTParser) -> None:
+ fi = _make_file_info("php_pkg/Calculator.php", "php")
+ result = parser.parse_file(fi, PHP_SOURCE)
+ methods = [s for s in result.symbols if s.kind == "method"]
+ assert any(s.name == "add" for s in methods)
+
+ def test_parses_imports(self, parser: ASTParser) -> None:
+ fi = _make_file_info("php_pkg/Calculator.php", "php")
+ result = parser.parse_file(fi, PHP_SOURCE)
+ assert len(result.imports) >= 1
+
+ def test_private_visibility(self, parser: ASTParser) -> None:
+ fi = _make_file_info("php_pkg/Calculator.php", "php")
+ result = parser.parse_file(fi, PHP_SOURCE)
+ helper = next((s for s in result.symbols if s.name == "helper"), None)
+ assert helper is not None
+ assert helper.visibility == "private"
+
+ def test_no_parse_errors(self, parser: ASTParser) -> None:
+ fi = _make_file_info("php_pkg/Calculator.php", "php")
+ result = parser.parse_file(fi, PHP_SOURCE)
+ assert result.parse_errors == []
diff --git a/tests/unit/ingestion/parser/test_python.py b/tests/unit/ingestion/parser/test_python.py
new file mode 100644
index 000000000..22fb3b58d
--- /dev/null
+++ b/tests/unit/ingestion/parser/test_python.py
@@ -0,0 +1,234 @@
+"""Unit tests for the unified ASTParser.
+
+Tests parse inline byte strings so no filesystem I/O is needed.
+Covers Python, TypeScript, Go, Rust, Java, C++ — one test class per language.
+"""
+
+from __future__ import annotations
+
+from repowise.core.ingestion.parser import ASTParser
+from tests.unit.ingestion.parser._helpers import _make_file_info
+
+PYTHON_SOURCE = b'''"""Module docstring."""
+
+from __future__ import annotations
+
+from python_pkg.models import Operation
+from python_pkg.utils import round_result
+import os
+
+
+class DivisionByZeroError(ArithmeticError):
+ """Raised on division by zero."""
+
+
+def add(x: float, y: float) -> float:
+ """Return x + y."""
+ return x + y
+
+
+def subtract(x: float, y: float) -> float:
+ """Return x - y."""
+ return x - y
+
+
+class Calculator:
+ """Stateful calculator."""
+
+ def __init__(self) -> None:
+ self._history = []
+
+ def add(self, x: float, y: float) -> float:
+ """Add x and y."""
+ return add(x, y)
+
+ @staticmethod
+ def version() -> str:
+ """Return version string."""
+ return "1.0"
+'''
+
+
+class TestPythonParser:
+ def test_module_docstring(self, parser: ASTParser) -> None:
+ fi = _make_file_info("pkg/calc.py", "python")
+ result = parser.parse_file(fi, PYTHON_SOURCE)
+ assert result.docstring == "Module docstring."
+
+ def test_finds_top_level_functions(self, parser: ASTParser) -> None:
+ fi = _make_file_info("pkg/calc.py", "python")
+ result = parser.parse_file(fi, PYTHON_SOURCE)
+ names = [s.name for s in result.symbols]
+ assert "add" in names
+ assert "subtract" in names
+
+ def test_finds_classes(self, parser: ASTParser) -> None:
+ fi = _make_file_info("pkg/calc.py", "python")
+ result = parser.parse_file(fi, PYTHON_SOURCE)
+ classes = [s for s in result.symbols if s.kind == "class"]
+ class_names = [c.name for c in classes]
+ assert "Calculator" in class_names
+ assert "DivisionByZeroError" in class_names
+
+ def test_finds_methods(self, parser: ASTParser) -> None:
+ fi = _make_file_info("pkg/calc.py", "python")
+ result = parser.parse_file(fi, PYTHON_SOURCE)
+ methods = [s for s in result.symbols if s.kind == "method"]
+ method_names = [m.name for m in methods]
+ assert "add" in method_names
+ assert "__init__" in method_names
+
+ def test_method_has_parent(self, parser: ASTParser) -> None:
+ fi = _make_file_info("pkg/calc.py", "python")
+ result = parser.parse_file(fi, PYTHON_SOURCE)
+ calc_add = next(
+ s for s in result.symbols if s.name == "add" and s.parent_name == "Calculator"
+ )
+ assert calc_add.parent_name == "Calculator"
+
+ def test_private_visibility(self, parser: ASTParser) -> None:
+ fi = _make_file_info("pkg/calc.py", "python")
+ result = parser.parse_file(fi, PYTHON_SOURCE)
+ init = next(s for s in result.symbols if s.name == "__init__")
+ # Dunder is public by our convention
+ assert init.visibility == "public"
+
+ def test_parses_imports(self, parser: ASTParser) -> None:
+ fi = _make_file_info("pkg/calc.py", "python")
+ result = parser.parse_file(fi, PYTHON_SOURCE)
+ module_paths = [i.module_path for i in result.imports]
+ assert "python_pkg.models" in module_paths
+ assert "python_pkg.utils" in module_paths
+ assert "os" in module_paths
+
+ def test_from_import_names(self, parser: ASTParser) -> None:
+ fi = _make_file_info("pkg/calc.py", "python")
+ result = parser.parse_file(fi, PYTHON_SOURCE)
+ op_import = next(i for i in result.imports if i.module_path == "python_pkg.models")
+ assert "Operation" in op_import.imported_names
+
+ def test_relative_from_import_single_name(self, parser: ASTParser) -> None:
+ # Regression: `from .X import Y` was dropping the only imported name.
+ fi = _make_file_info("pkg/__init__.py", "python")
+ result = parser.parse_file(fi, b"from .graph import GraphBuilder\n")
+ rel_import = next(i for i in result.imports if "graph" in i.module_path)
+ assert rel_import.imported_names == ["GraphBuilder"]
+
+ def test_relative_from_import_multiple_names_keeps_first(self, parser: ASTParser) -> None:
+ # Regression: `from .X import A, B, C` was dropping `A`.
+ fi = _make_file_info("pkg/__init__.py", "python")
+ result = parser.parse_file(
+ fi, b"from .change_detector import AffectedPages, ChangeDetector, FileDiff\n"
+ )
+ rel_import = next(i for i in result.imports if "change_detector" in i.module_path)
+ assert rel_import.imported_names == ["AffectedPages", "ChangeDetector", "FileDiff"]
+
+ def test_bare_relative_import_expands_to_one_per_submodule(self, parser: ASTParser) -> None:
+ # Regression (D2): ``from . import a, b`` produced one Import with
+ # ``module_path="."`` which the resolver dropped on the floor, so
+ # every plugin-registry barrel silently lost its sibling-submodule
+ # edges. Expansion rewrites each name into ``.a``/``.b`` so the
+ # existing relative-resolver can locate the submodule.
+ fi = _make_file_info("pkg/__init__.py", "python")
+ result = parser.parse_file(fi, b"from . import cargo, go, npm, nuget, pypi\n")
+ paths = sorted(i.module_path for i in result.imports if i.is_relative)
+ assert paths == [".cargo", ".go", ".npm", ".nuget", ".pypi"]
+ for imp in result.imports:
+ if imp.module_path.startswith(".") and imp.module_path != ".":
+ assert len(imp.imported_names) == 1
+ assert imp.imported_names[0] == imp.module_path.lstrip(".")
+
+ def test_bare_double_dot_relative_import_expands(self, parser: ASTParser) -> None:
+ # ``from .. import x`` must also expand, preserving dot depth.
+ fi = _make_file_info("pkg/sub/mod.py", "python")
+ result = parser.parse_file(fi, b"from .. import sibling, other\n")
+ paths = sorted(i.module_path for i in result.imports if i.is_relative)
+ assert paths == ["..other", "..sibling"]
+
+ def test_named_relative_import_is_not_split(self, parser: ASTParser) -> None:
+ # Negative: ``from .pkg import a, b`` must stay as a single Import —
+ # only the bare-dots case is rewritten.
+ fi = _make_file_info("pkg/use.py", "python")
+ result = parser.parse_file(fi, b"from .pkg import a, b\n")
+ rel = [i for i in result.imports if i.module_path == ".pkg"]
+ assert len(rel) == 1
+ assert sorted(rel[0].imported_names) == ["a", "b"]
+
+ def test_absolute_from_import_skips_module_keeps_first_name(self, parser: ASTParser) -> None:
+ # Guard against over-correction: absolute imports must still drop the
+ # module path while keeping every imported name including the first.
+ fi = _make_file_info("pkg/use.py", "python")
+ result = parser.parse_file(fi, b"from python_pkg.models import Operation, Result\n")
+ imp = next(i for i in result.imports if i.module_path == "python_pkg.models")
+ assert imp.imported_names == ["Operation", "Result"]
+
+ def test_nested_function_not_extracted_as_top_level(self, parser: ASTParser) -> None:
+ # Regression (D8): orchestrator-style helpers defined inside an
+ # async method (e.g. ``_on_start``, ``_on_done``, ``_step``) were
+ # flattened to the top-level symbol list and read as unused public
+ # exports. Only module-top-level + class-body members should appear.
+ src = (
+ b"async def run():\n"
+ b" def _on_start():\n"
+ b" pass\n"
+ b" async def _step():\n"
+ b" pass\n"
+ b"\n"
+ b"class Worker:\n"
+ b" async def perform(self):\n"
+ b" def _on_done():\n"
+ b" pass\n"
+ b" return _on_done\n"
+ )
+ fi = _make_file_info("pkg/orchestrator.py", "python")
+ result = parser.parse_file(fi, src)
+ names = {s.name for s in result.symbols}
+ assert names == {"run", "Worker", "perform"}
+ assert "_on_start" not in names
+ assert "_step" not in names
+ assert "_on_done" not in names
+
+ def test_nested_class_inside_function_not_extracted(self, parser: ASTParser) -> None:
+ src = b"def make():\n class Helper:\n def m(self): pass\n"
+ fi = _make_file_info("pkg/factories.py", "python")
+ result = parser.parse_file(fi, src)
+ names = {s.name for s in result.symbols}
+ assert names == {"make"}
+
+ def test_function_docstring(self, parser: ASTParser) -> None:
+ fi = _make_file_info("pkg/calc.py", "python")
+ result = parser.parse_file(fi, PYTHON_SOURCE)
+ add_fn = next(s for s in result.symbols if s.name == "add" and s.parent_name is None)
+ assert add_fn.docstring == "Return x + y."
+
+ def test_class_docstring(self, parser: ASTParser) -> None:
+ fi = _make_file_info("pkg/calc.py", "python")
+ result = parser.parse_file(fi, PYTHON_SOURCE)
+ calc = next(s for s in result.symbols if s.name == "Calculator")
+ assert calc.docstring == "Stateful calculator."
+
+ def test_no_parse_errors_on_valid_source(self, parser: ASTParser) -> None:
+ fi = _make_file_info("pkg/calc.py", "python")
+ result = parser.parse_file(fi, PYTHON_SOURCE)
+ assert result.parse_errors == []
+
+ def test_parse_errors_on_invalid_source(self, parser: ASTParser) -> None:
+ fi = _make_file_info("pkg/bad.py", "python")
+ result = parser.parse_file(fi, b"def (broken syntax: \npass\n")
+ # Should not crash, but should report error
+ assert isinstance(result.parse_errors, list)
+
+ def test_qualified_name(self, parser: ASTParser) -> None:
+ fi = _make_file_info("python_pkg/calculator.py", "python")
+ result = parser.parse_file(fi, PYTHON_SOURCE)
+ calc_add = next(
+ s for s in result.symbols if s.name == "add" and s.parent_name == "Calculator"
+ )
+ assert calc_add.qualified_name == "python_pkg.calculator.Calculator.add"
+
+ def test_exports_list(self, parser: ASTParser) -> None:
+ fi = _make_file_info("pkg/calc.py", "python")
+ result = parser.parse_file(fi, PYTHON_SOURCE)
+ # Public top-level symbols should be in exports
+ assert "add" in result.exports
+ assert "Calculator" in result.exports
diff --git a/tests/unit/ingestion/parser/test_ruby.py b/tests/unit/ingestion/parser/test_ruby.py
new file mode 100644
index 000000000..dbaccf744
--- /dev/null
+++ b/tests/unit/ingestion/parser/test_ruby.py
@@ -0,0 +1,70 @@
+"""Unit tests for the unified ASTParser.
+
+Tests parse inline byte strings so no filesystem I/O is needed.
+Covers Python, TypeScript, Go, Rust, Java, C++ — one test class per language.
+"""
+
+from __future__ import annotations
+
+from repowise.core.ingestion.parser import ASTParser
+from tests.unit.ingestion.parser._helpers import _make_file_info
+
+RUBY_SOURCE = b"""\
+# Calculator module
+require_relative './models'
+
+class Calculator < BaseCalculator
+ def add(x, y)
+ result = x + y
+ record(x, y, result)
+ result
+ end
+
+ def subtract(x, y)
+ x - y
+ end
+
+ def self.create
+ Calculator.new
+ end
+end
+
+module Operations
+ def multiply(x, y)
+ x * y
+ end
+end
+"""
+
+
+class TestRubyParser:
+ def test_finds_class(self, parser: ASTParser) -> None:
+ fi = _make_file_info("ruby_pkg/calculator.rb", "ruby")
+ result = parser.parse_file(fi, RUBY_SOURCE)
+ classes = [s for s in result.symbols if s.kind == "class"]
+ assert any(s.name == "Calculator" for s in classes)
+
+ def test_finds_module(self, parser: ASTParser) -> None:
+ fi = _make_file_info("ruby_pkg/calculator.rb", "ruby")
+ result = parser.parse_file(fi, RUBY_SOURCE)
+ modules = [s for s in result.symbols if s.kind == "module"]
+ assert any(s.name == "Operations" for s in modules)
+
+ def test_finds_methods(self, parser: ASTParser) -> None:
+ fi = _make_file_info("ruby_pkg/calculator.rb", "ruby")
+ result = parser.parse_file(fi, RUBY_SOURCE)
+ # add/subtract are inside Calculator so they become methods
+ fns = [s for s in result.symbols if s.kind in ("function", "method")]
+ names = {s.name for s in fns}
+ assert "add" in names
+ assert "subtract" in names
+
+ def test_parses_imports(self, parser: ASTParser) -> None:
+ fi = _make_file_info("ruby_pkg/calculator.rb", "ruby")
+ result = parser.parse_file(fi, RUBY_SOURCE)
+ assert len(result.imports) >= 1
+
+ def test_no_parse_errors(self, parser: ASTParser) -> None:
+ fi = _make_file_info("ruby_pkg/calculator.rb", "ruby")
+ result = parser.parse_file(fi, RUBY_SOURCE)
+ assert result.parse_errors == []
diff --git a/tests/unit/ingestion/parser/test_rust.py b/tests/unit/ingestion/parser/test_rust.py
new file mode 100644
index 000000000..99905bb89
--- /dev/null
+++ b/tests/unit/ingestion/parser/test_rust.py
@@ -0,0 +1,100 @@
+"""Unit tests for the unified ASTParser.
+
+Tests parse inline byte strings so no filesystem I/O is needed.
+Covers Python, TypeScript, Go, Rust, Java, C++ — one test class per language.
+"""
+
+from __future__ import annotations
+
+from repowise.core.ingestion.parser import ASTParser
+from tests.unit.ingestion.parser._helpers import _make_file_info
+
+RUST_SOURCE = b"""//! Sample Rust calculator.
+
+use std::fmt;
+
+/// Supported operations.
+#[derive(Debug, Clone, Copy)]
+pub enum Operation {
+ Add,
+ Subtract,
+}
+
+/// A single recorded calculation.
+#[derive(Debug, Clone)]
+pub struct CalculationRecord {
+ pub result: f64,
+}
+
+impl CalculationRecord {
+ /// Create a new record.
+ pub fn new(result: f64) -> Self {
+ Self { result }
+ }
+
+ /// Return a summary string.
+ pub fn summary(&self) -> String {
+ format!("{:.2}", self.result)
+ }
+}
+
+/// Add two numbers.
+pub fn add(x: f64, y: f64) -> f64 {
+ x + y
+}
+"""
+
+
+class TestRustParser:
+ def test_finds_enum(self, parser: ASTParser) -> None:
+ fi = _make_file_info("rust_pkg/src/models.rs", "rust")
+ result = parser.parse_file(fi, RUST_SOURCE)
+ enums = [s for s in result.symbols if s.kind == "enum"]
+ assert any(s.name == "Operation" for s in enums)
+
+ def test_finds_struct(self, parser: ASTParser) -> None:
+ fi = _make_file_info("rust_pkg/src/models.rs", "rust")
+ result = parser.parse_file(fi, RUST_SOURCE)
+ structs = [s for s in result.symbols if s.kind == "struct"]
+ assert any(s.name == "CalculationRecord" for s in structs)
+
+ def test_finds_impl_block(self, parser: ASTParser) -> None:
+ fi = _make_file_info("rust_pkg/src/models.rs", "rust")
+ result = parser.parse_file(fi, RUST_SOURCE)
+ impls = [s for s in result.symbols if s.kind == "impl"]
+ assert any(s.name == "CalculationRecord" for s in impls)
+
+ def test_finds_top_level_function(self, parser: ASTParser) -> None:
+ fi = _make_file_info("rust_pkg/src/models.rs", "rust")
+ result = parser.parse_file(fi, RUST_SOURCE)
+ fns = [s for s in result.symbols if s.kind == "function"]
+ assert any(s.name == "add" for s in fns)
+
+ def test_pub_visibility(self, parser: ASTParser) -> None:
+ fi = _make_file_info("rust_pkg/src/models.rs", "rust")
+ result = parser.parse_file(fi, RUST_SOURCE)
+ add_fn = next(s for s in result.symbols if s.name == "add" and s.kind == "function")
+ assert add_fn.visibility == "public"
+
+ def test_parses_use_declaration(self, parser: ASTParser) -> None:
+ fi = _make_file_info("rust_pkg/src/models.rs", "rust")
+ result = parser.parse_file(fi, RUST_SOURCE)
+ assert len(result.imports) >= 1
+
+ def test_path_attribute_preceding_sibling(self, parser: ASTParser) -> None:
+ """#[path = "..."] is a preceding sibling, not a child of mod_item."""
+ src = b'#[path = "csv.rs"]\nmod csv_;\n'
+ fi = _make_file_info("rust_pkg/src/lib.rs", "rust")
+ result = parser.parse_file(fi, src)
+ mod_imports = [i for i in result.imports if i.raw_statement.startswith("mod")]
+ assert len(mod_imports) == 1
+ assert mod_imports[0].module_path == "csv.rs"
+
+ def test_path_attribute_not_applied_to_wrong_mod(self, parser: ASTParser) -> None:
+ """An attribute on one mod must not leak to an unrelated mod."""
+ src = b'#[path = "csv.rs"]\nmod csv_;\nmod normal;\n'
+ fi = _make_file_info("rust_pkg/src/lib.rs", "rust")
+ result = parser.parse_file(fi, src)
+ normal = [i for i in result.imports if "normal" in i.raw_statement]
+ assert len(normal) == 1
+ assert normal[0].module_path == "normal"
diff --git a/tests/unit/ingestion/parser/test_scala.py b/tests/unit/ingestion/parser/test_scala.py
new file mode 100644
index 000000000..1e6a7ca87
--- /dev/null
+++ b/tests/unit/ingestion/parser/test_scala.py
@@ -0,0 +1,68 @@
+"""Unit tests for the unified ASTParser.
+
+Tests parse inline byte strings so no filesystem I/O is needed.
+Covers Python, TypeScript, Go, Rust, Java, C++ — one test class per language.
+"""
+
+from __future__ import annotations
+
+from repowise.core.ingestion.parser import ASTParser
+from tests.unit.ingestion.parser._helpers import _make_file_info
+
+SCALA_SOURCE = b"""\
+package sample
+
+import sample.models.{Operation, CalculationRecord}
+
+/** Calculator for basic arithmetic. */
+class Calculator extends BaseCalc with Computable {
+ def add(x: Double, y: Double): Double = x + y
+
+ private def helper(): Unit = {}
+}
+
+trait Computable {
+ def compute(): Double
+}
+
+object Singleton {
+ val name = "calc"
+}
+"""
+
+
+class TestScalaParser:
+ def test_finds_class(self, parser: ASTParser) -> None:
+ fi = _make_file_info("scala_pkg/Calculator.scala", "scala")
+ result = parser.parse_file(fi, SCALA_SOURCE)
+ classes = [s for s in result.symbols if s.kind == "class"]
+ assert any(s.name == "Calculator" for s in classes)
+
+ def test_finds_trait(self, parser: ASTParser) -> None:
+ fi = _make_file_info("scala_pkg/Calculator.scala", "scala")
+ result = parser.parse_file(fi, SCALA_SOURCE)
+ traits = [s for s in result.symbols if s.kind == "trait"]
+ assert any(s.name == "Computable" for s in traits)
+
+ def test_finds_object(self, parser: ASTParser) -> None:
+ fi = _make_file_info("scala_pkg/Calculator.scala", "scala")
+ result = parser.parse_file(fi, SCALA_SOURCE)
+ objs = [s for s in result.symbols if s.name == "Singleton"]
+ assert len(objs) >= 1
+
+ def test_finds_functions(self, parser: ASTParser) -> None:
+ fi = _make_file_info("scala_pkg/Calculator.scala", "scala")
+ result = parser.parse_file(fi, SCALA_SOURCE)
+ # def inside a class is promoted to "method"; top-level def stays "function"
+ fns = [s for s in result.symbols if s.kind in ("function", "method")]
+ assert any(s.name == "add" for s in fns)
+
+ def test_parses_imports(self, parser: ASTParser) -> None:
+ fi = _make_file_info("scala_pkg/Calculator.scala", "scala")
+ result = parser.parse_file(fi, SCALA_SOURCE)
+ assert len(result.imports) >= 1
+
+ def test_no_parse_errors(self, parser: ASTParser) -> None:
+ fi = _make_file_info("scala_pkg/Calculator.scala", "scala")
+ result = parser.parse_file(fi, SCALA_SOURCE)
+ assert result.parse_errors == []
diff --git a/tests/unit/ingestion/parser/test_swift.py b/tests/unit/ingestion/parser/test_swift.py
new file mode 100644
index 000000000..cb7e30251
--- /dev/null
+++ b/tests/unit/ingestion/parser/test_swift.py
@@ -0,0 +1,77 @@
+"""Unit tests for the unified ASTParser.
+
+Tests parse inline byte strings so no filesystem I/O is needed.
+Covers Python, TypeScript, Go, Rust, Java, C++ — one test class per language.
+"""
+
+from __future__ import annotations
+
+from repowise.core.ingestion.parser import ASTParser
+from tests.unit.ingestion.parser._helpers import _make_file_info
+
+SWIFT_SOURCE = b"""\
+import Foundation
+
+/// Calculator for basic arithmetic.
+class Calculator: Computable {
+ func add(x: Double, y: Double) -> Double {
+ return x + y
+ }
+
+ private func helper() {}
+}
+
+protocol Computable {
+ func compute() -> Double
+}
+
+enum Operation {
+ case add
+ case subtract
+}
+
+struct Point {
+ var x: Double
+ var y: Double
+}
+"""
+
+
+class TestSwiftParser:
+ def test_finds_class(self, parser: ASTParser) -> None:
+ fi = _make_file_info("swift_pkg/Calculator.swift", "swift")
+ result = parser.parse_file(fi, SWIFT_SOURCE)
+ classes = [s for s in result.symbols if s.kind == "class"]
+ assert any(s.name == "Calculator" for s in classes)
+
+ def test_finds_protocol(self, parser: ASTParser) -> None:
+ fi = _make_file_info("swift_pkg/Calculator.swift", "swift")
+ result = parser.parse_file(fi, SWIFT_SOURCE)
+ interfaces = [s for s in result.symbols if s.kind == "interface"]
+ assert any(s.name == "Computable" for s in interfaces)
+
+ def test_finds_functions(self, parser: ASTParser) -> None:
+ fi = _make_file_info("swift_pkg/Calculator.swift", "swift")
+ result = parser.parse_file(fi, SWIFT_SOURCE)
+ # Functions inside a class are upgraded to "method"
+ fns = [s for s in result.symbols if s.kind in ("function", "method")]
+ assert any(s.name == "add" for s in fns)
+
+ def test_parses_imports(self, parser: ASTParser) -> None:
+ fi = _make_file_info("swift_pkg/Calculator.swift", "swift")
+ result = parser.parse_file(fi, SWIFT_SOURCE)
+ assert len(result.imports) >= 1
+ modules = {imp.module_path for imp in result.imports}
+ assert any("Foundation" in m for m in modules)
+
+ def test_private_visibility(self, parser: ASTParser) -> None:
+ fi = _make_file_info("swift_pkg/Calculator.swift", "swift")
+ result = parser.parse_file(fi, SWIFT_SOURCE)
+ helper = next((s for s in result.symbols if s.name == "helper"), None)
+ assert helper is not None
+ assert helper.visibility == "private"
+
+ def test_no_parse_errors(self, parser: ASTParser) -> None:
+ fi = _make_file_info("swift_pkg/Calculator.swift", "swift")
+ result = parser.parse_file(fi, SWIFT_SOURCE)
+ assert result.parse_errors == []
diff --git a/tests/unit/ingestion/parser/test_typescript.py b/tests/unit/ingestion/parser/test_typescript.py
new file mode 100644
index 000000000..945ad4158
--- /dev/null
+++ b/tests/unit/ingestion/parser/test_typescript.py
@@ -0,0 +1,209 @@
+"""Unit tests for the unified ASTParser.
+
+Tests parse inline byte strings so no filesystem I/O is needed.
+Covers Python, TypeScript, Go, Rust, Java, C++ — one test class per language.
+"""
+
+from __future__ import annotations
+
+from repowise.core.ingestion.parser import ASTParser
+from tests.unit.ingestion.parser._helpers import _make_file_info
+
+TS_SOURCE = b"""/**
+ * Sample TypeScript client module.
+ * Exports ApiClient and related types.
+ */
+
+import type {
+ ApiClientConfig,
+ CalculationRequest,
+ CalculationResponse,
+} from "./types";
+import { validateRequest, parseApiError } from "./utils";
+
+/** Error from the API. */
+export class ApiClientError extends Error {
+ public readonly apiError: unknown;
+ constructor(apiError: unknown) {
+ super("API error");
+ this.apiError = apiError;
+ }
+}
+
+/** Validation error. */
+export class ValidationError extends Error {}
+
+const DEFAULT_TIMEOUT_MS = 10_000;
+
+/** Typed HTTP client. */
+export class ApiClient {
+ private readonly baseUrl: string;
+
+ constructor(config: ApiClientConfig) {
+ this.baseUrl = config.baseUrl;
+ }
+
+ async calculate(request: CalculationRequest): Promise<CalculationResponse> {
+ return this.post("/calculations", request);
+ }
+
+ async healthCheck(): Promise<boolean> {
+ return true;
+ }
+
+ private async post<T>(path: string, body: unknown): Promise<T> {
+ return {} as T;
+ }
+}
+
+export function createClient(config: ApiClientConfig): ApiClient {
+ return new ApiClient(config);
+}
+"""
+
+
+class TestTypeScriptParser:
+ def test_finds_classes(self, parser: ASTParser) -> None:
+ fi = _make_file_info("typescript_pkg/src/client.ts", "typescript")
+ result = parser.parse_file(fi, TS_SOURCE)
+ class_names = [s.name for s in result.symbols if s.kind == "class"]
+ assert "ApiClient" in class_names
+ assert "ApiClientError" in class_names
+ assert "ValidationError" in class_names
+
+ def test_finds_methods(self, parser: ASTParser) -> None:
+ fi = _make_file_info("typescript_pkg/src/client.ts", "typescript")
+ result = parser.parse_file(fi, TS_SOURCE)
+ method_names = [s.name for s in result.symbols if s.kind == "method"]
+ assert "calculate" in method_names
+ assert "healthCheck" in method_names
+
+ def test_finds_top_level_function(self, parser: ASTParser) -> None:
+ fi = _make_file_info("typescript_pkg/src/client.ts", "typescript")
+ result = parser.parse_file(fi, TS_SOURCE)
+ fn_names = [s.name for s in result.symbols if s.kind == "function"]
+ assert "createClient" in fn_names
+
+ def test_parses_imports(self, parser: ASTParser) -> None:
+ fi = _make_file_info("typescript_pkg/src/client.ts", "typescript")
+ result = parser.parse_file(fi, TS_SOURCE)
+ module_paths = [i.module_path for i in result.imports]
+ assert "./types" in module_paths
+ assert "./utils" in module_paths
+
+ def test_relative_imports_flagged(self, parser: ASTParser) -> None:
+ fi = _make_file_info("typescript_pkg/src/client.ts", "typescript")
+ result = parser.parse_file(fi, TS_SOURCE)
+ types_import = next(i for i in result.imports if i.module_path == "./types")
+ assert types_import.is_relative is True
+
+ def test_no_parse_errors(self, parser: ASTParser) -> None:
+ fi = _make_file_info("typescript_pkg/src/client.ts", "typescript")
+ result = parser.parse_file(fi, TS_SOURCE)
+ assert result.parse_errors == []
+
+ def test_nested_helpers_inside_component_not_extracted(self, parser: ASTParser) -> None:
+ # Regression (D5): React component bodies contain helper function
+ # declarations and arrow-const handlers (``handleSave``,
+ # ``handleKeyDown``, ``Section``) that were being flattened to
+ # top-level public symbols and surfacing as ``unused_export``
+ # findings with confidence 1.0.
+ src = b"""
+export function GeneralForm({ onSave }: Props) {
+ function addPattern(p: string) { return p; }
+ async function handleSave() { onSave(); }
+ const Section = ({ title }: { title: string }) => <div>{title}</div>;
+ const handleKeyDown = (e: KeyboardEvent) => { e.preventDefault(); };
+ return <Section title="x" />;
+}
+
+export const Wrapper = () => {
+ const inner = () => 42;
+ return inner();
+};
+"""
+ fi = _make_file_info("ui/src/general-form.tsx", "typescript")
+ result = parser.parse_file(fi, src)
+ names = {s.name for s in result.symbols}
+ assert "GeneralForm" in names
+ assert "Wrapper" in names
+ for hidden in ("addPattern", "handleSave", "Section", "handleKeyDown", "inner"):
+ assert hidden not in names, f"nested helper {hidden} leaked to top level"
+
+ def test_tsx_file_uses_jsx_grammar(self, parser: ASTParser) -> None:
+ # .tsx files require the JSX-aware grammar variant; the default
+ # typescript grammar errors out on ``<Component />`` and recovers
+ # by hoisting nested helpers out of the broken component body.
+ src = b"""
+export function Card({ title }: { title: string }) {
+ function handleClick() { console.log("clicked"); }
+ return <div onClick={handleClick}>{title}</div>;
+}
+"""
+ fi = _make_file_info("ui/src/card.tsx", "typescript")
+ result = parser.parse_file(fi, src)
+ assert result.parse_errors == []
+ names = {s.name for s in result.symbols}
+ assert "Card" in names
+ assert "handleClick" not in names
+
+ def test_jsx_element_registers_as_call_target(self, parser: ASTParser) -> None:
+ # Regression: ``<StatRow ... />`` inside the same file as the
+ # ``StatRow`` component definition was not registering as a call,
+ # so same-file-only sub-components surfaced as unused public
+ # exports at confidence 1.0. The tsx-specific JSX captures now
+ # emit a CallSite for both self-closing and paired elements.
+ src = b"""
+export function StatRow({ value }: { value: number }) {
+ return <span>{value}</span>;
+}
+
+export function Section({ title }: { title: string }) {
+ return <h2>{title}</h2>;
+}
+
+export function Card() {
+ return (
+ <div>
+ <Section title="x" />
+ <StatRow value={1}></StatRow>
+ </div>
+ );
+}
+"""
+ fi = _make_file_info("ui/src/card.tsx", "typescript")
+ result = parser.parse_file(fi, src)
+ targets = {c.target_name for c in result.calls}
+ assert "StatRow" in targets
+ assert "Section" in targets
+
+ def test_jsx_element_call_works_for_jsx_grammar(self, parser: ASTParser) -> None:
+ # Same behaviour for .jsx (plain JavaScript grammar already
+ # supports JSX node types natively).
+ src = b"""
+export function StatRow({ value }) {
+ return <span>{value}</span>;
+}
+
+export function Card() {
+ return <StatRow value={1} />;
+}
+"""
+ fi = _make_file_info("ui/src/card.jsx", "javascript")
+ result = parser.parse_file(fi, src)
+ targets = {c.target_name for c in result.calls}
+ assert "StatRow" in targets
+
+ def test_class_methods_still_extracted(self, parser: ASTParser) -> None:
+ # Negative for D5: methods inside class bodies must still be
+ # extracted — only function/method *bodies* count as nesting.
+ src = b"""
+export class Service {
+ run() { return 1; }
+ private helper() { return 2; }
+}
+"""
+ fi = _make_file_info("ui/src/service.ts", "typescript")
+ result = parser.parse_file(fi, src)
+ method_names = {s.name for s in result.symbols if s.kind == "method"}
+ assert {"run", "helper"} <= method_names
diff --git a/tests/unit/ingestion/test_parser.py b/tests/unit/ingestion/test_parser.py
deleted file mode 100644
index 4182d6145..000000000
--- a/tests/unit/ingestion/test_parser.py
+++ /dev/null
@@ -1,1436 +0,0 @@
-"""Unit tests for the unified ASTParser.
-
-Tests parse inline byte strings so no filesystem I/O is needed.
-Covers Python, TypeScript, Go, Rust, Java, C++ — one test class per language.
-"""
-
-from __future__ import annotations
-
-from datetime import datetime
-
-import pytest
-
-from repowise.core.ingestion.models import FileInfo
-from repowise.core.ingestion.parser import LANGUAGE_CONFIGS, ASTParser
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-
-def _make_file_info(path: str, language: str) -> FileInfo:
- return FileInfo(
- path=path,
- abs_path=f"/tmp/{path}",
- language=language,
- size_bytes=100,
- git_hash="",
- last_modified=datetime.now(),
- is_test=False,
- is_config=False,
- is_api_contract=False,
- is_entry_point=False,
- )
-
-
[email protected](scope="module")
-def parser() -> ASTParser:
- return ASTParser()
-
-
-# ---------------------------------------------------------------------------
-# Python
-# ---------------------------------------------------------------------------
-
-PYTHON_SOURCE = b'''"""Module docstring."""
-
-from __future__ import annotations
-
-from python_pkg.models import Operation
-from python_pkg.utils import round_result
-import os
-
-
-class DivisionByZeroError(ArithmeticError):
- """Raised on division by zero."""
-
-
-def add(x: float, y: float) -> float:
- """Return x + y."""
- return x + y
-
-
-def subtract(x: float, y: float) -> float:
- """Return x - y."""
- return x - y
-
-
-class Calculator:
- """Stateful calculator."""
-
- def __init__(self) -> None:
- self._history = []
-
- def add(self, x: float, y: float) -> float:
- """Add x and y."""
- return add(x, y)
-
- @staticmethod
- def version() -> str:
- """Return version string."""
- return "1.0"
-'''
-
-
-class TestPythonParser:
- def test_module_docstring(self, parser: ASTParser) -> None:
- fi = _make_file_info("pkg/calc.py", "python")
- result = parser.parse_file(fi, PYTHON_SOURCE)
- assert result.docstring == "Module docstring."
-
- def test_finds_top_level_functions(self, parser: ASTParser) -> None:
- fi = _make_file_info("pkg/calc.py", "python")
- result = parser.parse_file(fi, PYTHON_SOURCE)
- names = [s.name for s in result.symbols]
- assert "add" in names
- assert "subtract" in names
-
- def test_finds_classes(self, parser: ASTParser) -> None:
- fi = _make_file_info("pkg/calc.py", "python")
- result = parser.parse_file(fi, PYTHON_SOURCE)
- classes = [s for s in result.symbols if s.kind == "class"]
- class_names = [c.name for c in classes]
- assert "Calculator" in class_names
- assert "DivisionByZeroError" in class_names
-
- def test_finds_methods(self, parser: ASTParser) -> None:
- fi = _make_file_info("pkg/calc.py", "python")
- result = parser.parse_file(fi, PYTHON_SOURCE)
- methods = [s for s in result.symbols if s.kind == "method"]
- method_names = [m.name for m in methods]
- assert "add" in method_names
- assert "__init__" in method_names
-
- def test_method_has_parent(self, parser: ASTParser) -> None:
- fi = _make_file_info("pkg/calc.py", "python")
- result = parser.parse_file(fi, PYTHON_SOURCE)
- calc_add = next(
- s for s in result.symbols if s.name == "add" and s.parent_name == "Calculator"
- )
- assert calc_add.parent_name == "Calculator"
-
- def test_private_visibility(self, parser: ASTParser) -> None:
- fi = _make_file_info("pkg/calc.py", "python")
- result = parser.parse_file(fi, PYTHON_SOURCE)
- init = next(s for s in result.symbols if s.name == "__init__")
- # Dunder is public by our convention
- assert init.visibility == "public"
-
- def test_parses_imports(self, parser: ASTParser) -> None:
- fi = _make_file_info("pkg/calc.py", "python")
- result = parser.parse_file(fi, PYTHON_SOURCE)
- module_paths = [i.module_path for i in result.imports]
- assert "python_pkg.models" in module_paths
- assert "python_pkg.utils" in module_paths
- assert "os" in module_paths
-
- def test_from_import_names(self, parser: ASTParser) -> None:
- fi = _make_file_info("pkg/calc.py", "python")
- result = parser.parse_file(fi, PYTHON_SOURCE)
- op_import = next(i for i in result.imports if i.module_path == "python_pkg.models")
- assert "Operation" in op_import.imported_names
-
- def test_relative_from_import_single_name(self, parser: ASTParser) -> None:
- # Regression: `from .X import Y` was dropping the only imported name.
- fi = _make_file_info("pkg/__init__.py", "python")
- result = parser.parse_file(fi, b"from .graph import GraphBuilder\n")
- rel_import = next(i for i in result.imports if "graph" in i.module_path)
- assert rel_import.imported_names == ["GraphBuilder"]
-
- def test_relative_from_import_multiple_names_keeps_first(
- self, parser: ASTParser
- ) -> None:
- # Regression: `from .X import A, B, C` was dropping `A`.
- fi = _make_file_info("pkg/__init__.py", "python")
- result = parser.parse_file(
- fi, b"from .change_detector import AffectedPages, ChangeDetector, FileDiff\n"
- )
- rel_import = next(i for i in result.imports if "change_detector" in i.module_path)
- assert rel_import.imported_names == ["AffectedPages", "ChangeDetector", "FileDiff"]
-
- def test_bare_relative_import_expands_to_one_per_submodule(
- self, parser: ASTParser
- ) -> None:
- # Regression (D2): ``from . import a, b`` produced one Import with
- # ``module_path="."`` which the resolver dropped on the floor, so
- # every plugin-registry barrel silently lost its sibling-submodule
- # edges. Expansion rewrites each name into ``.a``/``.b`` so the
- # existing relative-resolver can locate the submodule.
- fi = _make_file_info("pkg/__init__.py", "python")
- result = parser.parse_file(
- fi, b"from . import cargo, go, npm, nuget, pypi\n"
- )
- paths = sorted(i.module_path for i in result.imports if i.is_relative)
- assert paths == [".cargo", ".go", ".npm", ".nuget", ".pypi"]
- for imp in result.imports:
- if imp.module_path.startswith(".") and imp.module_path != ".":
- assert len(imp.imported_names) == 1
- assert imp.imported_names[0] == imp.module_path.lstrip(".")
-
- def test_bare_double_dot_relative_import_expands(self, parser: ASTParser) -> None:
- # ``from .. import x`` must also expand, preserving dot depth.
- fi = _make_file_info("pkg/sub/mod.py", "python")
- result = parser.parse_file(fi, b"from .. import sibling, other\n")
- paths = sorted(i.module_path for i in result.imports if i.is_relative)
- assert paths == ["..other", "..sibling"]
-
- def test_named_relative_import_is_not_split(self, parser: ASTParser) -> None:
- # Negative: ``from .pkg import a, b`` must stay as a single Import —
- # only the bare-dots case is rewritten.
- fi = _make_file_info("pkg/use.py", "python")
- result = parser.parse_file(fi, b"from .pkg import a, b\n")
- rel = [i for i in result.imports if i.module_path == ".pkg"]
- assert len(rel) == 1
- assert sorted(rel[0].imported_names) == ["a", "b"]
-
- def test_absolute_from_import_skips_module_keeps_first_name(
- self, parser: ASTParser
- ) -> None:
- # Guard against over-correction: absolute imports must still drop the
- # module path while keeping every imported name including the first.
- fi = _make_file_info("pkg/use.py", "python")
- result = parser.parse_file(
- fi, b"from python_pkg.models import Operation, Result\n"
- )
- imp = next(i for i in result.imports if i.module_path == "python_pkg.models")
- assert imp.imported_names == ["Operation", "Result"]
-
- def test_nested_function_not_extracted_as_top_level(self, parser: ASTParser) -> None:
- # Regression (D8): orchestrator-style helpers defined inside an
- # async method (e.g. ``_on_start``, ``_on_done``, ``_step``) were
- # flattened to the top-level symbol list and read as unused public
- # exports. Only module-top-level + class-body members should appear.
- src = (
- b"async def run():\n"
- b" def _on_start():\n"
- b" pass\n"
- b" async def _step():\n"
- b" pass\n"
- b"\n"
- b"class Worker:\n"
- b" async def perform(self):\n"
- b" def _on_done():\n"
- b" pass\n"
- b" return _on_done\n"
- )
- fi = _make_file_info("pkg/orchestrator.py", "python")
- result = parser.parse_file(fi, src)
- names = {s.name for s in result.symbols}
- assert names == {"run", "Worker", "perform"}
- assert "_on_start" not in names
- assert "_step" not in names
- assert "_on_done" not in names
-
- def test_nested_class_inside_function_not_extracted(self, parser: ASTParser) -> None:
- src = (
- b"def make():\n"
- b" class Helper:\n"
- b" def m(self): pass\n"
- )
- fi = _make_file_info("pkg/factories.py", "python")
- result = parser.parse_file(fi, src)
- names = {s.name for s in result.symbols}
- assert names == {"make"}
-
- def test_function_docstring(self, parser: ASTParser) -> None:
- fi = _make_file_info("pkg/calc.py", "python")
- result = parser.parse_file(fi, PYTHON_SOURCE)
- add_fn = next(s for s in result.symbols if s.name == "add" and s.parent_name is None)
- assert add_fn.docstring == "Return x + y."
-
- def test_class_docstring(self, parser: ASTParser) -> None:
- fi = _make_file_info("pkg/calc.py", "python")
- result = parser.parse_file(fi, PYTHON_SOURCE)
- calc = next(s for s in result.symbols if s.name == "Calculator")
- assert calc.docstring == "Stateful calculator."
-
- def test_no_parse_errors_on_valid_source(self, parser: ASTParser) -> None:
- fi = _make_file_info("pkg/calc.py", "python")
- result = parser.parse_file(fi, PYTHON_SOURCE)
- assert result.parse_errors == []
-
- def test_parse_errors_on_invalid_source(self, parser: ASTParser) -> None:
- fi = _make_file_info("pkg/bad.py", "python")
- result = parser.parse_file(fi, b"def (broken syntax: \npass\n")
- # Should not crash, but should report error
- assert isinstance(result.parse_errors, list)
-
- def test_qualified_name(self, parser: ASTParser) -> None:
- fi = _make_file_info("python_pkg/calculator.py", "python")
- result = parser.parse_file(fi, PYTHON_SOURCE)
- calc_add = next(
- s for s in result.symbols if s.name == "add" and s.parent_name == "Calculator"
- )
- assert calc_add.qualified_name == "python_pkg.calculator.Calculator.add"
-
- def test_exports_list(self, parser: ASTParser) -> None:
- fi = _make_file_info("pkg/calc.py", "python")
- result = parser.parse_file(fi, PYTHON_SOURCE)
- # Public top-level symbols should be in exports
- assert "add" in result.exports
- assert "Calculator" in result.exports
-
-
-# ---------------------------------------------------------------------------
-# TypeScript
-# ---------------------------------------------------------------------------
-
-TS_SOURCE = b"""/**
- * Sample TypeScript client module.
- * Exports ApiClient and related types.
- */
-
-import type {
- ApiClientConfig,
- CalculationRequest,
- CalculationResponse,
-} from "./types";
-import { validateRequest, parseApiError } from "./utils";
-
-/** Error from the API. */
-export class ApiClientError extends Error {
- public readonly apiError: unknown;
- constructor(apiError: unknown) {
- super("API error");
- this.apiError = apiError;
- }
-}
-
-/** Validation error. */
-export class ValidationError extends Error {}
-
-const DEFAULT_TIMEOUT_MS = 10_000;
-
-/** Typed HTTP client. */
-export class ApiClient {
- private readonly baseUrl: string;
-
- constructor(config: ApiClientConfig) {
- this.baseUrl = config.baseUrl;
- }
-
- async calculate(request: CalculationRequest): Promise<CalculationResponse> {
- return this.post("/calculations", request);
- }
-
- async healthCheck(): Promise<boolean> {
- return true;
- }
-
- private async post<T>(path: string, body: unknown): Promise<T> {
- return {} as T;
- }
-}
-
-export function createClient(config: ApiClientConfig): ApiClient {
- return new ApiClient(config);
-}
-"""
-
-
-class TestTypeScriptParser:
- def test_finds_classes(self, parser: ASTParser) -> None:
- fi = _make_file_info("typescript_pkg/src/client.ts", "typescript")
- result = parser.parse_file(fi, TS_SOURCE)
- class_names = [s.name for s in result.symbols if s.kind == "class"]
- assert "ApiClient" in class_names
- assert "ApiClientError" in class_names
- assert "ValidationError" in class_names
-
- def test_finds_methods(self, parser: ASTParser) -> None:
- fi = _make_file_info("typescript_pkg/src/client.ts", "typescript")
- result = parser.parse_file(fi, TS_SOURCE)
- method_names = [s.name for s in result.symbols if s.kind == "method"]
- assert "calculate" in method_names
- assert "healthCheck" in method_names
-
- def test_finds_top_level_function(self, parser: ASTParser) -> None:
- fi = _make_file_info("typescript_pkg/src/client.ts", "typescript")
- result = parser.parse_file(fi, TS_SOURCE)
- fn_names = [s.name for s in result.symbols if s.kind == "function"]
- assert "createClient" in fn_names
-
- def test_parses_imports(self, parser: ASTParser) -> None:
- fi = _make_file_info("typescript_pkg/src/client.ts", "typescript")
- result = parser.parse_file(fi, TS_SOURCE)
- module_paths = [i.module_path for i in result.imports]
- assert "./types" in module_paths
- assert "./utils" in module_paths
-
- def test_relative_imports_flagged(self, parser: ASTParser) -> None:
- fi = _make_file_info("typescript_pkg/src/client.ts", "typescript")
- result = parser.parse_file(fi, TS_SOURCE)
- types_import = next(i for i in result.imports if i.module_path == "./types")
- assert types_import.is_relative is True
-
- def test_no_parse_errors(self, parser: ASTParser) -> None:
- fi = _make_file_info("typescript_pkg/src/client.ts", "typescript")
- result = parser.parse_file(fi, TS_SOURCE)
- assert result.parse_errors == []
-
- def test_nested_helpers_inside_component_not_extracted(
- self, parser: ASTParser
- ) -> None:
- # Regression (D5): React component bodies contain helper function
- # declarations and arrow-const handlers (``handleSave``,
- # ``handleKeyDown``, ``Section``) that were being flattened to
- # top-level public symbols and surfacing as ``unused_export``
- # findings with confidence 1.0.
- src = b"""
-export function GeneralForm({ onSave }: Props) {
- function addPattern(p: string) { return p; }
- async function handleSave() { onSave(); }
- const Section = ({ title }: { title: string }) => <div>{title}</div>;
- const handleKeyDown = (e: KeyboardEvent) => { e.preventDefault(); };
- return <Section title="x" />;
-}
-
-export const Wrapper = () => {
- const inner = () => 42;
- return inner();
-};
-"""
- fi = _make_file_info("ui/src/general-form.tsx", "typescript")
- result = parser.parse_file(fi, src)
- names = {s.name for s in result.symbols}
- assert "GeneralForm" in names
- assert "Wrapper" in names
- for hidden in ("addPattern", "handleSave", "Section", "handleKeyDown", "inner"):
- assert hidden not in names, f"nested helper {hidden} leaked to top level"
-
- def test_tsx_file_uses_jsx_grammar(self, parser: ASTParser) -> None:
- # .tsx files require the JSX-aware grammar variant; the default
- # typescript grammar errors out on ``<Component />`` and recovers
- # by hoisting nested helpers out of the broken component body.
- src = b"""
-export function Card({ title }: { title: string }) {
- function handleClick() { console.log("clicked"); }
- return <div onClick={handleClick}>{title}</div>;
-}
-"""
- fi = _make_file_info("ui/src/card.tsx", "typescript")
- result = parser.parse_file(fi, src)
- assert result.parse_errors == []
- names = {s.name for s in result.symbols}
- assert "Card" in names
- assert "handleClick" not in names
-
- def test_jsx_element_registers_as_call_target(self, parser: ASTParser) -> None:
- # Regression: ``<StatRow ... />`` inside the same file as the
- # ``StatRow`` component definition was not registering as a call,
- # so same-file-only sub-components surfaced as unused public
- # exports at confidence 1.0. The tsx-specific JSX captures now
- # emit a CallSite for both self-closing and paired elements.
- src = b"""
-export function StatRow({ value }: { value: number }) {
- return <span>{value}</span>;
-}
-
-export function Section({ title }: { title: string }) {
- return <h2>{title}</h2>;
-}
-
-export function Card() {
- return (
- <div>
- <Section title="x" />
- <StatRow value={1}></StatRow>
- </div>
- );
-}
-"""
- fi = _make_file_info("ui/src/card.tsx", "typescript")
- result = parser.parse_file(fi, src)
- targets = {c.target_name for c in result.calls}
- assert "StatRow" in targets
- assert "Section" in targets
-
- def test_jsx_element_call_works_for_jsx_grammar(
- self, parser: ASTParser
- ) -> None:
- # Same behaviour for .jsx (plain JavaScript grammar already
- # supports JSX node types natively).
- src = b"""
-export function StatRow({ value }) {
- return <span>{value}</span>;
-}
-
-export function Card() {
- return <StatRow value={1} />;
-}
-"""
- fi = _make_file_info("ui/src/card.jsx", "javascript")
- result = parser.parse_file(fi, src)
- targets = {c.target_name for c in result.calls}
- assert "StatRow" in targets
-
- def test_class_methods_still_extracted(self, parser: ASTParser) -> None:
- # Negative for D5: methods inside class bodies must still be
- # extracted — only function/method *bodies* count as nesting.
- src = b"""
-export class Service {
- run() { return 1; }
- private helper() { return 2; }
-}
-"""
- fi = _make_file_info("ui/src/service.ts", "typescript")
- result = parser.parse_file(fi, src)
- method_names = {s.name for s in result.symbols if s.kind == "method"}
- assert {"run", "helper"} <= method_names
-
-
-# ---------------------------------------------------------------------------
-# Go
-# ---------------------------------------------------------------------------
-
-GO_SOURCE = b"""// Package calculator provides arithmetic with history.
-package calculator
-
-import (
- "errors"
- "fmt"
-
- "github.com/repowise-ai/sample/types"
-)
-
-// ErrDivisionByZero is returned on division by zero.
-var ErrDivisionByZero = errors.New("division by zero")
-
-// Calculator maintains a calculation history.
-type Calculator struct {
- history []types.CalculationRecord
-}
-
-// New returns a new Calculator.
-func New() *Calculator {
- return &Calculator{}
-}
-
-// Add returns the sum of the operands.
-func (c *Calculator) Add(ops types.Operands) (float64, error) {
- result := ops.X + ops.Y
- return result, nil
-}
-
-// Divide returns ops.X / ops.Y.
-func (c *Calculator) Divide(ops types.Operands) (float64, error) {
- if ops.Y == 0 {
- return 0, ErrDivisionByZero
- }
- return ops.X / ops.Y, nil
-}
-"""
-
-
-class TestGoParser:
- def test_finds_struct(self, parser: ASTParser) -> None:
- fi = _make_file_info("go_pkg/calculator/calculator.go", "go")
- result = parser.parse_file(fi, GO_SOURCE)
- structs = [s for s in result.symbols if s.kind == "struct"]
- assert any(s.name == "Calculator" for s in structs)
-
- def test_finds_functions(self, parser: ASTParser) -> None:
- fi = _make_file_info("go_pkg/calculator/calculator.go", "go")
- result = parser.parse_file(fi, GO_SOURCE)
- fns = [s for s in result.symbols if s.kind == "function"]
- assert any(s.name == "New" for s in fns)
-
- def test_finds_methods_with_receiver(self, parser: ASTParser) -> None:
- fi = _make_file_info("go_pkg/calculator/calculator.go", "go")
- result = parser.parse_file(fi, GO_SOURCE)
- methods = [s for s in result.symbols if s.kind == "method"]
- method_names = [m.name for m in methods]
- assert "Add" in method_names
- assert "Divide" in method_names
-
- def test_method_has_parent_from_receiver(self, parser: ASTParser) -> None:
- fi = _make_file_info("go_pkg/calculator/calculator.go", "go")
- result = parser.parse_file(fi, GO_SOURCE)
- add_method = next(s for s in result.symbols if s.name == "Add" and s.kind == "method")
- assert add_method.parent_name == "Calculator"
-
- def test_go_visibility_by_capitalisation(self, parser: ASTParser) -> None:
- fi = _make_file_info("go_pkg/calculator/calculator.go", "go")
- result = parser.parse_file(fi, GO_SOURCE)
- new_fn = next(s for s in result.symbols if s.name == "New")
- assert new_fn.visibility == "public"
-
- def test_parses_imports(self, parser: ASTParser) -> None:
- fi = _make_file_info("go_pkg/calculator/calculator.go", "go")
- result = parser.parse_file(fi, GO_SOURCE)
- module_paths = [i.module_path for i in result.imports]
- assert any("errors" in p for p in module_paths)
- assert any("sample/types" in p for p in module_paths)
-
- def test_no_parse_errors(self, parser: ASTParser) -> None:
- fi = _make_file_info("go_pkg/calculator/calculator.go", "go")
- result = parser.parse_file(fi, GO_SOURCE)
- assert result.parse_errors == []
-
-
-# ---------------------------------------------------------------------------
-# Rust
-# ---------------------------------------------------------------------------
-
-RUST_SOURCE = b"""//! Sample Rust calculator.
-
-use std::fmt;
-
-/// Supported operations.
-#[derive(Debug, Clone, Copy)]
-pub enum Operation {
- Add,
- Subtract,
-}
-
-/// A single recorded calculation.
-#[derive(Debug, Clone)]
-pub struct CalculationRecord {
- pub result: f64,
-}
-
-impl CalculationRecord {
- /// Create a new record.
- pub fn new(result: f64) -> Self {
- Self { result }
- }
-
- /// Return a summary string.
- pub fn summary(&self) -> String {
- format!("{:.2}", self.result)
- }
-}
-
-/// Add two numbers.
-pub fn add(x: f64, y: f64) -> f64 {
- x + y
-}
-"""
-
-
-class TestRustParser:
- def test_finds_enum(self, parser: ASTParser) -> None:
- fi = _make_file_info("rust_pkg/src/models.rs", "rust")
- result = parser.parse_file(fi, RUST_SOURCE)
- enums = [s for s in result.symbols if s.kind == "enum"]
- assert any(s.name == "Operation" for s in enums)
-
- def test_finds_struct(self, parser: ASTParser) -> None:
- fi = _make_file_info("rust_pkg/src/models.rs", "rust")
- result = parser.parse_file(fi, RUST_SOURCE)
- structs = [s for s in result.symbols if s.kind == "struct"]
- assert any(s.name == "CalculationRecord" for s in structs)
-
- def test_finds_impl_block(self, parser: ASTParser) -> None:
- fi = _make_file_info("rust_pkg/src/models.rs", "rust")
- result = parser.parse_file(fi, RUST_SOURCE)
- impls = [s for s in result.symbols if s.kind == "impl"]
- assert any(s.name == "CalculationRecord" for s in impls)
-
- def test_finds_top_level_function(self, parser: ASTParser) -> None:
- fi = _make_file_info("rust_pkg/src/models.rs", "rust")
- result = parser.parse_file(fi, RUST_SOURCE)
- fns = [s for s in result.symbols if s.kind == "function"]
- assert any(s.name == "add" for s in fns)
-
- def test_pub_visibility(self, parser: ASTParser) -> None:
- fi = _make_file_info("rust_pkg/src/models.rs", "rust")
- result = parser.parse_file(fi, RUST_SOURCE)
- add_fn = next(s for s in result.symbols if s.name == "add" and s.kind == "function")
- assert add_fn.visibility == "public"
-
- def test_parses_use_declaration(self, parser: ASTParser) -> None:
- fi = _make_file_info("rust_pkg/src/models.rs", "rust")
- result = parser.parse_file(fi, RUST_SOURCE)
- assert len(result.imports) >= 1
-
- def test_path_attribute_preceding_sibling(self, parser: ASTParser) -> None:
- """#[path = "..."] is a preceding sibling, not a child of mod_item."""
- src = b'#[path = "csv.rs"]\nmod csv_;\n'
- fi = _make_file_info("rust_pkg/src/lib.rs", "rust")
- result = parser.parse_file(fi, src)
- mod_imports = [i for i in result.imports if i.raw_statement.startswith("mod")]
- assert len(mod_imports) == 1
- assert mod_imports[0].module_path == "csv.rs"
-
- def test_path_attribute_not_applied_to_wrong_mod(self, parser: ASTParser) -> None:
- """An attribute on one mod must not leak to an unrelated mod."""
- src = b'#[path = "csv.rs"]\nmod csv_;\nmod normal;\n'
- fi = _make_file_info("rust_pkg/src/lib.rs", "rust")
- result = parser.parse_file(fi, src)
- normal = [i for i in result.imports if "normal" in i.raw_statement]
- assert len(normal) == 1
- assert normal[0].module_path == "normal"
-
-
-# ---------------------------------------------------------------------------
-# Java
-# ---------------------------------------------------------------------------
-
-JAVA_SOURCE = b"""package com.repowise.sample;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Stateful calculator with history.
- */
-public class Calculator {
-
- private final List<Object> history = new ArrayList<>();
-
- /**
- * Adds x and y.
- */
- public double add(double x, double y) {
- return x + y;
- }
-
- /** Private helper. */
- private void record(Object entry) {
- history.add(entry);
- }
-}
-"""
-
-
-class TestJavaParser:
- def test_finds_class(self, parser: ASTParser) -> None:
- fi = _make_file_info("java_pkg/Calculator.java", "java")
- result = parser.parse_file(fi, JAVA_SOURCE)
- classes = [s for s in result.symbols if s.kind == "class"]
- assert any(s.name == "Calculator" for s in classes)
-
- def test_finds_methods(self, parser: ASTParser) -> None:
- fi = _make_file_info("java_pkg/Calculator.java", "java")
- result = parser.parse_file(fi, JAVA_SOURCE)
- methods = [s for s in result.symbols if s.kind == "method"]
- method_names = [m.name for m in methods]
- assert "add" in method_names
- assert "record" in method_names
-
- def test_parses_imports(self, parser: ASTParser) -> None:
- fi = _make_file_info("java_pkg/Calculator.java", "java")
- result = parser.parse_file(fi, JAVA_SOURCE)
- assert len(result.imports) >= 2
- module_paths = [i.module_path for i in result.imports]
- assert any("ArrayList" in p for p in module_paths)
-
-
-# ---------------------------------------------------------------------------
-# C++
-# ---------------------------------------------------------------------------
-
-CPP_SOURCE = b"""#include "calculator.hpp"
-#include <stdexcept>
-#include <string>
-
-namespace sample {
-
-double Calculator::add(double x, double y) {
- return x + y;
-}
-
-double Calculator::divide(double x, double y) {
- if (y == 0.0) {
- throw std::invalid_argument("Division by zero");
- }
- return x / y;
-}
-
-} // namespace sample
-"""
-
-CPP_HEADER_SOURCE = b"""#pragma once
-
-#include <vector>
-#include "models.hpp"
-
-namespace sample {
-
-class Calculator {
-public:
- double add(double x, double y);
- double subtract(double x, double y);
- double divide(double x, double y);
-
-private:
- std::vector<int> history_;
-};
-
-} // namespace sample
-"""
-
-
-class TestCppParser:
- def test_finds_class_in_header(self, parser: ASTParser) -> None:
- fi = _make_file_info("cpp_pkg/calculator.hpp", "cpp")
- result = parser.parse_file(fi, CPP_HEADER_SOURCE)
- classes = [s for s in result.symbols if s.kind == "class"]
- assert any(s.name == "Calculator" for s in classes)
-
- def test_finds_functions_in_source(self, parser: ASTParser) -> None:
- fi = _make_file_info("cpp_pkg/calculator.cpp", "cpp")
- result = parser.parse_file(fi, CPP_SOURCE)
- # ``Calculator::add`` style qualified definitions now resolve to
- # ``kind=method`` with ``parent_name=Calculator``; free functions
- # stay ``kind=function``. Either way we expect symbols to land.
- callable_symbols = [s for s in result.symbols if s.kind in ("function", "method")]
- assert len(callable_symbols) >= 1
-
- def test_parses_includes(self, parser: ASTParser) -> None:
- fi = _make_file_info("cpp_pkg/calculator.cpp", "cpp")
- result = parser.parse_file(fi, CPP_SOURCE)
- assert len(result.imports) >= 2
- module_paths = [i.module_path for i in result.imports]
- assert any("calculator.hpp" in p or "stdexcept" in p for p in module_paths)
-
-
-# ---------------------------------------------------------------------------
-# Kotlin
-# ---------------------------------------------------------------------------
-
-KOTLIN_SOURCE = b"""\
-package sample
-
-import sample.models.Operation
-
-/** Calculator for basic arithmetic. */
-class Calculator {
- fun add(x: Double, y: Double): Double {
- val result = x + y
- return result
- }
-
- private fun helper() {}
-}
-
-enum class Operation {
- ADD, SUBTRACT
-}
-"""
-
-
-class TestKotlinParser:
- def test_finds_class(self, parser: ASTParser) -> None:
- fi = _make_file_info("kotlin_pkg/Calculator.kt", "kotlin")
- result = parser.parse_file(fi, KOTLIN_SOURCE)
- classes = [s for s in result.symbols if s.kind == "class"]
- assert any(s.name == "Calculator" for s in classes)
-
- def test_finds_functions(self, parser: ASTParser) -> None:
- fi = _make_file_info("kotlin_pkg/Calculator.kt", "kotlin")
- result = parser.parse_file(fi, KOTLIN_SOURCE)
- # add is inside Calculator so it becomes a method; check both kinds
- fns = [s for s in result.symbols if s.kind in ("function", "method")]
- assert any(s.name == "add" for s in fns)
-
- def test_parses_imports(self, parser: ASTParser) -> None:
- fi = _make_file_info("kotlin_pkg/Calculator.kt", "kotlin")
- result = parser.parse_file(fi, KOTLIN_SOURCE)
- assert len(result.imports) >= 1
- modules = {imp.module_path for imp in result.imports}
- assert any("Operation" in m for m in modules)
-
- def test_no_parse_errors(self, parser: ASTParser) -> None:
- fi = _make_file_info("kotlin_pkg/Calculator.kt", "kotlin")
- result = parser.parse_file(fi, KOTLIN_SOURCE)
- assert result.parse_errors == []
-
- def test_private_visibility(self, parser: ASTParser) -> None:
- fi = _make_file_info("kotlin_pkg/Calculator.kt", "kotlin")
- result = parser.parse_file(fi, KOTLIN_SOURCE)
- helper = next((s for s in result.symbols if s.name == "helper"), None)
- assert helper is not None
- assert helper.visibility == "private"
-
-
-# ---------------------------------------------------------------------------
-# Ruby
-# ---------------------------------------------------------------------------
-
-RUBY_SOURCE = b"""\
-# Calculator module
-require_relative './models'
-
-class Calculator < BaseCalculator
- def add(x, y)
- result = x + y
- record(x, y, result)
- result
- end
-
- def subtract(x, y)
- x - y
- end
-
- def self.create
- Calculator.new
- end
-end
-
-module Operations
- def multiply(x, y)
- x * y
- end
-end
-"""
-
-
-class TestRubyParser:
- def test_finds_class(self, parser: ASTParser) -> None:
- fi = _make_file_info("ruby_pkg/calculator.rb", "ruby")
- result = parser.parse_file(fi, RUBY_SOURCE)
- classes = [s for s in result.symbols if s.kind == "class"]
- assert any(s.name == "Calculator" for s in classes)
-
- def test_finds_module(self, parser: ASTParser) -> None:
- fi = _make_file_info("ruby_pkg/calculator.rb", "ruby")
- result = parser.parse_file(fi, RUBY_SOURCE)
- modules = [s for s in result.symbols if s.kind == "module"]
- assert any(s.name == "Operations" for s in modules)
-
- def test_finds_methods(self, parser: ASTParser) -> None:
- fi = _make_file_info("ruby_pkg/calculator.rb", "ruby")
- result = parser.parse_file(fi, RUBY_SOURCE)
- # add/subtract are inside Calculator so they become methods
- fns = [s for s in result.symbols if s.kind in ("function", "method")]
- names = {s.name for s in fns}
- assert "add" in names
- assert "subtract" in names
-
- def test_parses_imports(self, parser: ASTParser) -> None:
- fi = _make_file_info("ruby_pkg/calculator.rb", "ruby")
- result = parser.parse_file(fi, RUBY_SOURCE)
- assert len(result.imports) >= 1
-
- def test_no_parse_errors(self, parser: ASTParser) -> None:
- fi = _make_file_info("ruby_pkg/calculator.rb", "ruby")
- result = parser.parse_file(fi, RUBY_SOURCE)
- assert result.parse_errors == []
-
-
-# ---------------------------------------------------------------------------
-# Unsupported language (graceful fallback)
-# ---------------------------------------------------------------------------
-
-
-class TestUnsupportedLanguage:
- def test_returns_empty_parsed_file(self, parser: ASTParser) -> None:
- """Unsupported languages return an empty ParsedFile with no errors
- (silent passthrough by design — see parser.py line 354)."""
- fi = _make_file_info("file.xyz", "unknown")
- fi.language = "unknown"
- result = parser.parse_file(fi, b"some content here")
- assert result.symbols == []
- assert result.imports == []
- assert result.parse_errors == []
-
-
-# ---------------------------------------------------------------------------
-# LANGUAGE_CONFIGS completeness
-# ---------------------------------------------------------------------------
-
-
-# ---------------------------------------------------------------------------
-# C#
-# ---------------------------------------------------------------------------
-
-CSHARP_SOURCE = b"""\
-using System;
-using Sample.Models;
-
-namespace Sample
-{
- /// <summary>Calculator for basic arithmetic.</summary>
- public class Calculator
- {
- public double Add(double x, double y)
- {
- return x + y;
- }
-
- private void Helper() { }
- }
-
- public interface IComputable
- {
- double Compute();
- }
-
- public enum Operation { Add, Subtract }
-
- public struct Point
- {
- public double X;
- public double Y;
- }
-}
-"""
-
-
-class TestCSharpParser:
- def test_finds_class(self, parser: ASTParser) -> None:
- fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")
- result = parser.parse_file(fi, CSHARP_SOURCE)
- classes = [s for s in result.symbols if s.kind == "class"]
- assert any(s.name == "Calculator" for s in classes)
-
- def test_finds_interface(self, parser: ASTParser) -> None:
- fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")
- result = parser.parse_file(fi, CSHARP_SOURCE)
- interfaces = [s for s in result.symbols if s.kind == "interface"]
- assert any(s.name == "IComputable" for s in interfaces)
-
- def test_finds_enum(self, parser: ASTParser) -> None:
- fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")
- result = parser.parse_file(fi, CSHARP_SOURCE)
- enums = [s for s in result.symbols if s.kind == "enum"]
- assert any(s.name == "Operation" for s in enums)
-
- def test_finds_struct(self, parser: ASTParser) -> None:
- fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")
- result = parser.parse_file(fi, CSHARP_SOURCE)
- structs = [s for s in result.symbols if s.kind == "struct"]
- assert any(s.name == "Point" for s in structs)
-
- def test_finds_methods(self, parser: ASTParser) -> None:
- fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")
- result = parser.parse_file(fi, CSHARP_SOURCE)
- methods = [s for s in result.symbols if s.kind == "method"]
- assert any(s.name == "Add" for s in methods)
-
- def test_parses_imports(self, parser: ASTParser) -> None:
- fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")
- result = parser.parse_file(fi, CSHARP_SOURCE)
- assert len(result.imports) >= 2
- modules = {imp.module_path for imp in result.imports}
- assert "System" in modules
-
- def test_private_visibility(self, parser: ASTParser) -> None:
- fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")
- result = parser.parse_file(fi, CSHARP_SOURCE)
- helper = next((s for s in result.symbols if s.name == "Helper"), None)
- assert helper is not None
- assert helper.visibility == "private"
-
- def test_no_parse_errors(self, parser: ASTParser) -> None:
- fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")
- result = parser.parse_file(fi, CSHARP_SOURCE)
- assert result.parse_errors == []
-
-
-# ---------------------------------------------------------------------------
-# C# — modern features (records, delegates, events, namespaces, global using)
-# ---------------------------------------------------------------------------
-
-CSHARP_MODERN_SOURCE = b"""\
-global using System;
-global using static System.Math;
-using Foo = Sample.Very.Long.Namespace.Type;
-using static System.Convert;
-
-namespace Sample.Modern;
-
-public delegate int BinaryOp(int x, int y);
-
-public record User(string Name, int Age);
-
-public record struct Coordinate(double X, double Y);
-
-public class EventBus
-{
- public event EventHandler<string>? MessageReceived;
- public string Topic = "default";
- private const int MaxListeners = 100;
-}
-
-public enum Status { Active, Inactive, Pending }
-"""
-
-
-class TestCSharpModernParser:
- def test_finds_record(self, parser: ASTParser) -> None:
- fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")
- result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)
- names = {s.name for s in result.symbols}
- assert "User" in names
-
- def test_finds_record_struct(self, parser: ASTParser) -> None:
- fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")
- result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)
- names = {s.name for s in result.symbols}
- assert "Coordinate" in names
-
- def test_finds_delegate(self, parser: ASTParser) -> None:
- fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")
- result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)
- names = {s.name for s in result.symbols}
- assert "BinaryOp" in names
-
- def test_finds_event(self, parser: ASTParser) -> None:
- fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")
- result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)
- names = {s.name for s in result.symbols}
- assert "MessageReceived" in names
-
- def test_finds_field(self, parser: ASTParser) -> None:
- fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")
- result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)
- names = {s.name for s in result.symbols}
- assert "Topic" in names
- assert "MaxListeners" in names
-
- def test_finds_enum_member(self, parser: ASTParser) -> None:
- fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")
- result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)
- names = {s.name for s in result.symbols}
- assert "Active" in names
- assert "Inactive" in names
-
- def test_finds_file_scoped_namespace(self, parser: ASTParser) -> None:
- fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")
- result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)
- modules = [s for s in result.symbols if s.kind == "module"]
- assert any("Sample.Modern" in s.name or s.name == "Sample.Modern" for s in modules)
-
- def test_imports_capture_global_and_static(self, parser: ASTParser) -> None:
- fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")
- result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)
- modules = {imp.module_path for imp in result.imports}
- # global using and using static still surface as imports — full flag
- # propagation (is_global / is_static) lives in the binding extractor.
- assert "System" in modules
- assert any("Math" in m for m in modules)
- assert any("Convert" in m for m in modules)
- # The alias form `using Foo = Long.Namespace.Type` is captured as the
- # right-hand qualified name; alias propagation is wired in Batch 3.
- assert len(result.imports) >= 3
-
- def test_no_parse_errors(self, parser: ASTParser) -> None:
- fi = _make_file_info("csharp_pkg/Modern.cs", "csharp")
- result = parser.parse_file(fi, CSHARP_MODERN_SOURCE)
- assert result.parse_errors == []
-
-
-class TestCSharpRegistryMetadata:
- def test_csharp_spec_has_manifest_files(self) -> None:
- from repowise.core.ingestion.languages.registry import REGISTRY
-
- spec = REGISTRY.get("csharp")
- assert spec is not None
- assert "global.json" in spec.manifest_files
- assert "Directory.Build.props" in spec.manifest_files
-
- def test_csharp_spec_has_blocked_dirs(self) -> None:
- from repowise.core.ingestion.languages.registry import REGISTRY
-
- spec = REGISTRY.get("csharp")
- assert spec is not None
- assert "bin" in spec.blocked_dirs
- assert "obj" in spec.blocked_dirs
-
- def test_csharp_spec_has_generated_suffixes(self) -> None:
- from repowise.core.ingestion.languages.registry import REGISTRY
-
- spec = REGISTRY.get("csharp")
- assert spec is not None
- assert ".g.cs" in spec.generated_suffixes
- assert ".Designer.cs" in spec.generated_suffixes
-
- def test_csharp_record_in_heritage_node_types(self) -> None:
- from repowise.core.ingestion.languages.registry import REGISTRY
-
- spec = REGISTRY.get("csharp")
- assert spec is not None
- assert "record_declaration" in spec.heritage_node_types
-
-
-# ---------------------------------------------------------------------------
-# Swift
-# ---------------------------------------------------------------------------
-
-SWIFT_SOURCE = b"""\
-import Foundation
-
-/// Calculator for basic arithmetic.
-class Calculator: Computable {
- func add(x: Double, y: Double) -> Double {
- return x + y
- }
-
- private func helper() {}
-}
-
-protocol Computable {
- func compute() -> Double
-}
-
-enum Operation {
- case add
- case subtract
-}
-
-struct Point {
- var x: Double
- var y: Double
-}
-"""
-
-
-class TestSwiftParser:
- def test_finds_class(self, parser: ASTParser) -> None:
- fi = _make_file_info("swift_pkg/Calculator.swift", "swift")
- result = parser.parse_file(fi, SWIFT_SOURCE)
- classes = [s for s in result.symbols if s.kind == "class"]
- assert any(s.name == "Calculator" for s in classes)
-
- def test_finds_protocol(self, parser: ASTParser) -> None:
- fi = _make_file_info("swift_pkg/Calculator.swift", "swift")
- result = parser.parse_file(fi, SWIFT_SOURCE)
- interfaces = [s for s in result.symbols if s.kind == "interface"]
- assert any(s.name == "Computable" for s in interfaces)
-
- def test_finds_functions(self, parser: ASTParser) -> None:
- fi = _make_file_info("swift_pkg/Calculator.swift", "swift")
- result = parser.parse_file(fi, SWIFT_SOURCE)
- # Functions inside a class are upgraded to "method"
- fns = [s for s in result.symbols if s.kind in ("function", "method")]
- assert any(s.name == "add" for s in fns)
-
- def test_parses_imports(self, parser: ASTParser) -> None:
- fi = _make_file_info("swift_pkg/Calculator.swift", "swift")
- result = parser.parse_file(fi, SWIFT_SOURCE)
- assert len(result.imports) >= 1
- modules = {imp.module_path for imp in result.imports}
- assert any("Foundation" in m for m in modules)
-
- def test_private_visibility(self, parser: ASTParser) -> None:
- fi = _make_file_info("swift_pkg/Calculator.swift", "swift")
- result = parser.parse_file(fi, SWIFT_SOURCE)
- helper = next((s for s in result.symbols if s.name == "helper"), None)
- assert helper is not None
- assert helper.visibility == "private"
-
- def test_no_parse_errors(self, parser: ASTParser) -> None:
- fi = _make_file_info("swift_pkg/Calculator.swift", "swift")
- result = parser.parse_file(fi, SWIFT_SOURCE)
- assert result.parse_errors == []
-
-
-# ---------------------------------------------------------------------------
-# Scala
-# ---------------------------------------------------------------------------
-
-SCALA_SOURCE = b"""\
-package sample
-
-import sample.models.{Operation, CalculationRecord}
-
-/** Calculator for basic arithmetic. */
-class Calculator extends BaseCalc with Computable {
- def add(x: Double, y: Double): Double = x + y
-
- private def helper(): Unit = {}
-}
-
-trait Computable {
- def compute(): Double
-}
-
-object Singleton {
- val name = "calc"
-}
-"""
-
-
-class TestScalaParser:
- def test_finds_class(self, parser: ASTParser) -> None:
- fi = _make_file_info("scala_pkg/Calculator.scala", "scala")
- result = parser.parse_file(fi, SCALA_SOURCE)
- classes = [s for s in result.symbols if s.kind == "class"]
- assert any(s.name == "Calculator" for s in classes)
-
- def test_finds_trait(self, parser: ASTParser) -> None:
- fi = _make_file_info("scala_pkg/Calculator.scala", "scala")
- result = parser.parse_file(fi, SCALA_SOURCE)
- traits = [s for s in result.symbols if s.kind == "trait"]
- assert any(s.name == "Computable" for s in traits)
-
- def test_finds_object(self, parser: ASTParser) -> None:
- fi = _make_file_info("scala_pkg/Calculator.scala", "scala")
- result = parser.parse_file(fi, SCALA_SOURCE)
- objs = [s for s in result.symbols if s.name == "Singleton"]
- assert len(objs) >= 1
-
- def test_finds_functions(self, parser: ASTParser) -> None:
- fi = _make_file_info("scala_pkg/Calculator.scala", "scala")
- result = parser.parse_file(fi, SCALA_SOURCE)
- # def inside a class is promoted to "method"; top-level def stays "function"
- fns = [s for s in result.symbols if s.kind in ("function", "method")]
- assert any(s.name == "add" for s in fns)
-
- def test_parses_imports(self, parser: ASTParser) -> None:
- fi = _make_file_info("scala_pkg/Calculator.scala", "scala")
- result = parser.parse_file(fi, SCALA_SOURCE)
- assert len(result.imports) >= 1
-
- def test_no_parse_errors(self, parser: ASTParser) -> None:
- fi = _make_file_info("scala_pkg/Calculator.scala", "scala")
- result = parser.parse_file(fi, SCALA_SOURCE)
- assert result.parse_errors == []
-
-
-# ---------------------------------------------------------------------------
-# PHP
-# ---------------------------------------------------------------------------
-
-PHP_SOURCE = b"""\
-<?php
-namespace Sample;
-
-use Sample\\Models\\Operation;
-use Sample\\Models\\CalculationRecord;
-
-/** Calculator for basic arithmetic. */
-class Calculator extends BaseCalc implements Computable
-{
- public function add(float $x, float $y): float
- {
- return $x + $y;
- }
-
- private function helper(): void {}
-}
-
-interface Computable
-{
- public function compute(): float;
-}
-
-enum Operation
-{
- case Add;
- case Subtract;
-}
-"""
-
-
-class TestPhpParser:
- def test_finds_class(self, parser: ASTParser) -> None:
- fi = _make_file_info("php_pkg/Calculator.php", "php")
- result = parser.parse_file(fi, PHP_SOURCE)
- classes = [s for s in result.symbols if s.kind == "class"]
- assert any(s.name == "Calculator" for s in classes)
-
- def test_finds_interface(self, parser: ASTParser) -> None:
- fi = _make_file_info("php_pkg/Calculator.php", "php")
- result = parser.parse_file(fi, PHP_SOURCE)
- interfaces = [s for s in result.symbols if s.kind == "interface"]
- assert any(s.name == "Computable" for s in interfaces)
-
- def test_finds_enum(self, parser: ASTParser) -> None:
- fi = _make_file_info("php_pkg/Calculator.php", "php")
- result = parser.parse_file(fi, PHP_SOURCE)
- enums = [s for s in result.symbols if s.kind == "enum"]
- assert any(s.name == "Operation" for s in enums)
-
- def test_finds_methods(self, parser: ASTParser) -> None:
- fi = _make_file_info("php_pkg/Calculator.php", "php")
- result = parser.parse_file(fi, PHP_SOURCE)
- methods = [s for s in result.symbols if s.kind == "method"]
- assert any(s.name == "add" for s in methods)
-
- def test_parses_imports(self, parser: ASTParser) -> None:
- fi = _make_file_info("php_pkg/Calculator.php", "php")
- result = parser.parse_file(fi, PHP_SOURCE)
- assert len(result.imports) >= 1
-
- def test_private_visibility(self, parser: ASTParser) -> None:
- fi = _make_file_info("php_pkg/Calculator.php", "php")
- result = parser.parse_file(fi, PHP_SOURCE)
- helper = next((s for s in result.symbols if s.name == "helper"), None)
- assert helper is not None
- assert helper.visibility == "private"
-
- def test_no_parse_errors(self, parser: ASTParser) -> None:
- fi = _make_file_info("php_pkg/Calculator.php", "php")
- result = parser.parse_file(fi, PHP_SOURCE)
- assert result.parse_errors == []
-
-
-# ---------------------------------------------------------------------------
-# Luau (issue #52 — Roblox/Rojo support)
-# ---------------------------------------------------------------------------
-
-LUAU_SOURCE = b"""-- Module docstring placeholder.
-
-local Signal = require(script.Parent.Signal)
-local Shared = require(game.ReplicatedStorage.Shared.Util)
-
-type Callback = (value: number) -> ()
-
-function greet(name: string): string
- return "hello " .. name
-end
-
-function Calculator:add(x: number, y: number): number
- return x + y
-end
-"""
-
-
-# tree-sitter-luau is a real dep in pyproject.toml, but it is sometimes
-# absent from a partially-synced developer venv (e.g. when an old `uv pip
-# install -e .` ran before the dep was added). Skip explicitly so the
-# failure mode is "go run uv sync" rather than two confusing AssertionErrors.
-pytest.importorskip("tree_sitter_luau", reason="run `uv sync --all-packages`")
-
-
-class TestLuauParser:
- def test_finds_top_level_function(self, parser: ASTParser) -> None:
- fi = _make_file_info("luau_pkg/init.luau", "luau")
- result = parser.parse_file(fi, LUAU_SOURCE)
- names = [s.name for s in result.symbols]
- assert "greet" in names
-
- def test_parses_require_imports(self, parser: ASTParser) -> None:
- fi = _make_file_info("luau_pkg/init.luau", "luau")
- result = parser.parse_file(fi, LUAU_SOURCE)
- raw = [i.module_path for i in result.imports]
- # The .scm emits the raw argument text; the resolver interprets it.
- assert any("Signal" in m for m in raw)
- assert any("ReplicatedStorage" in m for m in raw)
-
-
-class TestLanguageConfigs:
- def test_all_supported_languages_have_config(self) -> None:
- expected = {
- "python", "typescript", "javascript", "go", "rust",
- "java", "cpp", "c", "kotlin", "ruby", "csharp", "swift",
- "scala", "php", "luau",
- }
- for lang in expected:
- assert lang in LANGUAGE_CONFIGS, f"Missing config for {lang}"
-
- def test_each_config_has_symbol_node_types(self) -> None:
- for lang, config in LANGUAGE_CONFIGS.items():
- assert len(config.symbol_node_types) > 0, f"{lang} has no symbol_node_types"
-
- def test_each_config_has_visibility_fn(self) -> None:
- for lang, config in LANGUAGE_CONFIGS.items():
- # Must be callable
- result = config.visibility_fn("MyClass", [])
- assert result in ("public", "private", "protected", "internal"), (
- f"{lang} visibility_fn returned unexpected: {result}"
- )
diff --git a/tests/unit/server/mcp/__init__.py b/tests/unit/server/mcp/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/unit/server/mcp/conftest.py b/tests/unit/server/mcp/conftest.py
new file mode 100644
index 000000000..825a9409c
--- /dev/null
+++ b/tests/unit/server/mcp/conftest.py
@@ -0,0 +1,629 @@
+"""Unit tests for repowise MCP server tools.
+
+Tests all 9 MCP tools using an in-memory SQLite database with pre-populated
+test data, mirroring the conftest pattern from the REST API tests.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
+from sqlalchemy.pool import StaticPool
+
+from repowise.core.persistence.database import init_db
+from repowise.core.persistence.models import (
+ DeadCodeFinding,
+ DecisionRecord,
+ GitMetadata,
+ GraphEdge,
+ GraphNode,
+ Page,
+ Repository,
+ WikiSymbol,
+)
+from repowise.core.persistence.search import FullTextSearch
+from repowise.core.persistence.vector_store import InMemoryVectorStore
+from repowise.core.providers.embedding.base import MockEmbedder
+
+_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=UTC)
+
+
+async def engine():
+ eng = create_async_engine(
+ "sqlite+aiosqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ poolclass=StaticPool,
+ )
+ await init_db(eng)
+ yield eng
+ await eng.dispose()
+
+
+async def factory(engine):
+ return async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
+
+
+async def session(factory):
+ async with factory() as s:
+ yield s
+ await s.commit()
+
+
+async def fts(engine):
+ f = FullTextSearch(engine)
+ await f.ensure_index()
+ return f
+
+
+async def vector_store():
+ embedder = MockEmbedder()
+ vs = InMemoryVectorStore(embedder=embedder)
+ yield vs
+ await vs.close()
+
+
+async def repo_id(session: AsyncSession) -> str:
+ """Create a test repository and return its ID."""
+ repo = Repository(
+ id="repo1",
+ name="test-repo",
+ url="https://github.com/example/test-repo",
+ local_path="/tmp/test-repo",
+ default_branch="main",
+ settings_json="{}",
+ created_at=_NOW,
+ updated_at=_NOW,
+ )
+ session.add(repo)
+ await session.flush()
+ return repo.id
+
+
+async def populated_db(session: AsyncSession, repo_id: str) -> str:
+ """Populate the database with test data for all MCP tools."""
+ rid = repo_id
+
+ # ---- Pages ----
+ pages = [
+ Page(
+ id="repo_overview:test-repo",
+ repository_id=rid,
+ page_type="repo_overview",
+ title="Test Repo Overview",
+ content="# Test Repo\n\nA comprehensive test repository.",
+ target_path="test-repo",
+ source_hash="abc123",
+ model_name="mock",
+ provider_name="mock",
+ generation_level=6,
+ confidence=1.0,
+ freshness_status="fresh",
+ metadata_json="{}",
+ created_at=_NOW,
+ updated_at=_NOW,
+ ),
+ Page(
+ id="architecture_diagram:test-repo",
+ repository_id=rid,
+ page_type="architecture_diagram",
+ title="Architecture Diagram",
+ content="graph TD\n A[Main] --> B[Auth]\n A --> C[DB]",
+ target_path="test-repo",
+ source_hash="abc124",
+ model_name="mock",
+ provider_name="mock",
+ generation_level=6,
+ confidence=1.0,
+ freshness_status="fresh",
+ metadata_json="{}",
+ created_at=_NOW,
+ updated_at=_NOW,
+ ),
+ Page(
+ id="module_page:src/auth",
+ repository_id=rid,
+ page_type="module_page",
+ title="Auth Module",
+ content="# Auth Module\n\nHandles authentication and authorization.",
+ target_path="src/auth",
+ source_hash="mod1",
+ model_name="mock",
+ provider_name="mock",
+ generation_level=4,
+ confidence=0.95,
+ freshness_status="fresh",
+ metadata_json="{}",
+ created_at=_NOW,
+ updated_at=_NOW,
+ ),
+ Page(
+ id="module_page:src/db",
+ repository_id=rid,
+ page_type="module_page",
+ title="Database Module",
+ content="# Database Module\n\nDatabase access and ORM layer.",
+ target_path="src/db",
+ source_hash="mod2",
+ model_name="mock",
+ provider_name="mock",
+ generation_level=4,
+ confidence=0.90,
+ freshness_status="fresh",
+ metadata_json="{}",
+ created_at=_NOW,
+ updated_at=_NOW,
+ ),
+ Page(
+ id="file_page:src/auth/service.py",
+ repository_id=rid,
+ page_type="file_page",
+ title="Auth Service",
+ content="# AuthService\n\nMain authentication service class.",
+ target_path="src/auth/service.py",
+ source_hash="file1",
+ model_name="mock",
+ provider_name="mock",
+ generation_level=2,
+ confidence=0.85,
+ freshness_status="fresh",
+ metadata_json="{}",
+ created_at=_NOW,
+ updated_at=_NOW,
+ ),
+ Page(
+ id="file_page:src/auth/middleware.py",
+ repository_id=rid,
+ page_type="file_page",
+ title="Auth Middleware",
+ content="# Auth Middleware\n\nRequest authentication middleware.",
+ target_path="src/auth/middleware.py",
+ source_hash="file2",
+ model_name="mock",
+ provider_name="mock",
+ generation_level=2,
+ confidence=0.50,
+ freshness_status="stale",
+ metadata_json="{}",
+ created_at=_NOW,
+ updated_at=_NOW,
+ ),
+ Page(
+ id="file_page:src/db/models.py",
+ repository_id=rid,
+ page_type="file_page",
+ title="DB Models",
+ content="# Database Models\n\nSQLAlchemy ORM models.",
+ target_path="src/db/models.py",
+ source_hash="file3",
+ model_name="mock",
+ provider_name="mock",
+ generation_level=2,
+ confidence=0.40,
+ freshness_status="stale",
+ metadata_json="{}",
+ created_at=_NOW,
+ updated_at=_NOW,
+ ),
+ ]
+ for p in pages:
+ session.add(p)
+
+ # ---- Symbols ----
+ symbols = [
+ WikiSymbol(
+ id="sym1",
+ repository_id=rid,
+ file_path="src/auth/service.py",
+ symbol_id="src/auth/service.py::AuthService",
+ name="AuthService",
+ qualified_name="auth.service.AuthService",
+ kind="class",
+ signature="class AuthService",
+ start_line=10,
+ end_line=100,
+ docstring="Main authentication service.",
+ visibility="public",
+ is_async=False,
+ complexity_estimate=15,
+ language="python",
+ parent_name=None,
+ created_at=_NOW,
+ updated_at=_NOW,
+ ),
+ WikiSymbol(
+ id="sym2",
+ repository_id=rid,
+ file_path="src/auth/service.py",
+ symbol_id="src/auth/service.py::login",
+ name="login",
+ qualified_name="auth.service.AuthService.login",
+ kind="method",
+ signature="async def login(self, username: str, password: str) -> Token",
+ start_line=20,
+ end_line=40,
+ docstring="Authenticate a user.",
+ visibility="public",
+ is_async=True,
+ complexity_estimate=5,
+ language="python",
+ parent_name="AuthService",
+ created_at=_NOW,
+ updated_at=_NOW,
+ ),
+ WikiSymbol(
+ id="sym3",
+ repository_id=rid,
+ file_path="src/db/models.py",
+ symbol_id="src/db/models.py::User",
+ name="User",
+ qualified_name="db.models.User",
+ kind="class",
+ signature="class User(Base)",
+ start_line=5,
+ end_line=30,
+ docstring="User ORM model.",
+ visibility="public",
+ is_async=False,
+ complexity_estimate=2,
+ language="python",
+ parent_name=None,
+ created_at=_NOW,
+ updated_at=_NOW,
+ ),
+ ]
+ for s in symbols:
+ session.add(s)
+
+ # ---- Graph Nodes ----
+ nodes = [
+ GraphNode(
+ id="gn1",
+ repository_id=rid,
+ node_id="src/auth/service.py",
+ node_type="file",
+ language="python",
+ symbol_count=2,
+ is_entry_point=True,
+ pagerank=0.85,
+ betweenness=0.5,
+ community_id=1,
+ created_at=_NOW,
+ ),
+ GraphNode(
+ id="gn2",
+ repository_id=rid,
+ node_id="src/auth/middleware.py",
+ node_type="file",
+ language="python",
+ symbol_count=1,
+ is_entry_point=False,
+ pagerank=0.4,
+ betweenness=0.2,
+ community_id=1,
+ created_at=_NOW,
+ ),
+ GraphNode(
+ id="gn3",
+ repository_id=rid,
+ node_id="src/db/models.py",
+ node_type="file",
+ language="python",
+ symbol_count=1,
+ is_entry_point=False,
+ pagerank=0.6,
+ betweenness=0.3,
+ community_id=2,
+ created_at=_NOW,
+ ),
+ ]
+ for n in nodes:
+ session.add(n)
+
+ # ---- Graph Edges ----
+ edges = [
+ GraphEdge(
+ id="ge1",
+ repository_id=rid,
+ source_node_id="src/auth/service.py",
+ target_node_id="src/db/models.py",
+ imported_names_json='["User"]',
+ created_at=_NOW,
+ ),
+ GraphEdge(
+ id="ge2",
+ repository_id=rid,
+ source_node_id="src/auth/middleware.py",
+ target_node_id="src/auth/service.py",
+ imported_names_json='["AuthService"]',
+ created_at=_NOW,
+ ),
+ ]
+ for e in edges:
+ session.add(e)
+
+ # ---- Git Metadata ----
+ git_metas = [
+ GitMetadata(
+ id="gm1",
+ repository_id=rid,
+ file_path="src/auth/service.py",
+ commit_count_total=42,
+ commit_count_90d=8,
+ commit_count_30d=3,
+ first_commit_at=datetime(2025, 1, 1, tzinfo=UTC),
+ last_commit_at=datetime(2026, 3, 15, tzinfo=UTC),
+ primary_owner_name="Alice",
+ primary_owner_email="[email protected]",
+ primary_owner_commit_pct=0.65,
+ top_authors_json=json.dumps(
+ [
+ {"name": "Alice", "count": 27},
+ {"name": "Bob", "count": 15},
+ ]
+ ),
+ significant_commits_json=json.dumps(
+ [
+ {
+ "sha": "abc1234",
+ "date": "2026-03-15",
+ "message": "Refactor auth flow",
+ "author": "Alice",
+ },
+ {
+ "sha": "def5678",
+ "date": "2026-02-10",
+ "message": "Add JWT support",
+ "author": "Bob",
+ },
+ ]
+ ),
+ co_change_partners_json=json.dumps(
+ [
+ {"file_path": "src/auth/middleware.py", "count": 5},
+ {"file_path": "src/db/models.py", "count": 3},
+ ]
+ ),
+ is_hotspot=True,
+ is_stable=False,
+ churn_percentile=0.92,
+ age_days=443,
+ created_at=_NOW,
+ updated_at=_NOW,
+ ),
+ GitMetadata(
+ id="gm2",
+ repository_id=rid,
+ file_path="src/db/models.py",
+ commit_count_total=15,
+ commit_count_90d=0,
+ commit_count_30d=0,
+ first_commit_at=datetime(2025, 1, 1, tzinfo=UTC),
+ last_commit_at=datetime(2025, 9, 1, tzinfo=UTC),
+ primary_owner_name="Bob",
+ primary_owner_email="[email protected]",
+ primary_owner_commit_pct=0.90,
+ top_authors_json=json.dumps([{"name": "Bob", "count": 13}]),
+ significant_commits_json=json.dumps(
+ [
+ {
+ "sha": "111aaa",
+ "date": "2025-09-01",
+ "message": "Add migration helper",
+ "author": "Bob",
+ },
+ ]
+ ),
+ co_change_partners_json=json.dumps(
+ [
+ {"file_path": "src/auth/service.py", "count": 3},
+ ]
+ ),
+ is_hotspot=False,
+ is_stable=True,
+ churn_percentile=0.15,
+ age_days=443,
+ created_at=_NOW,
+ updated_at=_NOW,
+ ),
+ ]
+ for g in git_metas:
+ session.add(g)
+
+ # ---- Dead Code Findings ----
+ findings = [
+ DeadCodeFinding(
+ id="dc1",
+ repository_id=rid,
+ kind="unreachable_file",
+ file_path="src/legacy/old_auth.py",
+ symbol_name=None,
+ symbol_kind=None,
+ confidence=0.9,
+ reason="No imports found; file not referenced by any other module",
+ lines=150,
+ safe_to_delete=True,
+ primary_owner="Alice",
+ age_days=365,
+ status="open",
+ analyzed_at=_NOW,
+ ),
+ DeadCodeFinding(
+ id="dc2",
+ repository_id=rid,
+ kind="unused_export",
+ file_path="src/auth/service.py",
+ symbol_name="deprecated_login",
+ symbol_kind="function",
+ confidence=0.7,
+ reason="Exported but no external callers found",
+ lines=20,
+ safe_to_delete=True,
+ primary_owner="Bob",
+ age_days=120,
+ status="open",
+ analyzed_at=_NOW,
+ ),
+ DeadCodeFinding(
+ id="dc3",
+ repository_id=rid,
+ kind="unused_export",
+ file_path="src/db/models.py",
+ symbol_name="OldModel",
+ symbol_kind="class",
+ confidence=0.5,
+ reason="Exported but no external callers found",
+ lines=40,
+ safe_to_delete=False,
+ primary_owner="Bob",
+ age_days=200,
+ status="open",
+ analyzed_at=_NOW,
+ ),
+ ]
+ for f in findings:
+ session.add(f)
+
+ # ---- Decision Records ----
+ decisions = [
+ DecisionRecord(
+ id="dec1",
+ repository_id=rid,
+ title="Use JWT for authentication",
+ status="proposed",
+ context="Need stateless auth for microservices",
+ decision="Use JWT tokens for all API authentication",
+ rationale="Stateless, scalable, works across services",
+ alternatives_json=json.dumps(["Session-based auth", "OAuth2 only"]),
+ consequences_json=json.dumps(["Must handle token refresh", "Token size overhead"]),
+ affected_files_json=json.dumps(["src/auth/service.py", "src/auth/middleware.py"]),
+ affected_modules_json=json.dumps(["src/auth"]),
+ tags_json=json.dumps(["auth", "security"]),
+ source="readme_mining",
+ confidence=0.6,
+ staleness_score=0.1,
+ created_at=_NOW,
+ updated_at=_NOW,
+ ),
+ DecisionRecord(
+ id="dec2",
+ repository_id=rid,
+ title="SQLAlchemy as ORM",
+ status="proposed",
+ context="Need an async-compatible ORM for Python",
+ decision="Use SQLAlchemy 2.0 with async support",
+ rationale="Mature, well-documented, async support in 2.0",
+ alternatives_json=json.dumps(["Tortoise ORM", "Django ORM"]),
+ consequences_json=json.dumps(["Learning curve for async patterns"]),
+ affected_files_json=json.dumps(["src/db/models.py"]),
+ affected_modules_json=json.dumps(["src/db"]),
+ tags_json=json.dumps(["database"]),
+ source="git_archaeology",
+ confidence=0.7,
+ staleness_score=0.0,
+ created_at=_NOW,
+ updated_at=_NOW,
+ ),
+ ]
+ for d in decisions:
+ session.add(d)
+
+ await session.flush()
+ return rid
+
+
+async def setup_mcp(factory, fts, vector_store, populated_db):
+ """Configure the MCP module's global state for testing."""
+ import repowise.server.mcp_server as mcp_mod
+
+ mcp_mod._session_factory = factory
+ mcp_mod._fts = fts
+ mcp_mod._vector_store = vector_store
+ mcp_mod._decision_store = InMemoryVectorStore(embedder=MockEmbedder())
+ mcp_mod._repo_path = "/tmp/test-repo"
+
+ yield populated_db
+
+ # Reset globals (including workspace state)
+ mcp_mod._session_factory = None
+ mcp_mod._fts = None
+ mcp_mod._vector_store = None
+ mcp_mod._decision_store = None
+ mcp_mod._repo_path = None
+ mcp_mod._registry = None
+ mcp_mod._workspace_root = None
+
+
+async def health_data(session: AsyncSession, populated_db: str) -> str:
+ """Seed health_findings + health_file_metrics for the existing repo."""
+ from repowise.core.persistence.crud import (
+ save_health_findings,
+ save_health_metrics,
+ )
+
+ rid = populated_db
+ await save_health_metrics(
+ session,
+ rid,
+ [
+ {
+ "file_path": "src/auth/service.py",
+ "score": 4.5,
+ "max_ccn": 15,
+ "max_nesting": 5,
+ "nloc": 200,
+ "has_test_file": False,
+ "module": "auth",
+ },
+ {
+ "file_path": "src/db/models.py",
+ "score": 8.5,
+ "max_ccn": 4,
+ "max_nesting": 2,
+ "nloc": 50,
+ "has_test_file": True,
+ "module": "db",
+ },
+ ],
+ )
+ await save_health_findings(
+ session,
+ rid,
+ [
+ {
+ "file_path": "src/auth/service.py",
+ "biomarker_type": "complex_method",
+ "severity": "high",
+ "function_name": "authenticate",
+ "line_start": 10,
+ "line_end": 80,
+ "details": {"ccn": 15, "cognitive": 30, "nloc": 70},
+ "health_impact": 1.2,
+ "reason": "authenticate has cyclomatic complexity 15",
+ },
+ {
+ "file_path": "src/auth/service.py",
+ "biomarker_type": "nested_complexity",
+ "severity": "medium",
+ "function_name": "authenticate",
+ "line_start": 10,
+ "line_end": 80,
+ "details": {"max_nesting": 5, "ccn": 15, "cognitive": 30},
+ "health_impact": 0.7,
+ "reason": "authenticate nests 5 levels deep",
+ },
+ ],
+ )
+ await session.commit()
+ return rid
diff --git a/tests/unit/server/mcp/test_config.py b/tests/unit/server/mcp/test_config.py
new file mode 100644
index 000000000..52a57b8fc
--- /dev/null
+++ b/tests/unit/server/mcp/test_config.py
@@ -0,0 +1,108 @@
+"""Unit tests for repowise MCP server tools.
+
+Tests all 9 MCP tools using an in-memory SQLite database with pre-populated
+test data, mirroring the conftest pattern from the REST API tests.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+
+def test_generate_mcp_config():
+ from pathlib import Path
+
+ from repowise.cli.mcp_config import generate_mcp_config
+
+ config = generate_mcp_config(Path("/tmp/test-repo"))
+ assert "mcpServers" in config
+ assert "repowise" in config["mcpServers"]
+ server = config["mcpServers"]["repowise"]
+ assert server["command"] == "repowise"
+ assert "mcp" in server["args"]
+ assert "stdio" in server["args"]
+
+
+def test_format_setup_instructions():
+ from pathlib import Path
+
+ from repowise.cli.mcp_config import format_setup_instructions
+
+ instructions = format_setup_instructions(Path("/tmp/test-repo"))
+ assert "Project .mcp.json" in instructions
+ assert "Claude Code" not in instructions
+ assert "Cursor" in instructions
+ assert "Cline" in instructions
+ assert "repowise" in instructions
+
+
+async def test_mcp_lifespan_uses_cli_database_env_var(monkeypatch):
+ """REPOWISE_DB_URL should be respected by MCP lifespan via resolve_db_url."""
+ import repowise.server.mcp_server._server as mcp_server
+ from repowise.server.mcp_server import _state
+
+ captured: dict[str, str] = {}
+
+ class DummyEngine:
+ @property
+ def dialect(self):
+ class _D:
+ name = "sqlite"
+
+ return _D()
+
+ async def dispose(self) -> None:
+ return None
+
+ class DummyFts:
+ def __init__(self, engine) -> None:
+ self.engine = engine
+
+ async def ensure_index(self) -> None:
+ return None
+
+ class DummyVectorStore:
+ def __init__(self, *, embedder) -> None:
+ self.embedder = embedder
+
+ async def close(self) -> None:
+ return None
+
+ async def fake_init_db(engine) -> None:
+ return None
+
+ async def fake_load_vector_stores(repo_path: str | None) -> None:
+ return None
+
+ def fake_create_async_engine(url: str, connect_args: dict | None = None) -> DummyEngine:
+ captured["url"] = url
+ return DummyEngine()
+
+ monkeypatch.setenv("REPOWISE_DB_URL", "sqlite+aiosqlite:///tmp/from-cli.db")
+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)
+ monkeypatch.setattr(mcp_server, "create_async_engine", fake_create_async_engine)
+ monkeypatch.setattr(mcp_server, "init_db", fake_init_db)
+ monkeypatch.setattr(mcp_server, "FullTextSearch", DummyFts)
+ monkeypatch.setattr(mcp_server, "InMemoryVectorStore", DummyVectorStore)
+ monkeypatch.setattr(mcp_server, "async_sessionmaker", lambda *args, **kwargs: object())
+ monkeypatch.setattr(mcp_server, "_load_vector_stores", fake_load_vector_stores)
+
+ original_repo_path = _state._repo_path
+ original_vector_store = _state._vector_store
+ original_decision_store = _state._decision_store
+ original_ready = _state._vector_store_ready
+
+ _state._repo_path = None
+ _state._vector_store = None
+ _state._decision_store = None
+ _state._vector_store_ready = None
+
+ try:
+ async with mcp_server._lifespan(mcp_server.mcp):
+ assert captured["url"] == "sqlite+aiosqlite:///tmp/from-cli.db"
+ finally:
+ _state._repo_path = original_repo_path
+ _state._vector_store = original_vector_store
+ _state._decision_store = original_decision_store
+ _state._vector_store_ready = original_ready
diff --git a/tests/unit/server/mcp/test_context.py b/tests/unit/server/mcp/test_context.py
new file mode 100644
index 000000000..04115bab4
--- /dev/null
+++ b/tests/unit/server/mcp/test_context.py
@@ -0,0 +1,206 @@
+"""Unit tests for repowise MCP server tools.
+
+Tests all 9 MCP tools using an in-memory SQLite database with pre-populated
+test data, mirroring the conftest pattern from the REST API tests.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+
+async def test_get_context_single_file(setup_mcp):
+ from repowise.server.mcp_server import get_context
+
+ result = await get_context(
+ ["src/auth/service.py"],
+ include=["docs", "full_doc", "ownership", "last_change", "decisions", "freshness"],
+ compact=False,
+ )
+ targets = result["targets"]
+ assert "src/auth/service.py" in targets
+ t = targets["src/auth/service.py"]
+ assert t["type"] == "file"
+ # Docs
+ assert t["docs"]["title"] == "Auth Service"
+ assert "AuthService" in t["docs"]["content_md"]
+ assert len(t["docs"]["symbols"]) == 2
+ assert any(s["name"] == "AuthService" for s in t["docs"]["symbols"])
+ assert "src/auth/middleware.py" in t["docs"]["imported_by"]
+ # Ownership
+ assert t["ownership"]["primary_owner"] == "Alice"
+ assert t["ownership"]["owner_pct"] == 0.65
+ assert t["ownership"]["contributor_count"] == 2
+ # Last change
+ assert t["last_change"]["author"] == "Alice"
+ assert t["last_change"]["days_ago"] == 443
+ # Decisions
+ assert len(t["decisions"]) >= 1
+ assert any(d["title"] == "Use JWT for authentication" for d in t["decisions"])
+ # Freshness
+ assert t["freshness"]["confidence_score"] == 0.85
+ assert t["freshness"]["freshness_status"] == "fresh"
+ assert t["freshness"]["is_stale"] is False
+
+
+async def test_get_context_single_module(setup_mcp):
+ from repowise.server.mcp_server import get_context
+
+ result = await get_context(
+ ["src/auth"],
+ include=["docs", "full_doc", "ownership", "last_change", "decisions", "freshness"],
+ compact=False,
+ )
+ targets = result["targets"]
+ assert "src/auth" in targets
+ t = targets["src/auth"]
+ assert t["type"] == "module"
+ assert t["docs"]["title"] == "Auth Module"
+ assert "authentication" in t["docs"]["content_md"].lower()
+ assert len(t["docs"]["files"]) == 2 # service.py and middleware.py
+ # Freshness from module page
+ assert t["freshness"]["confidence_score"] == 0.95
+
+
+async def test_get_context_single_symbol(setup_mcp):
+ from repowise.server.mcp_server import get_context
+
+ result = await get_context(
+ ["AuthService"],
+ include=["docs", "full_doc"],
+ compact=False,
+ )
+ targets = result["targets"]
+ assert "AuthService" in targets
+ t = targets["AuthService"]
+ assert t["type"] == "symbol"
+ assert t["docs"]["name"] == "AuthService"
+ assert t["docs"]["kind"] == "class"
+ assert t["docs"]["signature"] == "class AuthService"
+ assert t["docs"]["file_path"] == "src/auth/service.py"
+ assert t["docs"]["documentation"] # Has content from file page
+
+
+async def test_get_context_multiple_targets(setup_mcp):
+ from repowise.server.mcp_server import get_context
+
+ result = await get_context(["src/auth/service.py", "src/auth", "AuthService"])
+ targets = result["targets"]
+ assert len(targets) == 3
+ assert targets["src/auth/service.py"]["type"] == "file"
+ assert targets["src/auth"]["type"] == "module"
+ assert targets["AuthService"]["type"] == "symbol"
+
+
+async def test_get_context_include_filter(setup_mcp):
+ from repowise.server.mcp_server import get_context
+
+ result = await get_context(["src/auth/service.py"], include=["docs"])
+ t = result["targets"]["src/auth/service.py"]
+ assert "docs" in t
+ assert "ownership" not in t
+ assert "last_change" not in t
+ assert "decisions" not in t
+ assert "freshness" not in t
+
+
+async def test_get_context_not_found(setup_mcp):
+ from repowise.server.mcp_server import get_context
+
+ result = await get_context(["nonexistent_thing_xyz"])
+ t = result["targets"]["nonexistent_thing_xyz"]
+ assert "error" in t
+
+
+def _make_big_response(n_targets: int = 5, n_symbols: int = 80, body_chars: int = 4000) -> dict:
+ """Build a synthetic get_context response well over the 32 KB budget."""
+ targets = {}
+ for i in range(n_targets):
+ name = f"pkg/mod_{i}/file_{i}.ext"
+ targets[name] = {
+ "target": name,
+ "type": "file",
+ "docs": {
+ "title": f"File {i}",
+ "summary": "s" * 200,
+ "content_md": "x" * body_chars,
+ "symbols": [
+ {
+ "name": f"Sym{i}_{j}",
+ "kind": "class" if j % 5 == 0 else "function",
+ "signature": f"sig_{j}(...)",
+ "start_line": j * 10,
+ "end_line": j * 10 + 8,
+ "docstring": "d" * 300,
+ }
+ for j in range(n_symbols)
+ ],
+ },
+ }
+ return {"targets": targets, "_meta": {"timing_ms": 1.0}}
+
+
+def test_truncate_to_budget_enforces_cap():
+ from repowise.server.mcp_server.tool_context import (
+ _CHAR_BUDGET,
+ _truncate_to_budget,
+ )
+
+ big = _make_big_response()
+ raw_size = len(json.dumps(big, separators=(",", ":"), default=str))
+ assert raw_size > _CHAR_BUDGET, "fixture must exceed budget to be meaningful"
+
+ out = _truncate_to_budget(big)
+ final_size = len(json.dumps(out, separators=(",", ":"), default=str))
+ assert final_size <= _CHAR_BUDGET
+ assert out["truncated"] is True
+ # At least one target must survive.
+ assert len(out["targets"]) >= 1
+
+
+def test_truncate_flags_and_dropped_fields_populate():
+ from repowise.server.mcp_server.tool_context import _truncate_to_budget
+
+ big = _make_big_response(n_targets=6, n_symbols=60, body_chars=5000)
+ out = _truncate_to_budget(big)
+
+ assert out["truncated"] is True
+ # Either whole targets were dropped, or individual symbols were dropped —
+ # both are acceptable outcomes; at least one must be populated.
+ dropped_any = bool(out["dropped_targets"]) or bool(out["dropped_symbols"])
+ assert dropped_any
+ # Heavy optional fields should have been stripped from surviving targets.
+ for tgt in out["targets"].values():
+ assert "content_md" not in tgt.get("docs", {})
+ # Dropped symbol lists (if any) must reference actual symbol names.
+ for tgt_name, names in out["dropped_symbols"].items():
+ assert tgt_name in big["targets"] or tgt_name not in out["targets"]
+ assert all(isinstance(n, str) for n in names)
+
+
+def test_truncate_noop_when_under_budget():
+ from repowise.server.mcp_server.tool_context import _truncate_to_budget
+
+ small = {
+ "targets": {
+ "a.py": {
+ "target": "a.py",
+ "type": "file",
+ "docs": {"title": "A", "symbols": [{"name": "f", "kind": "function"}]},
+ }
+ },
+ "_meta": {},
+ }
+ out = _truncate_to_budget(small)
+ assert out["truncated"] is False
+ assert out["dropped_targets"] == []
+ assert out["dropped_symbols"] == {}
+ assert "content_md" not in out["targets"]["a.py"]["docs"] # wasn't there anyway
diff --git a/tests/unit/server/mcp/test_dead_code.py b/tests/unit/server/mcp/test_dead_code.py
new file mode 100644
index 000000000..bfe4411d9
--- /dev/null
+++ b/tests/unit/server/mcp/test_dead_code.py
@@ -0,0 +1,98 @@
+"""Unit tests for repowise MCP server tools.
+
+Tests all 9 MCP tools using an in-memory SQLite database with pre-populated
+test data, mirroring the conftest pattern from the REST API tests.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+
+async def test_get_dead_code(setup_mcp):
+ from repowise.server.mcp_server import get_dead_code
+
+ result = await get_dead_code()
+ assert result["summary"]["total_findings"] == 3
+ assert result["summary"]["safe_to_delete_count"] == 2
+
+ # Tiered structure: dc1 (0.9) in high, dc2 (0.7) + dc3 (0.5) in medium
+ tiers = result["tiers"]
+ assert tiers["high"]["count"] == 1
+ assert tiers["medium"]["count"] == 2
+ assert tiers["low"]["count"] == 0
+
+ # High tier findings sorted by confidence desc
+ high_findings = tiers["high"]["findings"]
+ assert high_findings[0]["confidence"] >= 0.8
+
+ # Impact estimate present
+ assert result["impact"]["total_lines_reclaimable"] > 0
+
+
+async def test_get_dead_code_safe_only(setup_mcp):
+ from repowise.server.mcp_server import get_dead_code
+
+ result = await get_dead_code(safe_only=True)
+ for tier_data in result["tiers"].values():
+ for f in tier_data["findings"]:
+ assert f["safe_to_delete"] is True
+
+
+async def test_get_dead_code_by_kind(setup_mcp):
+ from repowise.server.mcp_server import get_dead_code
+
+ result = await get_dead_code(kind="unreachable_file", min_confidence=0.0)
+ for tier_data in result["tiers"].values():
+ for f in tier_data["findings"]:
+ assert f["kind"] == "unreachable_file"
+
+
+async def test_get_dead_code_low_confidence(setup_mcp):
+ from repowise.server.mcp_server import get_dead_code
+
+ result = await get_dead_code(min_confidence=0.0)
+ total = sum(t["count"] for t in result["tiers"].values())
+ assert total == 3 # All 3 findings included
+
+
+async def test_get_dead_code_tier_filter(setup_mcp):
+ from repowise.server.mcp_server import get_dead_code
+
+ result = await get_dead_code(tier="high")
+ assert "high" in result["tiers"]
+ assert "medium" not in result["tiers"]
+ assert "low" not in result["tiers"]
+ assert result["tiers"]["high"]["count"] == 1
+
+
+async def test_get_dead_code_group_by_directory(setup_mcp):
+ from repowise.server.mcp_server import get_dead_code
+
+ result = await get_dead_code(group_by="directory", min_confidence=0.0)
+ assert "by_directory" in result
+ dirs = result["by_directory"]
+ assert len(dirs) >= 1
+ # Each dir entry has count, lines, safe_count
+ for d in dirs:
+ assert "directory" in d
+ assert "count" in d
+ assert "lines" in d
+
+
+async def test_get_dead_code_group_by_owner(setup_mcp):
+ from repowise.server.mcp_server import get_dead_code
+
+ result = await get_dead_code(group_by="owner", min_confidence=0.0)
+ assert "by_owner" in result
+ owners = result["by_owner"]
+ assert len(owners) >= 1
+ owner_names = [o["owner"] for o in owners]
+ assert "Bob" in owner_names # Bob owns dc2 + dc3
diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.py
new file mode 100644
index 000000000..5d66e47de
--- /dev/null
+++ b/tests/unit/server/mcp/test_health.py
@@ -0,0 +1,33 @@
+"""Unit tests for repowise MCP server tools.
+
+Tests all 9 MCP tools using an in-memory SQLite database with pre-populated
+test data, mirroring the conftest pattern from the REST API tests.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+
+async def test_get_health_dashboard(setup_mcp, health_data):
+ from repowise.server.mcp_server import get_health
+
+ result = await get_health()
+ assert result["mode"] == "dashboard"
+ assert result["kpis"]["file_count"] == 2
+ assert result["kpis"]["worst_performer_path"] == "src/auth/service.py"
+ assert len(result["worst_files"]) == 2
+ assert result["worst_files"][0]["file_path"] == "src/auth/service.py"
+ assert len(result["top_findings"]) == 2
+
+
+async def test_get_health_targeted(setup_mcp, health_data):
+ from repowise.server.mcp_server import get_health
+
+ result = await get_health(targets=["src/auth/service.py"])
+ assert result["mode"] == "targets"
+ assert len(result["metrics"]) == 1
+ assert result["metrics"][0]["max_ccn"] == 15
+ assert all(f["file_path"] == "src/auth/service.py" for f in result["findings"])
diff --git a/tests/unit/server/mcp/test_overview.py b/tests/unit/server/mcp/test_overview.py
new file mode 100644
index 000000000..c5a700844
--- /dev/null
+++ b/tests/unit/server/mcp/test_overview.py
@@ -0,0 +1,38 @@
+"""Unit tests for repowise MCP server tools.
+
+Tests all 9 MCP tools using an in-memory SQLite database with pre-populated
+test data, mirroring the conftest pattern from the REST API tests.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+
+async def test_get_overview(setup_mcp):
+ from repowise.server.mcp_server import get_overview
+
+ result = await get_overview()
+ assert result["title"] == "Test Repo Overview"
+ assert "comprehensive test" in result["content_md"]
+ assert "architecture_diagram_mermaid" not in result # removed: not useful for agents
+ assert len(result["key_modules"]) == 2
+ assert any(m["name"] == "Auth Module" for m in result["key_modules"])
+ assert "src/auth/service.py" in result["entry_points"]
+
+
+async def test_get_overview_with_repo_path(setup_mcp):
+ from repowise.server.mcp_server import get_overview
+
+ result = await get_overview(repo="/tmp/test-repo")
+ assert result["title"] == "Test Repo Overview"
+
+
+async def test_get_overview_repo_not_found(setup_mcp):
+ from repowise.server.mcp_server import get_overview
+
+ with pytest.raises(LookupError, match="not found"):
+ await get_overview(repo="/nonexistent")
diff --git a/tests/unit/server/mcp/test_risk.py b/tests/unit/server/mcp/test_risk.py
new file mode 100644
index 000000000..d4a935836
--- /dev/null
+++ b/tests/unit/server/mcp/test_risk.py
@@ -0,0 +1,91 @@
+"""Unit tests for repowise MCP server tools.
+
+Tests all 9 MCP tools using an in-memory SQLite database with pre-populated
+test data, mirroring the conftest pattern from the REST API tests.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+
+async def test_get_risk_single_target(setup_mcp):
+ from repowise.server.mcp_server import get_risk
+
+ result = await get_risk(["src/auth/service.py"])
+ targets = result["targets"]
+ assert "src/auth/service.py" in targets
+ t = targets["src/auth/service.py"]
+ assert t["hotspot_score"] == 0.92
+ assert t["dependents_count"] >= 1 # middleware imports it
+ assert len(t["co_change_partners"]) == 2
+ assert t["primary_owner"] == "Alice"
+ assert t["owner_pct"] == 0.65
+ assert "risk_summary" in t
+ assert "hotspot score" in t["risk_summary"]
+
+ # Trend: 30d=3, 90d=8 → baseline_rate=0.083, recent=0.1 → stable
+ assert t["trend"] in ("increasing", "stable", "decreasing")
+
+ # Risk type: churn_percentile=0.92, no fix keywords → churn-heavy
+ assert t["risk_type"] == "churn-heavy"
+
+ # Impact surface: middleware.py depends on service.py
+ assert len(t["impact_surface"]) >= 1
+ impact_files = [s["file_path"] for s in t["impact_surface"]]
+ assert "src/auth/middleware.py" in impact_files
+ # Each entry has pagerank and is_entry_point
+ for s in t["impact_surface"]:
+ assert "pagerank" in s
+ assert "is_entry_point" in s
+
+
+async def test_get_risk_multiple_targets(setup_mcp):
+ from repowise.server.mcp_server import get_risk
+
+ result = await get_risk(["src/auth/service.py", "src/db/models.py"])
+ targets = result["targets"]
+ assert len(targets) == 2
+ assert "global_hotspots" in result
+ # Both targets should have trend and risk_type
+ for t in targets.values():
+ assert "trend" in t
+ assert "risk_type" in t
+
+
+async def test_get_risk_global_hotspots_exclude_targets(setup_mcp):
+ from repowise.server.mcp_server import get_risk
+
+ result = await get_risk(["src/auth/service.py"])
+ # service.py is a hotspot but should NOT appear in global_hotspots
+ for h in result["global_hotspots"]:
+ assert h["file_path"] != "src/auth/service.py"
+
+
+async def test_get_risk_no_git_metadata(setup_mcp):
+ from repowise.server.mcp_server import get_risk
+
+ result = await get_risk(["src/auth/middleware.py"])
+ t = result["targets"]["src/auth/middleware.py"]
+ assert t["hotspot_score"] == 0.0 # No git metadata for this file
+ assert t["trend"] == "unknown"
+ assert "risk_summary" in t
+ # Impact surface and risk_type still computed from graph data
+ assert "risk_type" in t
+ assert "impact_surface" in t
+
+
+async def test_get_risk_stable_file(setup_mcp):
+ from repowise.server.mcp_server import get_risk
+
+ result = await get_risk(["src/db/models.py"])
+ t = result["targets"]["src/db/models.py"]
+ # 0 commits in 30d and 90d → stable
+ assert t["trend"] == "stable"
+ # churn_percentile=0.15, dep_count=1, no fix keywords → stable
+ assert t["risk_type"] == "stable"
diff --git a/tests/unit/server/mcp/test_search.py b/tests/unit/server/mcp/test_search.py
new file mode 100644
index 000000000..f1d9c69cd
--- /dev/null
+++ b/tests/unit/server/mcp/test_search.py
@@ -0,0 +1,31 @@
+"""Unit tests for repowise MCP server tools.
+
+Tests all 9 MCP tools using an in-memory SQLite database with pre-populated
+test data, mirroring the conftest pattern from the REST API tests.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+
+async def test_search_codebase(setup_mcp):
+ # Index pages in the MCP module's vector store (which is the InMemoryVectorStore)
+ import repowise.server.mcp_server as mcp_mod
+ from repowise.server.mcp_server import search_codebase
+
+ await mcp_mod._vector_store.embed_and_upsert(
+ "file_page:src/auth/service.py",
+ "Auth Service — Main authentication service class",
+ {"title": "Auth Service", "page_type": "file_page", "target_path": "src/auth/service.py"},
+ )
+ await mcp_mod._vector_store.embed_and_upsert(
+ "file_page:src/db/models.py",
+ "DB Models — SQLAlchemy ORM models",
+ {"title": "DB Models", "page_type": "file_page", "target_path": "src/db/models.py"},
+ )
+
+ result = await search_codebase("authentication service")
+ assert "results" in result
+ assert len(result["results"]) >= 1
diff --git a/tests/unit/server/mcp/test_why.py b/tests/unit/server/mcp/test_why.py
new file mode 100644
index 000000000..be6124917
--- /dev/null
+++ b/tests/unit/server/mcp/test_why.py
@@ -0,0 +1,243 @@
+"""Unit tests for repowise MCP server tools.
+
+Tests all 9 MCP tools using an in-memory SQLite database with pre-populated
+test data, mirroring the conftest pattern from the REST API tests.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+
+async def test_get_why_natural_language(setup_mcp):
+ from repowise.server.mcp_server import get_why
+
+ result = await get_why("why is JWT used for authentication")
+ assert result["mode"] == "search"
+ assert result["query"] == "why is JWT used for authentication"
+ assert len(result["decisions"]) >= 1
+ assert any("JWT" in d["title"] for d in result["decisions"])
+
+
+async def test_get_why_file_path(setup_mcp):
+ from repowise.server.mcp_server import get_why
+
+ result = await get_why("src/auth/service.py")
+ assert result["mode"] == "path"
+ assert result["path"] == "src/auth/service.py"
+ assert len(result["decisions"]) >= 1
+ assert any(d["title"] == "Use JWT for authentication" for d in result["decisions"])
+
+ # Origin story
+ origin = result["origin_story"]
+ assert origin["available"] is True
+ assert origin["primary_author"] == "Alice"
+ assert origin["total_commits"] == 42
+ assert len(origin["key_commits"]) >= 1
+ assert len(origin["contributors"]) >= 1
+ assert "Alice" in origin["summary"]
+
+ # Alignment — dec1 is "proposed", both service.py and middleware.py share it
+ alignment = result["alignment"]
+ assert alignment["score"] in ("high", "medium", "low", "none")
+ assert alignment["governing_count"] >= 1
+ assert "explanation" in alignment
+
+
+async def test_get_why_file_path_commit_decision_linkage(setup_mcp):
+ from repowise.server.mcp_server import get_why
+
+ result = await get_why("src/auth/service.py")
+ origin = result["origin_story"]
+
+ # "Add JWT support" commit should link to "Use JWT for authentication" decision
+ # because "JWT" appears in both the commit message and decision title
+ linked = origin["linked_decisions"]
+ assert len(linked) >= 1
+ jwt_decision = next((d for d in linked if d["title"] == "Use JWT for authentication"), None)
+ assert jwt_decision is not None
+ assert len(jwt_decision["evidence_commits"]) >= 1
+ ec = jwt_decision["evidence_commits"][0]
+ assert "JWT" in ec["message"] or "jwt" in ec["message"].lower()
+ assert "matching_keywords" in ec
+
+
+async def test_get_why_natural_language_with_targets(setup_mcp):
+ from repowise.server.mcp_server import get_why
+
+ # Search with targets — decisions governing service.py should be boosted
+ result = await get_why(
+ "authentication approach",
+ targets=["src/auth/service.py"],
+ )
+ assert result["mode"] == "search"
+ assert len(result["decisions"]) >= 1
+
+ # target_context should be present
+ assert "target_context" in result
+ ctx = result["target_context"]["src/auth/service.py"]
+ assert len(ctx["governing_decisions"]) >= 1
+ assert ctx["origin"]["available"] is True
+ assert ctx["origin"]["primary_author"] == "Alice"
+
+
+async def test_get_why_expanded_keyword_search(setup_mcp):
+ from repowise.server.mcp_server import get_why
+
+ # Search for "security" — should match via tags_json on dec1
+ result = await get_why("security")
+ assert result["mode"] == "search"
+ # dec1 has tags=["auth", "security"], should be found
+ assert len(result["decisions"]) >= 1
+ assert any(d.get("title") == "Use JWT for authentication" for d in result["decisions"])
+
+
+async def test_get_why_file_no_git_metadata(setup_mcp):
+ from repowise.server.mcp_server import get_why
+
+ # middleware.py has no GitMetadata in the fixture
+ result = await get_why("src/auth/middleware.py")
+ assert result["mode"] == "path"
+ origin = result["origin_story"]
+ assert origin["available"] is False
+ assert "No git history" in origin["summary"]
+
+ # But it still has decisions (dec1 affects middleware.py)
+ assert len(result["decisions"]) >= 1
+ alignment = result["alignment"]
+ assert alignment["governing_count"] >= 1
+
+
+async def test_get_why_file_ungoverned(setup_mcp):
+ from repowise.server.mcp_server import get_why
+
+ # Use a path that has no decisions — triggers git archaeology fallback
+ result = await get_why("src/other/utils.py")
+ assert result["mode"] == "path"
+ assert result["alignment"]["score"] == "none"
+ assert "ungoverned" in result["alignment"]["explanation"]
+
+ # Git archaeology fallback should be triggered
+ assert "git_archaeology" in result
+ arch = result["git_archaeology"]
+ assert arch["triggered"] is True
+ assert "summary" in arch
+ assert "file_commits" in arch
+ assert "cross_references" in arch
+ assert "git_log" in arch
+
+
+async def test_get_why_fallback_with_cross_references(setup_mcp):
+ from repowise.server.mcp_server import get_why
+
+ # src/auth/service.py has git metadata with commits mentioning "auth"
+ # Query a nonexistent auth file — cross-references should find commits
+ # from service.py that mention "auth" terms
+ result = await get_why("src/auth/new_handler.py")
+ assert result["mode"] == "path"
+ assert len(result["decisions"]) == 0 # No decisions for this file
+
+ arch = result["git_archaeology"]
+ assert arch["triggered"] is True
+ # Cross-references may find commits from service.py whose messages
+ # contain "auth" (matching the path stem "new_handler" won't match,
+ # but the file_commits will still be empty since no git metadata exists)
+ assert isinstance(arch["cross_references"], list)
+
+
+async def test_get_why_targets_fallback(setup_mcp):
+ from repowise.server.mcp_server import get_why
+
+ # Search with a target that has no governing decisions
+ result = await get_why(
+ "why does this exist",
+ targets=["src/other/unknown.py"],
+ )
+ assert result["mode"] == "search"
+ ctx = result["target_context"]["src/other/unknown.py"]
+ assert len(ctx["governing_decisions"]) == 0
+ # Fallback should trigger
+ assert "git_archaeology" in ctx
+ assert ctx["git_archaeology"]["triggered"] is True
+
+
+async def test_get_why_no_args(setup_mcp):
+ from repowise.server.mcp_server import get_why
+
+ result = await get_why()
+ assert result["mode"] == "health"
+ assert "summary" in result
+ assert "counts" in result
+ assert "proposed_awaiting_review" in result
+ assert "ungoverned_hotspots" in result
+
+
+async def test_get_why_module_path(setup_mcp):
+ from repowise.server.mcp_server import get_why
+
+ result = await get_why("src/db")
+ assert result["mode"] == "path"
+ assert len(result["decisions"]) >= 1
+ assert any(d["title"] == "SQLAlchemy as ORM" for d in result["decisions"])
+
+
+async def test_get_why_semantic_decision_namespace_filtering(setup_mcp):
+ """Mode 3 semantic path: over-fetch from page store, keep only decision: hits.
+
+ Upserts a decision vector under the 'decision:' prefix and a noise page
+ without the prefix into the shared vector store. Confirms that get_why
+ surfaces the decision hit with the prefix stripped, and excludes the noise
+ page from the decisions list.
+ """
+ import repowise.server.mcp_server as mcp_mod
+ from repowise.core.analysis.decision_semantic_match import DECISION_VECTOR_PREFIX
+ from repowise.server.mcp_server import get_why
+
+ vs = mcp_mod._vector_store
+
+ # Insert a decision under the decision: namespace
+ await vs.embed_and_upsert(
+ f"{DECISION_VECTOR_PREFIX}dec-vec-1",
+ "Use Redis for caching to reduce latency",
+ {
+ "title": "Use Redis for caching",
+ "page_type": "decision_record",
+ "target_path": "",
+ "content": "Use Redis for caching to reduce latency",
+ },
+ )
+
+ # Insert a noise page (no decision: prefix) with similar text
+ await vs.embed_and_upsert(
+ "file_page:src/cache/redis.py",
+ "Redis caching implementation module",
+ {
+ "title": "Redis Cache Module",
+ "page_type": "file_page",
+ "target_path": "src/cache/redis.py",
+ "content": "Redis caching implementation module",
+ },
+ )
+
+ result = await get_why("why use Redis for caching")
+ assert result["mode"] == "search"
+
+ decision_ids = [d["id"] for d in result["decisions"]]
+ # The semantic decision hit should appear with the prefix stripped
+ assert "dec-vec-1" in decision_ids, f"Expected 'dec-vec-1' in decisions; got {decision_ids}"
+ # The noise page must not appear in decisions
+ assert not any(d.get("id", "").startswith("file_page:") for d in result["decisions"]), (
+ "Noise page should not appear in decisions list"
+ )
diff --git a/tests/unit/server/test_mcp.py b/tests/unit/server/test_mcp.py
deleted file mode 100644
index 7a75dcb56..000000000
--- a/tests/unit/server/test_mcp.py
+++ /dev/null
@@ -1,1443 +0,0 @@
-"""Unit tests for repowise MCP server tools.
-
-Tests all 9 MCP tools using an in-memory SQLite database with pre-populated
-test data, mirroring the conftest pattern from the REST API tests.
-"""
-
-from __future__ import annotations
-
-import json
-from datetime import UTC, datetime
-
-import pytest
-from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
-from sqlalchemy.pool import StaticPool
-
-from repowise.core.persistence.database import init_db
-from repowise.core.persistence.models import (
- DeadCodeFinding,
- DecisionRecord,
- GitMetadata,
- GraphEdge,
- GraphNode,
- Page,
- Repository,
- WikiSymbol,
-)
-from repowise.core.persistence.search import FullTextSearch
-from repowise.core.persistence.vector_store import InMemoryVectorStore
-from repowise.core.providers.embedding.base import MockEmbedder
-
-# ---------------------------------------------------------------------------
-# Fixtures
-# ---------------------------------------------------------------------------
-
-_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=UTC)
-
-
-async def engine():
- eng = create_async_engine(
- "sqlite+aiosqlite:///:memory:",
- connect_args={"check_same_thread": False},
- poolclass=StaticPool,
- )
- await init_db(eng)
- yield eng
- await eng.dispose()
-
-
-async def factory(engine):
- return async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
-
-
-async def session(factory):
- async with factory() as s:
- yield s
- await s.commit()
-
-
-async def fts(engine):
- f = FullTextSearch(engine)
- await f.ensure_index()
- return f
-
-
-async def vector_store():
- embedder = MockEmbedder()
- vs = InMemoryVectorStore(embedder=embedder)
- yield vs
- await vs.close()
-
-
-async def repo_id(session: AsyncSession) -> str:
- """Create a test repository and return its ID."""
- repo = Repository(
- id="repo1",
- name="test-repo",
- url="https://github.com/example/test-repo",
- local_path="/tmp/test-repo",
- default_branch="main",
- settings_json="{}",
- created_at=_NOW,
- updated_at=_NOW,
- )
- session.add(repo)
- await session.flush()
- return repo.id
-
-
-async def populated_db(session: AsyncSession, repo_id: str) -> str:
- """Populate the database with test data for all MCP tools."""
- rid = repo_id
-
- # ---- Pages ----
- pages = [
- Page(
- id="repo_overview:test-repo",
- repository_id=rid,
- page_type="repo_overview",
- title="Test Repo Overview",
- content="# Test Repo\n\nA comprehensive test repository.",
- target_path="test-repo",
- source_hash="abc123",
- model_name="mock",
- provider_name="mock",
- generation_level=6,
- confidence=1.0,
- freshness_status="fresh",
- metadata_json="{}",
- created_at=_NOW,
- updated_at=_NOW,
- ),
- Page(
- id="architecture_diagram:test-repo",
- repository_id=rid,
- page_type="architecture_diagram",
- title="Architecture Diagram",
- content="graph TD\n A[Main] --> B[Auth]\n A --> C[DB]",
- target_path="test-repo",
- source_hash="abc124",
- model_name="mock",
- provider_name="mock",
- generation_level=6,
- confidence=1.0,
- freshness_status="fresh",
- metadata_json="{}",
- created_at=_NOW,
- updated_at=_NOW,
- ),
- Page(
- id="module_page:src/auth",
- repository_id=rid,
- page_type="module_page",
- title="Auth Module",
- content="# Auth Module\n\nHandles authentication and authorization.",
- target_path="src/auth",
- source_hash="mod1",
- model_name="mock",
- provider_name="mock",
- generation_level=4,
- confidence=0.95,
- freshness_status="fresh",
- metadata_json="{}",
- created_at=_NOW,
- updated_at=_NOW,
- ),
- Page(
- id="module_page:src/db",
- repository_id=rid,
- page_type="module_page",
- title="Database Module",
- content="# Database Module\n\nDatabase access and ORM layer.",
- target_path="src/db",
- source_hash="mod2",
- model_name="mock",
- provider_name="mock",
- generation_level=4,
- confidence=0.90,
- freshness_status="fresh",
- metadata_json="{}",
- created_at=_NOW,
- updated_at=_NOW,
- ),
- Page(
- id="file_page:src/auth/service.py",
- repository_id=rid,
- page_type="file_page",
- title="Auth Service",
- content="# AuthService\n\nMain authentication service class.",
- target_path="src/auth/service.py",
- source_hash="file1",
- model_name="mock",
- provider_name="mock",
- generation_level=2,
- confidence=0.85,
- freshness_status="fresh",
- metadata_json="{}",
- created_at=_NOW,
- updated_at=_NOW,
- ),
- Page(
- id="file_page:src/auth/middleware.py",
- repository_id=rid,
- page_type="file_page",
- title="Auth Middleware",
- content="# Auth Middleware\n\nRequest authentication middleware.",
- target_path="src/auth/middleware.py",
- source_hash="file2",
- model_name="mock",
- provider_name="mock",
- generation_level=2,
- confidence=0.50,
- freshness_status="stale",
- metadata_json="{}",
- created_at=_NOW,
- updated_at=_NOW,
- ),
- Page(
- id="file_page:src/db/models.py",
- repository_id=rid,
- page_type="file_page",
- title="DB Models",
- content="# Database Models\n\nSQLAlchemy ORM models.",
- target_path="src/db/models.py",
- source_hash="file3",
- model_name="mock",
- provider_name="mock",
- generation_level=2,
- confidence=0.40,
- freshness_status="stale",
- metadata_json="{}",
- created_at=_NOW,
- updated_at=_NOW,
- ),
- ]
- for p in pages:
- session.add(p)
-
- # ---- Symbols ----
- symbols = [
- WikiSymbol(
- id="sym1",
- repository_id=rid,
- file_path="src/auth/service.py",
- symbol_id="src/auth/service.py::AuthService",
- name="AuthService",
- qualified_name="auth.service.AuthService",
- kind="class",
- signature="class AuthService",
- start_line=10,
- end_line=100,
- docstring="Main authentication service.",
- visibility="public",
- is_async=False,
- complexity_estimate=15,
- language="python",
- parent_name=None,
- created_at=_NOW,
- updated_at=_NOW,
- ),
- WikiSymbol(
- id="sym2",
- repository_id=rid,
- file_path="src/auth/service.py",
- symbol_id="src/auth/service.py::login",
- name="login",
- qualified_name="auth.service.AuthService.login",
- kind="method",
- signature="async def login(self, username: str, password: str) -> Token",
- start_line=20,
- end_line=40,
- docstring="Authenticate a user.",
- visibility="public",
- is_async=True,
- complexity_estimate=5,
- language="python",
- parent_name="AuthService",
- created_at=_NOW,
- updated_at=_NOW,
- ),
- WikiSymbol(
- id="sym3",
- repository_id=rid,
- file_path="src/db/models.py",
- symbol_id="src/db/models.py::User",
- name="User",
- qualified_name="db.models.User",
- kind="class",
- signature="class User(Base)",
- start_line=5,
- end_line=30,
- docstring="User ORM model.",
- visibility="public",
- is_async=False,
- complexity_estimate=2,
- language="python",
- parent_name=None,
- created_at=_NOW,
- updated_at=_NOW,
- ),
- ]
- for s in symbols:
- session.add(s)
-
- # ---- Graph Nodes ----
- nodes = [
- GraphNode(
- id="gn1",
- repository_id=rid,
- node_id="src/auth/service.py",
- node_type="file",
- language="python",
- symbol_count=2,
- is_entry_point=True,
- pagerank=0.85,
- betweenness=0.5,
- community_id=1,
- created_at=_NOW,
- ),
- GraphNode(
- id="gn2",
- repository_id=rid,
- node_id="src/auth/middleware.py",
- node_type="file",
- language="python",
- symbol_count=1,
- is_entry_point=False,
- pagerank=0.4,
- betweenness=0.2,
- community_id=1,
- created_at=_NOW,
- ),
- GraphNode(
- id="gn3",
- repository_id=rid,
- node_id="src/db/models.py",
- node_type="file",
- language="python",
- symbol_count=1,
- is_entry_point=False,
- pagerank=0.6,
- betweenness=0.3,
- community_id=2,
- created_at=_NOW,
- ),
- ]
- for n in nodes:
- session.add(n)
-
- # ---- Graph Edges ----
- edges = [
- GraphEdge(
- id="ge1",
- repository_id=rid,
- source_node_id="src/auth/service.py",
- target_node_id="src/db/models.py",
- imported_names_json='["User"]',
- created_at=_NOW,
- ),
- GraphEdge(
- id="ge2",
- repository_id=rid,
- source_node_id="src/auth/middleware.py",
- target_node_id="src/auth/service.py",
- imported_names_json='["AuthService"]',
- created_at=_NOW,
- ),
- ]
- for e in edges:
- session.add(e)
-
- # ---- Git Metadata ----
- git_metas = [
- GitMetadata(
- id="gm1",
- repository_id=rid,
- file_path="src/auth/service.py",
- commit_count_total=42,
- commit_count_90d=8,
- commit_count_30d=3,
- first_commit_at=datetime(2025, 1, 1, tzinfo=UTC),
- last_commit_at=datetime(2026, 3, 15, tzinfo=UTC),
- primary_owner_name="Alice",
- primary_owner_email="[email protected]",
- primary_owner_commit_pct=0.65,
- top_authors_json=json.dumps(
- [
- {"name": "Alice", "count": 27},
- {"name": "Bob", "count": 15},
- ]
- ),
- significant_commits_json=json.dumps(
- [
- {
- "sha": "abc1234",
- "date": "2026-03-15",
- "message": "Refactor auth flow",
- "author": "Alice",
- },
- {
- "sha": "def5678",
- "date": "2026-02-10",
- "message": "Add JWT support",
- "author": "Bob",
- },
- ]
- ),
- co_change_partners_json=json.dumps(
- [
- {"file_path": "src/auth/middleware.py", "count": 5},
- {"file_path": "src/db/models.py", "count": 3},
- ]
- ),
- is_hotspot=True,
- is_stable=False,
- churn_percentile=0.92,
- age_days=443,
- created_at=_NOW,
- updated_at=_NOW,
- ),
- GitMetadata(
- id="gm2",
- repository_id=rid,
- file_path="src/db/models.py",
- commit_count_total=15,
- commit_count_90d=0,
- commit_count_30d=0,
- first_commit_at=datetime(2025, 1, 1, tzinfo=UTC),
- last_commit_at=datetime(2025, 9, 1, tzinfo=UTC),
- primary_owner_name="Bob",
- primary_owner_email="[email protected]",
- primary_owner_commit_pct=0.90,
- top_authors_json=json.dumps([{"name": "Bob", "count": 13}]),
- significant_commits_json=json.dumps(
- [
- {
- "sha": "111aaa",
- "date": "2025-09-01",
- "message": "Add migration helper",
- "author": "Bob",
- },
- ]
- ),
- co_change_partners_json=json.dumps(
- [
- {"file_path": "src/auth/service.py", "count": 3},
- ]
- ),
- is_hotspot=False,
- is_stable=True,
- churn_percentile=0.15,
- age_days=443,
- created_at=_NOW,
- updated_at=_NOW,
- ),
- ]
- for g in git_metas:
- session.add(g)
-
- # ---- Dead Code Findings ----
- findings = [
- DeadCodeFinding(
- id="dc1",
- repository_id=rid,
- kind="unreachable_file",
- file_path="src/legacy/old_auth.py",
- symbol_name=None,
- symbol_kind=None,
- confidence=0.9,
- reason="No imports found; file not referenced by any other module",
- lines=150,
- safe_to_delete=True,
- primary_owner="Alice",
- age_days=365,
- status="open",
- analyzed_at=_NOW,
- ),
- DeadCodeFinding(
- id="dc2",
- repository_id=rid,
- kind="unused_export",
- file_path="src/auth/service.py",
- symbol_name="deprecated_login",
- symbol_kind="function",
- confidence=0.7,
- reason="Exported but no external callers found",
- lines=20,
- safe_to_delete=True,
- primary_owner="Bob",
- age_days=120,
- status="open",
- analyzed_at=_NOW,
- ),
- DeadCodeFinding(
- id="dc3",
- repository_id=rid,
- kind="unused_export",
- file_path="src/db/models.py",
- symbol_name="OldModel",
- symbol_kind="class",
- confidence=0.5,
- reason="Exported but no external callers found",
- lines=40,
- safe_to_delete=False,
- primary_owner="Bob",
- age_days=200,
- status="open",
- analyzed_at=_NOW,
- ),
- ]
- for f in findings:
- session.add(f)
-
- # ---- Decision Records ----
- decisions = [
- DecisionRecord(
- id="dec1",
- repository_id=rid,
- title="Use JWT for authentication",
- status="proposed",
- context="Need stateless auth for microservices",
- decision="Use JWT tokens for all API authentication",
- rationale="Stateless, scalable, works across services",
- alternatives_json=json.dumps(["Session-based auth", "OAuth2 only"]),
- consequences_json=json.dumps(["Must handle token refresh", "Token size overhead"]),
- affected_files_json=json.dumps(["src/auth/service.py", "src/auth/middleware.py"]),
- affected_modules_json=json.dumps(["src/auth"]),
- tags_json=json.dumps(["auth", "security"]),
- source="readme_mining",
- confidence=0.6,
- staleness_score=0.1,
- created_at=_NOW,
- updated_at=_NOW,
- ),
- DecisionRecord(
- id="dec2",
- repository_id=rid,
- title="SQLAlchemy as ORM",
- status="proposed",
- context="Need an async-compatible ORM for Python",
- decision="Use SQLAlchemy 2.0 with async support",
- rationale="Mature, well-documented, async support in 2.0",
- alternatives_json=json.dumps(["Tortoise ORM", "Django ORM"]),
- consequences_json=json.dumps(["Learning curve for async patterns"]),
- affected_files_json=json.dumps(["src/db/models.py"]),
- affected_modules_json=json.dumps(["src/db"]),
- tags_json=json.dumps(["database"]),
- source="git_archaeology",
- confidence=0.7,
- staleness_score=0.0,
- created_at=_NOW,
- updated_at=_NOW,
- ),
- ]
- for d in decisions:
- session.add(d)
-
- await session.flush()
- return rid
-
-
-# ---------------------------------------------------------------------------
-# MCP tool tests
-# ---------------------------------------------------------------------------
-
-
-async def setup_mcp(factory, fts, vector_store, populated_db):
- """Configure the MCP module's global state for testing."""
- import repowise.server.mcp_server as mcp_mod
-
- mcp_mod._session_factory = factory
- mcp_mod._fts = fts
- mcp_mod._vector_store = vector_store
- mcp_mod._decision_store = InMemoryVectorStore(embedder=MockEmbedder())
- mcp_mod._repo_path = "/tmp/test-repo"
-
- yield populated_db
-
- # Reset globals (including workspace state)
- mcp_mod._session_factory = None
- mcp_mod._fts = None
- mcp_mod._vector_store = None
- mcp_mod._decision_store = None
- mcp_mod._repo_path = None
- mcp_mod._registry = None
- mcp_mod._workspace_root = None
-
-
-# ---- Tool 1: get_overview ----
-
-
-async def test_get_overview(setup_mcp):
- from repowise.server.mcp_server import get_overview
-
- result = await get_overview()
- assert result["title"] == "Test Repo Overview"
- assert "comprehensive test" in result["content_md"]
- assert "architecture_diagram_mermaid" not in result # removed: not useful for agents
- assert len(result["key_modules"]) == 2
- assert any(m["name"] == "Auth Module" for m in result["key_modules"])
- assert "src/auth/service.py" in result["entry_points"]
-
-
-async def test_get_overview_with_repo_path(setup_mcp):
- from repowise.server.mcp_server import get_overview
-
- result = await get_overview(repo="/tmp/test-repo")
- assert result["title"] == "Test Repo Overview"
-
-
-async def test_get_overview_repo_not_found(setup_mcp):
- from repowise.server.mcp_server import get_overview
-
- with pytest.raises(LookupError, match="not found"):
- await get_overview(repo="/nonexistent")
-
-
-# ---- Tool 2: get_context ----
-
-
-async def test_get_context_single_file(setup_mcp):
- from repowise.server.mcp_server import get_context
-
- result = await get_context(
- ["src/auth/service.py"],
- include=["docs", "full_doc", "ownership", "last_change", "decisions", "freshness"],
- compact=False,
- )
- targets = result["targets"]
- assert "src/auth/service.py" in targets
- t = targets["src/auth/service.py"]
- assert t["type"] == "file"
- # Docs
- assert t["docs"]["title"] == "Auth Service"
- assert "AuthService" in t["docs"]["content_md"]
- assert len(t["docs"]["symbols"]) == 2
- assert any(s["name"] == "AuthService" for s in t["docs"]["symbols"])
- assert "src/auth/middleware.py" in t["docs"]["imported_by"]
- # Ownership
- assert t["ownership"]["primary_owner"] == "Alice"
- assert t["ownership"]["owner_pct"] == 0.65
- assert t["ownership"]["contributor_count"] == 2
- # Last change
- assert t["last_change"]["author"] == "Alice"
- assert t["last_change"]["days_ago"] == 443
- # Decisions
- assert len(t["decisions"]) >= 1
- assert any(d["title"] == "Use JWT for authentication" for d in t["decisions"])
- # Freshness
- assert t["freshness"]["confidence_score"] == 0.85
- assert t["freshness"]["freshness_status"] == "fresh"
- assert t["freshness"]["is_stale"] is False
-
-
-async def test_get_context_single_module(setup_mcp):
- from repowise.server.mcp_server import get_context
-
- result = await get_context(
- ["src/auth"],
- include=["docs", "full_doc", "ownership", "last_change", "decisions", "freshness"],
- compact=False,
- )
- targets = result["targets"]
- assert "src/auth" in targets
- t = targets["src/auth"]
- assert t["type"] == "module"
- assert t["docs"]["title"] == "Auth Module"
- assert "authentication" in t["docs"]["content_md"].lower()
- assert len(t["docs"]["files"]) == 2 # service.py and middleware.py
- # Freshness from module page
- assert t["freshness"]["confidence_score"] == 0.95
-
-
-async def test_get_context_single_symbol(setup_mcp):
- from repowise.server.mcp_server import get_context
-
- result = await get_context(
- ["AuthService"],
- include=["docs", "full_doc"],
- compact=False,
- )
- targets = result["targets"]
- assert "AuthService" in targets
- t = targets["AuthService"]
- assert t["type"] == "symbol"
- assert t["docs"]["name"] == "AuthService"
- assert t["docs"]["kind"] == "class"
- assert t["docs"]["signature"] == "class AuthService"
- assert t["docs"]["file_path"] == "src/auth/service.py"
- assert t["docs"]["documentation"] # Has content from file page
-
-
-async def test_get_context_multiple_targets(setup_mcp):
- from repowise.server.mcp_server import get_context
-
- result = await get_context(["src/auth/service.py", "src/auth", "AuthService"])
- targets = result["targets"]
- assert len(targets) == 3
- assert targets["src/auth/service.py"]["type"] == "file"
- assert targets["src/auth"]["type"] == "module"
- assert targets["AuthService"]["type"] == "symbol"
-
-
-async def test_get_context_include_filter(setup_mcp):
- from repowise.server.mcp_server import get_context
-
- result = await get_context(["src/auth/service.py"], include=["docs"])
- t = result["targets"]["src/auth/service.py"]
- assert "docs" in t
- assert "ownership" not in t
- assert "last_change" not in t
- assert "decisions" not in t
- assert "freshness" not in t
-
-
-async def test_get_context_not_found(setup_mcp):
- from repowise.server.mcp_server import get_context
-
- result = await get_context(["nonexistent_thing_xyz"])
- t = result["targets"]["nonexistent_thing_xyz"]
- assert "error" in t
-
-
-# ---- get_context: truncation ----
-
-
-def _make_big_response(n_targets: int = 5, n_symbols: int = 80, body_chars: int = 4000) -> dict:
- """Build a synthetic get_context response well over the 32 KB budget."""
- targets = {}
- for i in range(n_targets):
- name = f"pkg/mod_{i}/file_{i}.ext"
- targets[name] = {
- "target": name,
- "type": "file",
- "docs": {
- "title": f"File {i}",
- "summary": "s" * 200,
- "content_md": "x" * body_chars,
- "symbols": [
- {
- "name": f"Sym{i}_{j}",
- "kind": "class" if j % 5 == 0 else "function",
- "signature": f"sig_{j}(...)",
- "start_line": j * 10,
- "end_line": j * 10 + 8,
- "docstring": "d" * 300,
- }
- for j in range(n_symbols)
- ],
- },
- }
- return {"targets": targets, "_meta": {"timing_ms": 1.0}}
-
-
-def test_truncate_to_budget_enforces_cap():
- from repowise.server.mcp_server.tool_context import (
- _CHAR_BUDGET,
- _truncate_to_budget,
- )
-
- big = _make_big_response()
- raw_size = len(json.dumps(big, separators=(",", ":"), default=str))
- assert raw_size > _CHAR_BUDGET, "fixture must exceed budget to be meaningful"
-
- out = _truncate_to_budget(big)
- final_size = len(json.dumps(out, separators=(",", ":"), default=str))
- assert final_size <= _CHAR_BUDGET
- assert out["truncated"] is True
- # At least one target must survive.
- assert len(out["targets"]) >= 1
-
-
-def test_truncate_flags_and_dropped_fields_populate():
- from repowise.server.mcp_server.tool_context import _truncate_to_budget
-
- big = _make_big_response(n_targets=6, n_symbols=60, body_chars=5000)
- out = _truncate_to_budget(big)
-
- assert out["truncated"] is True
- # Either whole targets were dropped, or individual symbols were dropped —
- # both are acceptable outcomes; at least one must be populated.
- dropped_any = bool(out["dropped_targets"]) or bool(out["dropped_symbols"])
- assert dropped_any
- # Heavy optional fields should have been stripped from surviving targets.
- for tgt in out["targets"].values():
- assert "content_md" not in tgt.get("docs", {})
- # Dropped symbol lists (if any) must reference actual symbol names.
- for tgt_name, names in out["dropped_symbols"].items():
- assert tgt_name in big["targets"] or tgt_name not in out["targets"]
- assert all(isinstance(n, str) for n in names)
-
-
-def test_truncate_noop_when_under_budget():
- from repowise.server.mcp_server.tool_context import _truncate_to_budget
-
- small = {
- "targets": {
- "a.py": {
- "target": "a.py",
- "type": "file",
- "docs": {"title": "A", "symbols": [{"name": "f", "kind": "function"}]},
- }
- },
- "_meta": {},
- }
- out = _truncate_to_budget(small)
- assert out["truncated"] is False
- assert out["dropped_targets"] == []
- assert out["dropped_symbols"] == {}
- assert "content_md" not in out["targets"]["a.py"]["docs"] # wasn't there anyway
-
-
-# ---- Tool 3: get_risk ----
-
-
-async def test_get_risk_single_target(setup_mcp):
- from repowise.server.mcp_server import get_risk
-
- result = await get_risk(["src/auth/service.py"])
- targets = result["targets"]
- assert "src/auth/service.py" in targets
- t = targets["src/auth/service.py"]
- assert t["hotspot_score"] == 0.92
- assert t["dependents_count"] >= 1 # middleware imports it
- assert len(t["co_change_partners"]) == 2
- assert t["primary_owner"] == "Alice"
- assert t["owner_pct"] == 0.65
- assert "risk_summary" in t
- assert "hotspot score" in t["risk_summary"]
-
- # Trend: 30d=3, 90d=8 → baseline_rate=0.083, recent=0.1 → stable
- assert t["trend"] in ("increasing", "stable", "decreasing")
-
- # Risk type: churn_percentile=0.92, no fix keywords → churn-heavy
- assert t["risk_type"] == "churn-heavy"
-
- # Impact surface: middleware.py depends on service.py
- assert len(t["impact_surface"]) >= 1
- impact_files = [s["file_path"] for s in t["impact_surface"]]
- assert "src/auth/middleware.py" in impact_files
- # Each entry has pagerank and is_entry_point
- for s in t["impact_surface"]:
- assert "pagerank" in s
- assert "is_entry_point" in s
-
-
-async def test_get_risk_multiple_targets(setup_mcp):
- from repowise.server.mcp_server import get_risk
-
- result = await get_risk(["src/auth/service.py", "src/db/models.py"])
- targets = result["targets"]
- assert len(targets) == 2
- assert "global_hotspots" in result
- # Both targets should have trend and risk_type
- for t in targets.values():
- assert "trend" in t
- assert "risk_type" in t
-
-
-async def test_get_risk_global_hotspots_exclude_targets(setup_mcp):
- from repowise.server.mcp_server import get_risk
-
- result = await get_risk(["src/auth/service.py"])
- # service.py is a hotspot but should NOT appear in global_hotspots
- for h in result["global_hotspots"]:
- assert h["file_path"] != "src/auth/service.py"
-
-
-async def test_get_risk_no_git_metadata(setup_mcp):
- from repowise.server.mcp_server import get_risk
-
- result = await get_risk(["src/auth/middleware.py"])
- t = result["targets"]["src/auth/middleware.py"]
- assert t["hotspot_score"] == 0.0 # No git metadata for this file
- assert t["trend"] == "unknown"
- assert "risk_summary" in t
- # Impact surface and risk_type still computed from graph data
- assert "risk_type" in t
- assert "impact_surface" in t
-
-
-async def test_get_risk_stable_file(setup_mcp):
- from repowise.server.mcp_server import get_risk
-
- result = await get_risk(["src/db/models.py"])
- t = result["targets"]["src/db/models.py"]
- # 0 commits in 30d and 90d → stable
- assert t["trend"] == "stable"
- # churn_percentile=0.15, dep_count=1, no fix keywords → stable
- assert t["risk_type"] == "stable"
-
-
-# ---- Tool 4: get_why ----
-
-
-async def test_get_why_natural_language(setup_mcp):
- from repowise.server.mcp_server import get_why
-
- result = await get_why("why is JWT used for authentication")
- assert result["mode"] == "search"
- assert result["query"] == "why is JWT used for authentication"
- assert len(result["decisions"]) >= 1
- assert any("JWT" in d["title"] for d in result["decisions"])
-
-
-async def test_get_why_file_path(setup_mcp):
- from repowise.server.mcp_server import get_why
-
- result = await get_why("src/auth/service.py")
- assert result["mode"] == "path"
- assert result["path"] == "src/auth/service.py"
- assert len(result["decisions"]) >= 1
- assert any(d["title"] == "Use JWT for authentication" for d in result["decisions"])
-
- # Origin story
- origin = result["origin_story"]
- assert origin["available"] is True
- assert origin["primary_author"] == "Alice"
- assert origin["total_commits"] == 42
- assert len(origin["key_commits"]) >= 1
- assert len(origin["contributors"]) >= 1
- assert "Alice" in origin["summary"]
-
- # Alignment — dec1 is "proposed", both service.py and middleware.py share it
- alignment = result["alignment"]
- assert alignment["score"] in ("high", "medium", "low", "none")
- assert alignment["governing_count"] >= 1
- assert "explanation" in alignment
-
-
-async def test_get_why_file_path_commit_decision_linkage(setup_mcp):
- from repowise.server.mcp_server import get_why
-
- result = await get_why("src/auth/service.py")
- origin = result["origin_story"]
-
- # "Add JWT support" commit should link to "Use JWT for authentication" decision
- # because "JWT" appears in both the commit message and decision title
- linked = origin["linked_decisions"]
- assert len(linked) >= 1
- jwt_decision = next((d for d in linked if d["title"] == "Use JWT for authentication"), None)
- assert jwt_decision is not None
- assert len(jwt_decision["evidence_commits"]) >= 1
- ec = jwt_decision["evidence_commits"][0]
- assert "JWT" in ec["message"] or "jwt" in ec["message"].lower()
- assert "matching_keywords" in ec
-
-
-async def test_get_why_natural_language_with_targets(setup_mcp):
- from repowise.server.mcp_server import get_why
-
- # Search with targets — decisions governing service.py should be boosted
- result = await get_why(
- "authentication approach",
- targets=["src/auth/service.py"],
- )
- assert result["mode"] == "search"
- assert len(result["decisions"]) >= 1
-
- # target_context should be present
- assert "target_context" in result
- ctx = result["target_context"]["src/auth/service.py"]
- assert len(ctx["governing_decisions"]) >= 1
- assert ctx["origin"]["available"] is True
- assert ctx["origin"]["primary_author"] == "Alice"
-
-
-async def test_get_why_expanded_keyword_search(setup_mcp):
- from repowise.server.mcp_server import get_why
-
- # Search for "security" — should match via tags_json on dec1
- result = await get_why("security")
- assert result["mode"] == "search"
- # dec1 has tags=["auth", "security"], should be found
- assert len(result["decisions"]) >= 1
- assert any(d.get("title") == "Use JWT for authentication" for d in result["decisions"])
-
-
-async def test_get_why_file_no_git_metadata(setup_mcp):
- from repowise.server.mcp_server import get_why
-
- # middleware.py has no GitMetadata in the fixture
- result = await get_why("src/auth/middleware.py")
- assert result["mode"] == "path"
- origin = result["origin_story"]
- assert origin["available"] is False
- assert "No git history" in origin["summary"]
-
- # But it still has decisions (dec1 affects middleware.py)
- assert len(result["decisions"]) >= 1
- alignment = result["alignment"]
- assert alignment["governing_count"] >= 1
-
-
-async def test_get_why_file_ungoverned(setup_mcp):
- from repowise.server.mcp_server import get_why
-
- # Use a path that has no decisions — triggers git archaeology fallback
- result = await get_why("src/other/utils.py")
- assert result["mode"] == "path"
- assert result["alignment"]["score"] == "none"
- assert "ungoverned" in result["alignment"]["explanation"]
-
- # Git archaeology fallback should be triggered
- assert "git_archaeology" in result
- arch = result["git_archaeology"]
- assert arch["triggered"] is True
- assert "summary" in arch
- assert "file_commits" in arch
- assert "cross_references" in arch
- assert "git_log" in arch
-
-
-async def test_get_why_fallback_with_cross_references(setup_mcp):
- from repowise.server.mcp_server import get_why
-
- # src/auth/service.py has git metadata with commits mentioning "auth"
- # Query a nonexistent auth file — cross-references should find commits
- # from service.py that mention "auth" terms
- result = await get_why("src/auth/new_handler.py")
- assert result["mode"] == "path"
- assert len(result["decisions"]) == 0 # No decisions for this file
-
- arch = result["git_archaeology"]
- assert arch["triggered"] is True
- # Cross-references may find commits from service.py whose messages
- # contain "auth" (matching the path stem "new_handler" won't match,
- # but the file_commits will still be empty since no git metadata exists)
- assert isinstance(arch["cross_references"], list)
-
-
-async def test_get_why_targets_fallback(setup_mcp):
- from repowise.server.mcp_server import get_why
-
- # Search with a target that has no governing decisions
- result = await get_why(
- "why does this exist",
- targets=["src/other/unknown.py"],
- )
- assert result["mode"] == "search"
- ctx = result["target_context"]["src/other/unknown.py"]
- assert len(ctx["governing_decisions"]) == 0
- # Fallback should trigger
- assert "git_archaeology" in ctx
- assert ctx["git_archaeology"]["triggered"] is True
-
-
-async def test_get_why_no_args(setup_mcp):
- from repowise.server.mcp_server import get_why
-
- result = await get_why()
- assert result["mode"] == "health"
- assert "summary" in result
- assert "counts" in result
- assert "proposed_awaiting_review" in result
- assert "ungoverned_hotspots" in result
-
-
-async def test_get_why_module_path(setup_mcp):
- from repowise.server.mcp_server import get_why
-
- result = await get_why("src/db")
- assert result["mode"] == "path"
- assert len(result["decisions"]) >= 1
- assert any(d["title"] == "SQLAlchemy as ORM" for d in result["decisions"])
-
-
-async def test_get_why_semantic_decision_namespace_filtering(setup_mcp):
- """Mode 3 semantic path: over-fetch from page store, keep only decision: hits.
-
- Upserts a decision vector under the 'decision:' prefix and a noise page
- without the prefix into the shared vector store. Confirms that get_why
- surfaces the decision hit with the prefix stripped, and excludes the noise
- page from the decisions list.
- """
- import repowise.server.mcp_server as mcp_mod
- from repowise.core.analysis.decision_semantic_match import DECISION_VECTOR_PREFIX
- from repowise.server.mcp_server import get_why
-
- vs = mcp_mod._vector_store
-
- # Insert a decision under the decision: namespace
- await vs.embed_and_upsert(
- f"{DECISION_VECTOR_PREFIX}dec-vec-1",
- "Use Redis for caching to reduce latency",
- {
- "title": "Use Redis for caching",
- "page_type": "decision_record",
- "target_path": "",
- "content": "Use Redis for caching to reduce latency",
- },
- )
-
- # Insert a noise page (no decision: prefix) with similar text
- await vs.embed_and_upsert(
- "file_page:src/cache/redis.py",
- "Redis caching implementation module",
- {
- "title": "Redis Cache Module",
- "page_type": "file_page",
- "target_path": "src/cache/redis.py",
- "content": "Redis caching implementation module",
- },
- )
-
- result = await get_why("why use Redis for caching")
- assert result["mode"] == "search"
-
- decision_ids = [d["id"] for d in result["decisions"]]
- # The semantic decision hit should appear with the prefix stripped
- assert "dec-vec-1" in decision_ids, (
- f"Expected 'dec-vec-1' in decisions; got {decision_ids}"
- )
- # The noise page must not appear in decisions
- assert not any(
- d.get("id", "").startswith("file_page:") for d in result["decisions"]
- ), "Noise page should not appear in decisions list"
-
-
-# ---- Tool 5: search_codebase ----
-
-
-async def test_search_codebase(setup_mcp):
- # Index pages in the MCP module's vector store (which is the InMemoryVectorStore)
- import repowise.server.mcp_server as mcp_mod
- from repowise.server.mcp_server import search_codebase
-
- await mcp_mod._vector_store.embed_and_upsert(
- "file_page:src/auth/service.py",
- "Auth Service — Main authentication service class",
- {"title": "Auth Service", "page_type": "file_page", "target_path": "src/auth/service.py"},
- )
- await mcp_mod._vector_store.embed_and_upsert(
- "file_page:src/db/models.py",
- "DB Models — SQLAlchemy ORM models",
- {"title": "DB Models", "page_type": "file_page", "target_path": "src/db/models.py"},
- )
-
- result = await search_codebase("authentication service")
- assert "results" in result
- assert len(result["results"]) >= 1
-
-
-# ---- Tool 6: get_dead_code ----
-
-
-async def test_get_dead_code(setup_mcp):
- from repowise.server.mcp_server import get_dead_code
-
- result = await get_dead_code()
- assert result["summary"]["total_findings"] == 3
- assert result["summary"]["safe_to_delete_count"] == 2
-
- # Tiered structure: dc1 (0.9) in high, dc2 (0.7) + dc3 (0.5) in medium
- tiers = result["tiers"]
- assert tiers["high"]["count"] == 1
- assert tiers["medium"]["count"] == 2
- assert tiers["low"]["count"] == 0
-
- # High tier findings sorted by confidence desc
- high_findings = tiers["high"]["findings"]
- assert high_findings[0]["confidence"] >= 0.8
-
- # Impact estimate present
- assert result["impact"]["total_lines_reclaimable"] > 0
-
-
-async def test_get_dead_code_safe_only(setup_mcp):
- from repowise.server.mcp_server import get_dead_code
-
- result = await get_dead_code(safe_only=True)
- for tier_data in result["tiers"].values():
- for f in tier_data["findings"]:
- assert f["safe_to_delete"] is True
-
-
-async def test_get_dead_code_by_kind(setup_mcp):
- from repowise.server.mcp_server import get_dead_code
-
- result = await get_dead_code(kind="unreachable_file", min_confidence=0.0)
- for tier_data in result["tiers"].values():
- for f in tier_data["findings"]:
- assert f["kind"] == "unreachable_file"
-
-
-async def test_get_dead_code_low_confidence(setup_mcp):
- from repowise.server.mcp_server import get_dead_code
-
- result = await get_dead_code(min_confidence=0.0)
- total = sum(t["count"] for t in result["tiers"].values())
- assert total == 3 # All 3 findings included
-
-
-async def test_get_dead_code_tier_filter(setup_mcp):
- from repowise.server.mcp_server import get_dead_code
-
- result = await get_dead_code(tier="high")
- assert "high" in result["tiers"]
- assert "medium" not in result["tiers"]
- assert "low" not in result["tiers"]
- assert result["tiers"]["high"]["count"] == 1
-
-
-async def test_get_dead_code_group_by_directory(setup_mcp):
- from repowise.server.mcp_server import get_dead_code
-
- result = await get_dead_code(group_by="directory", min_confidence=0.0)
- assert "by_directory" in result
- dirs = result["by_directory"]
- assert len(dirs) >= 1
- # Each dir entry has count, lines, safe_count
- for d in dirs:
- assert "directory" in d
- assert "count" in d
- assert "lines" in d
-
-
-async def test_get_dead_code_group_by_owner(setup_mcp):
- from repowise.server.mcp_server import get_dead_code
-
- result = await get_dead_code(group_by="owner", min_confidence=0.0)
- assert "by_owner" in result
- owners = result["by_owner"]
- assert len(owners) >= 1
- owner_names = [o["owner"] for o in owners]
- assert "Bob" in owner_names # Bob owns dc2 + dc3
-
-
-# ---- Tool: get_health ----
-
-
-async def health_data(session: AsyncSession, populated_db: str) -> str:
- """Seed health_findings + health_file_metrics for the existing repo."""
- from repowise.core.persistence.crud import (
- save_health_findings,
- save_health_metrics,
- )
-
- rid = populated_db
- await save_health_metrics(
- session,
- rid,
- [
- {
- "file_path": "src/auth/service.py",
- "score": 4.5,
- "max_ccn": 15,
- "max_nesting": 5,
- "nloc": 200,
- "has_test_file": False,
- "module": "auth",
- },
- {
- "file_path": "src/db/models.py",
- "score": 8.5,
- "max_ccn": 4,
- "max_nesting": 2,
- "nloc": 50,
- "has_test_file": True,
- "module": "db",
- },
- ],
- )
- await save_health_findings(
- session,
- rid,
- [
- {
- "file_path": "src/auth/service.py",
- "biomarker_type": "complex_method",
- "severity": "high",
- "function_name": "authenticate",
- "line_start": 10,
- "line_end": 80,
- "details": {"ccn": 15, "cognitive": 30, "nloc": 70},
- "health_impact": 1.2,
- "reason": "authenticate has cyclomatic complexity 15",
- },
- {
- "file_path": "src/auth/service.py",
- "biomarker_type": "nested_complexity",
- "severity": "medium",
- "function_name": "authenticate",
- "line_start": 10,
- "line_end": 80,
- "details": {"max_nesting": 5, "ccn": 15, "cognitive": 30},
- "health_impact": 0.7,
- "reason": "authenticate nests 5 levels deep",
- },
- ],
- )
- await session.commit()
- return rid
-
-
-async def test_get_health_dashboard(setup_mcp, health_data):
- from repowise.server.mcp_server import get_health
-
- result = await get_health()
- assert result["mode"] == "dashboard"
- assert result["kpis"]["file_count"] == 2
- assert result["kpis"]["worst_performer_path"] == "src/auth/service.py"
- assert len(result["worst_files"]) == 2
- assert result["worst_files"][0]["file_path"] == "src/auth/service.py"
- assert len(result["top_findings"]) == 2
-
-
-async def test_get_health_targeted(setup_mcp, health_data):
- from repowise.server.mcp_server import get_health
-
- result = await get_health(targets=["src/auth/service.py"])
- assert result["mode"] == "targets"
- assert len(result["metrics"]) == 1
- assert result["metrics"][0]["max_ccn"] == 15
- assert all(f["file_path"] == "src/auth/service.py" for f in result["findings"])
-
-
-# ---- MCP config generation ----
-
-
-def test_generate_mcp_config():
- from pathlib import Path
-
- from repowise.cli.mcp_config import generate_mcp_config
-
- config = generate_mcp_config(Path("/tmp/test-repo"))
- assert "mcpServers" in config
- assert "repowise" in config["mcpServers"]
- server = config["mcpServers"]["repowise"]
- assert server["command"] == "repowise"
- assert "mcp" in server["args"]
- assert "stdio" in server["args"]
-
-
-def test_format_setup_instructions():
- from pathlib import Path
-
- from repowise.cli.mcp_config import format_setup_instructions
-
- instructions = format_setup_instructions(Path("/tmp/test-repo"))
- assert "Project .mcp.json" in instructions
- assert "Claude Code" not in instructions
- assert "Cursor" in instructions
- assert "Cline" in instructions
- assert "repowise" in instructions
-
-
-# ---- MCP lifespan DB resolution ----
-
-
-async def test_mcp_lifespan_uses_cli_database_env_var(monkeypatch):
- """REPOWISE_DB_URL should be respected by MCP lifespan via resolve_db_url."""
- import repowise.server.mcp_server._server as mcp_server
- from repowise.server.mcp_server import _state
-
- captured: dict[str, str] = {}
-
- class DummyEngine:
- @property
- def dialect(self):
- class _D:
- name = "sqlite"
- return _D()
-
- async def dispose(self) -> None:
- return None
-
- class DummyFts:
- def __init__(self, engine) -> None:
- self.engine = engine
-
- async def ensure_index(self) -> None:
- return None
-
- class DummyVectorStore:
- def __init__(self, *, embedder) -> None:
- self.embedder = embedder
-
- async def close(self) -> None:
- return None
-
- async def fake_init_db(engine) -> None:
- return None
-
- async def fake_load_vector_stores(repo_path: str | None) -> None:
- return None
-
- def fake_create_async_engine(url: str, connect_args: dict | None = None) -> DummyEngine:
- captured["url"] = url
- return DummyEngine()
-
- monkeypatch.setenv("REPOWISE_DB_URL", "sqlite+aiosqlite:///tmp/from-cli.db")
- monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)
- monkeypatch.setattr(mcp_server, "create_async_engine", fake_create_async_engine)
- monkeypatch.setattr(mcp_server, "init_db", fake_init_db)
- monkeypatch.setattr(mcp_server, "FullTextSearch", DummyFts)
- monkeypatch.setattr(mcp_server, "InMemoryVectorStore", DummyVectorStore)
- monkeypatch.setattr(mcp_server, "async_sessionmaker", lambda *args, **kwargs: object())
- monkeypatch.setattr(mcp_server, "_load_vector_stores", fake_load_vector_stores)
-
- original_repo_path = _state._repo_path
- original_vector_store = _state._vector_store
- original_decision_store = _state._decision_store
- original_ready = _state._vector_store_ready
-
- _state._repo_path = None
- _state._vector_store = None
- _state._decision_store = None
- _state._vector_store_ready = None
-
- try:
- async with mcp_server._lifespan(mcp_server.mcp):
- assert captured["url"] == "sqlite+aiosqlite:///tmp/from-cli.db"
- finally:
- _state._repo_path = original_repo_path
- _state._vector_store = original_vector_store
- _state._decision_store = original_decision_store
- _state._vector_store_ready = original_ready
diff --git a/tests/unit/test_dead_code.py b/tests/unit/test_dead_code.py
deleted file mode 100644
index 1644a223e..000000000
--- a/tests/unit/test_dead_code.py
+++ /dev/null
@@ -1,1713 +0,0 @@
-"""Unit tests for DeadCodeAnalyzer."""
-
-from __future__ import annotations
-
-from datetime import UTC, datetime, timedelta
-
-import networkx as nx
-import pytest
-
-from repowise.core.analysis.dead_code import (
- DeadCodeAnalyzer,
- DeadCodeKind,
-)
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-
-def _now() -> datetime:
- return datetime.now(UTC)
-
-
-def _old_date(days: int = 365) -> datetime:
- """Return a datetime `days` ago (timezone-aware)."""
- return _now() - timedelta(days=days)
-
-
-def _build_graph(
- nodes: dict[str, dict],
- edges: list[tuple[str, str]] | None = None,
-) -> nx.DiGraph:
- """Create a DiGraph with the given node attributes and edges.
-
- ``nodes`` maps node-id to its attribute dict. If a node has a
- ``symbols`` list, each entry is promoted to a proper symbol node
- connected to the file via a ``defines`` edge (matching the real
- GraphBuilder layout).
- ``edges`` is a list of (src, dst) pairs; edge data can be
- supplied as a 3-tuple (src, dst, data_dict).
- """
- g = nx.DiGraph()
- for name, attrs in nodes.items():
- attrs.setdefault("language", "python")
- # Extract symbols before adding the file node
- sym_list = attrs.pop("symbols", [])
- g.add_node(name, **attrs)
- # Create symbol nodes + defines edges (mirrors GraphBuilder.add_file)
- for sym in sym_list:
- sym_id = f"{name}::{sym['name']}"
- g.add_node(
- sym_id,
- node_type="symbol",
- file_path=name,
- **sym,
- )
- g.add_edge(name, sym_id, edge_type="defines")
- for edge in edges or []:
- if len(edge) == 3:
- g.add_edge(edge[0], edge[1], **(edge[2]))
- else:
- g.add_edge(edge[0], edge[1])
- return g
-
-
-# ---------------------------------------------------------------------------
-# 1. test_unreachable_file_detected
-# ---------------------------------------------------------------------------
-
-
-def test_unreachable_file_detected():
- """A file with in_degree=0, not an entry point, should be flagged as unreachable."""
- g = _build_graph(
- nodes={
- "pkg/orphan.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 5,
- "symbols": [],
- },
- "pkg/main.py": {
- "is_entry_point": True,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 10,
- "symbols": [],
- },
- },
- edges=[], # orphan.py has in_degree=0
- )
-
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze({"detect_unused_exports": False, "detect_zombie_packages": False})
-
- unreachable = [f for f in report.findings if f.kind == DeadCodeKind.UNREACHABLE_FILE]
- paths = [f.file_path for f in unreachable]
- assert "pkg/orphan.py" in paths
-
-
-# ---------------------------------------------------------------------------
-# 2. test_entry_point_not_flagged
-# ---------------------------------------------------------------------------
-
-
-def test_entry_point_not_flagged():
- """A file marked as is_entry_point=True should NOT be flagged even with in_degree=0."""
- g = _build_graph(
- nodes={
- "pkg/main.py": {
- "is_entry_point": True,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 10,
- "symbols": [],
- },
- },
- )
-
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze({"detect_unused_exports": False, "detect_zombie_packages": False})
-
- assert all(f.file_path != "pkg/main.py" for f in report.findings)
-
-
-# ---------------------------------------------------------------------------
-# 3. test_test_files_excluded
-# ---------------------------------------------------------------------------
-
-
-def test_test_files_excluded():
- """A test file (is_test=True) with in_degree=0 should NOT be flagged."""
- g = _build_graph(
- nodes={
- "tests/test_something.py": {
- "is_entry_point": False,
- "is_test": True,
- "is_api_contract": False,
- "symbol_count": 8,
- "symbols": [],
- },
- },
- )
-
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze({"detect_unused_exports": False, "detect_zombie_packages": False})
-
- assert all(f.file_path != "tests/test_something.py" for f in report.findings)
-
-
-# ---------------------------------------------------------------------------
-# 4. test_unused_export_detected
-# ---------------------------------------------------------------------------
-
-
-def test_unused_export_detected():
- """A public symbol with no importers should be flagged as unused export."""
- g = _build_graph(
- nodes={
- "pkg/utils.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 3,
- "symbols": [
- {
- "name": "helper_func",
- "kind": "function",
- "visibility": "public",
- "decorators": [],
- "start_line": 1,
- "end_line": 10,
- "complexity_estimate": 2,
- },
- ],
- },
- "pkg/main.py": {
- "is_entry_point": True,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 10,
- "symbols": [],
- },
- },
- # main.py imports utils.py but does NOT import helper_func by name
- edges=[("pkg/main.py", "pkg/utils.py", {"imported_names": ["other_func"]})],
- )
-
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {
- "detect_unreachable_files": False,
- "detect_zombie_packages": False,
- }
- )
-
- unused = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]
- sym_names = [f.symbol_name for f in unused]
- assert "helper_func" in sym_names
-
-
-def test_entry_point_names_never_flagged():
- """Runtime entry points (wWinMain, TEST_METHOD, DllInstall…) are
- never flagged regardless of incoming-edge counts. The Win32 / COM /
- MSTest runners reach them by mechanism, not by a `using` import."""
- g = _build_graph(
- nodes={
- "src/main.cpp": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 3,
- "language": "cpp",
- "symbols": [
- {
- "name": "wWinMain",
- "kind": "function",
- "visibility": "public",
- "decorators": [],
- "start_line": 1, "end_line": 10,
- "complexity_estimate": 1,
- },
- {
- "name": "TEST_METHOD",
- "kind": "function",
- "visibility": "public",
- "decorators": [],
- "start_line": 12, "end_line": 20,
- "complexity_estimate": 1,
- },
- ],
- },
- },
- edges=[],
- )
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {"detect_unreachable_files": False, "detect_zombie_packages": False}
- )
- names = [f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]
- assert "wWinMain" not in names
- assert "TEST_METHOD" not in names
-
-
-def test_unused_export_skipped_when_symbol_has_incoming_calls():
- """A public symbol with no file-level importers but at least one
- incoming ``calls`` edge on the symbol itself is still in use —
- typical for C++ intra-file helpers and ``Foo::method`` qualified
- definitions reached via call resolution rather than headers."""
- g = _build_graph(
- nodes={
- "pkg/utils.cpp": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 2,
- "language": "cpp",
- "symbols": [
- {
- "name": "helper",
- "kind": "function",
- "visibility": "public",
- "decorators": [],
- "start_line": 1,
- "end_line": 10,
- "complexity_estimate": 1,
- },
- {
- "name": "caller",
- "kind": "function",
- "visibility": "public",
- "decorators": [],
- "start_line": 12,
- "end_line": 20,
- "complexity_estimate": 1,
- },
- ],
- },
- },
- edges=[
- ("pkg/utils.cpp::caller", "pkg/utils.cpp::helper", {"edge_type": "calls"}),
- ],
- )
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {
- "detect_unreachable_files": False,
- "detect_zombie_packages": False,
- }
- )
- sym_names = [f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]
- # ``helper`` is called by ``caller`` — must not be flagged.
- assert "helper" not in sym_names
- # ``caller`` has no callers — still flagged.
- assert "caller" in sym_names
-
-
-def test_interface_without_implementor_demoted_below_safe_threshold():
- """Public interfaces with no incoming ``implements`` edges have
- their unused-export confidence clamped below 0.7 so the demo
- doesn't ship them as confident dead code. Implementor detection
- is heuristic — absence is missing-signal, not evidence-of-absence.
- """
- g = _build_graph(
- nodes={
- "src/IBasketService.cs": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 1,
- "symbols": [
- {
- "name": "IBasketService",
- "kind": "interface",
- "visibility": "public",
- "decorators": [],
- "start_line": 1,
- "end_line": 5,
- "complexity_estimate": 1,
- "language": "csharp",
- },
- ],
- },
- },
- edges=[],
- )
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze({
- "detect_unreachable_files": False,
- "detect_zombie_packages": False,
- "min_confidence": 0.0,
- })
- interface_findings = [
- f for f in report.findings
- if f.kind == DeadCodeKind.UNUSED_EXPORT and f.symbol_name == "IBasketService"
- ]
- # The finding may still surface, but never at safe-to-delete confidence.
- for f in interface_findings:
- assert f.confidence <= 0.4, f"interface flagged at unsafe confidence {f.confidence}"
- assert f.safe_to_delete is False
-
-
-def test_com_contract_method_demoted_below_safe_threshold():
- """``QueryInterface`` / ``AddRef`` / ``Release`` are reached through
- a native COM vtable — never via a static caller. The analyzer must
- not flag them as confident dead code.
- """
- g = _build_graph(
- nodes={
- "src/CoFoo.cpp": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 3,
- "symbols": [
- {
- "name": "QueryInterface",
- "kind": "method",
- "visibility": "public",
- "decorators": [],
- "start_line": 10,
- "end_line": 25,
- "complexity_estimate": 1,
- "language": "cpp",
- },
- {
- "name": "AddRef",
- "kind": "function",
- "visibility": "public",
- "decorators": [],
- "start_line": 27,
- "end_line": 30,
- "complexity_estimate": 1,
- "language": "cpp",
- },
- {
- "name": "Release",
- "kind": "method",
- "visibility": "public",
- "decorators": [],
- "start_line": 32,
- "end_line": 40,
- "complexity_estimate": 1,
- "language": "cpp",
- },
- ],
- },
- },
- edges=[],
- )
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze({
- "detect_unreachable_files": False,
- "detect_zombie_packages": False,
- "min_confidence": 0.0,
- })
- com_findings = [
- f for f in report.findings
- if f.symbol_name in {"QueryInterface", "AddRef", "Release"}
- ]
- for f in com_findings:
- assert f.confidence <= 0.4, f"COM method flagged at unsafe confidence {f.confidence}"
- assert f.safe_to_delete is False
-
-
-def test_release_in_non_com_language_not_clamped():
- """A free function named ``Release`` in TypeScript/Python is *not* a
- COM contract method — the contract-method clamp must not apply.
- """
- g = _build_graph(
- nodes={
- "src/foo.ts": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 1,
- "symbols": [
- {
- "name": "Release",
- "kind": "function",
- "visibility": "public",
- "decorators": [],
- "start_line": 1,
- "end_line": 5,
- "complexity_estimate": 1,
- "language": "typescript",
- },
- ],
- },
- },
- edges=[],
- )
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze({
- "detect_unreachable_files": False,
- "detect_zombie_packages": False,
- "min_confidence": 0.0,
- })
- # TS ``function`` kind is universally skipped from unused-export
- # detection (functions surface as variables in JS-style modules),
- # so the strongest assertion is "no spurious COM clamp masked the
- # real behaviour". The function should still be detectable somehow
- # downstream; here we just confirm the analyzer didn't crash and
- # didn't ship it under contract-method semantics.
- com_findings = [f for f in report.findings if f.symbol_name == "Release"]
- for f in com_findings:
- # If it surfaces at all, it must do so under the *normal*
- # rule — not under the COM clamp specifically. The normal
- # rule yields 0.7 / 1.0 depending on file-level importers.
- assert f.confidence >= 0.7 or f.confidence < 0.4
-
-
-# ---------------------------------------------------------------------------
-# 5. test_framework_decorator_excluded
-# ---------------------------------------------------------------------------
-
-
-def test_framework_decorator_excluded():
- """A symbol decorated with pytest.fixture should NOT be flagged."""
- g = _build_graph(
- nodes={
- "pkg/conftest.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 2,
- "symbols": [
- {
- "name": "db_session",
- "kind": "function",
- "visibility": "public",
- "decorators": ["pytest.fixture"],
- "start_line": 1,
- "end_line": 15,
- "complexity_estimate": 1,
- },
- ],
- },
- },
- )
-
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {
- "detect_unreachable_files": False,
- "detect_zombie_packages": False,
- }
- )
-
- sym_names = [f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]
- assert "db_session" not in sym_names
-
-
-# ---------------------------------------------------------------------------
-# 6. test_dynamic_pattern_excluded
-# ---------------------------------------------------------------------------
-
-
-def test_dynamic_pattern_excluded():
- """A symbol matching '*Handler' dynamic pattern should NOT be flagged as unused."""
- g = _build_graph(
- nodes={
- "pkg/events.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 2,
- "symbols": [
- {
- "name": "EventHandler",
- "kind": "class",
- "visibility": "public",
- "decorators": [],
- "start_line": 1,
- "end_line": 40,
- "complexity_estimate": 3,
- },
- ],
- },
- },
- )
-
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {
- "detect_unreachable_files": False,
- "detect_zombie_packages": False,
- }
- )
-
- sym_names = [f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]
- assert "EventHandler" not in sym_names
-
-
-# ---------------------------------------------------------------------------
-# 6b. test_nested_function_not_flagged
-# ---------------------------------------------------------------------------
-
-
-def test_nested_function_not_flagged():
- """Symbols defined inside another function's body cannot be imported by
- name and must not be flagged as unused exports."""
- g = _build_graph(
- nodes={
- "pkg/server.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 2,
- "symbols": [
- {
- "name": "chat",
- "kind": "function",
- "visibility": "public",
- "decorators": [],
- "start_line": 10,
- "end_line": 80,
- },
- # Nested closure / inner generator — line range strictly
- # contained inside ``chat``.
- {
- "name": "event_stream",
- "kind": "function",
- "visibility": "public",
- "decorators": [],
- "start_line": 25,
- "end_line": 60,
- },
- ],
- },
- },
- )
-
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {
- "detect_unreachable_files": False,
- "detect_zombie_packages": False,
- }
- )
- sym_names = [f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]
- assert "event_stream" not in sym_names
-
-
-# ---------------------------------------------------------------------------
-# 6c. test_at_prefixed_decorator_excluded
-# ---------------------------------------------------------------------------
-
-
-def test_at_prefixed_decorator_excluded():
- """Decorators stored with the leading '@' (as the parser emits them)
- must still match the framework-decorator whitelist."""
- g = _build_graph(
- nodes={
- "pkg/routes.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 2,
- "symbols": [
- {
- "name": "list_items",
- "kind": "function",
- "visibility": "public",
- "decorators": ["@router.get(\"/items\")"],
- "start_line": 1,
- "end_line": 8,
- },
- {
- "name": "lifespan",
- "kind": "function",
- "visibility": "public",
- "decorators": ["@asynccontextmanager"],
- "start_line": 10,
- "end_line": 20,
- },
- ],
- },
- },
- )
-
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {
- "detect_unreachable_files": False,
- "detect_zombie_packages": False,
- }
- )
- sym_names = [f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]
- assert "list_items" not in sym_names
- assert "lifespan" not in sym_names
-
-
-# ---------------------------------------------------------------------------
-# 7. test_confidence_low_for_recent_files
-# ---------------------------------------------------------------------------
-
-
-def test_confidence_low_for_recent_files():
- """Unreachable file with commit_count_90d > 0 should have confidence 0.4."""
- g = _build_graph(
- nodes={
- "pkg/recent.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 5,
- "symbols": [],
- },
- },
- )
-
- git_meta = {
- "pkg/recent.py": {
- "commit_count_90d": 3,
- "last_commit_at": _now() - timedelta(days=10),
- "age_days": 100,
- "primary_owner_name": "[email protected]",
- },
- }
-
- analyzer = DeadCodeAnalyzer(g, git_meta_map=git_meta)
- report = analyzer.analyze(
- {
- "detect_unused_exports": False,
- "detect_zombie_packages": False,
- "min_confidence": 0.0,
- }
- )
-
- findings = [f for f in report.findings if f.file_path == "pkg/recent.py"]
- assert len(findings) == 1
- assert findings[0].confidence == pytest.approx(0.4)
-
-
-# ---------------------------------------------------------------------------
-# 8. test_confidence_high_for_stale_unreachable
-# ---------------------------------------------------------------------------
-
-
-def test_confidence_high_for_stale_unreachable():
- """Unreachable file with no commits in 90d and last commit > 6 months ago -> confidence 1.0."""
- g = _build_graph(
- nodes={
- "pkg/stale.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 5,
- "symbols": [],
- },
- },
- )
-
- git_meta = {
- "pkg/stale.py": {
- "commit_count_90d": 0,
- "last_commit_at": _old_date(days=365),
- "age_days": 730,
- "primary_owner_name": "[email protected]",
- },
- }
-
- analyzer = DeadCodeAnalyzer(g, git_meta_map=git_meta)
- report = analyzer.analyze(
- {
- "detect_unused_exports": False,
- "detect_zombie_packages": False,
- }
- )
-
- findings = [f for f in report.findings if f.file_path == "pkg/stale.py"]
- assert len(findings) == 1
- assert findings[0].confidence == pytest.approx(1.0)
-
-
-# ---------------------------------------------------------------------------
-# 9. test_zombie_package_detected
-# ---------------------------------------------------------------------------
-
-
-def test_zombie_package_detected():
- """A package with no incoming inter-package imports should be flagged as zombie."""
- g = _build_graph(
- nodes={
- "pkgA/mod1.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 5,
- "symbols": [],
- },
- "pkgA/mod2.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 3,
- "symbols": [],
- },
- "pkgB/mod1.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 7,
- "symbols": [],
- },
- },
- edges=[
- # pkgA/mod1 imports from pkgA/mod2 (intra-package only)
- ("pkgA/mod1.py", "pkgA/mod2.py"),
- # pkgB has no inter-package importers either, but we focus on pkgA
- # having NO imports from pkgB -> pkgA
- ],
- )
-
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {
- "detect_unreachable_files": False,
- "detect_unused_exports": False,
- "min_confidence": 0.0,
- }
- )
-
- zombie = [f for f in report.findings if f.kind == DeadCodeKind.ZOMBIE_PACKAGE]
- pkgs = [f.package for f in zombie]
- # Both pkgA and pkgB are zombie since neither has inter-package importers
- assert "pkgA" in pkgs
- assert "pkgB" in pkgs
-
-
-def test_framework_anchor_counts_as_cross_package_importer():
- """``framework:`` synthetic predecessors should rescue a package from zombie status.
-
- ``external:`` predecessors don't count (third-party imports), but
- ``framework:`` anchors model real framework-mediated loading
- (e.g. TYPO3 core loading every ``Configuration/*.php``) and should.
- """
- g = _build_graph(
- nodes={
- "Configuration/foo.php": {"is_entry_point": False, "symbol_count": 1, "symbols": []},
- "src/main.php": {"is_entry_point": False, "symbol_count": 1, "symbols": []},
- },
- )
- g.add_node("framework:typo3-core", language="external")
- g.add_edge("framework:typo3-core", "Configuration/foo.php", edge_type="framework")
-
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {
- "detect_unreachable_files": False,
- "detect_unused_exports": False,
- "min_confidence": 0.0,
- }
- )
-
- zombie_pkgs = [
- f.package for f in report.findings if f.kind == DeadCodeKind.ZOMBIE_PACKAGE
- ]
- assert "Configuration" not in zombie_pkgs, (
- "framework: predecessors should count as cross-package importers"
- )
-
-
-def test_framework_anchor_node_not_flagged_as_unreachable():
- """A ``framework:`` synthetic node must not itself be flagged as dead."""
- g = _build_graph(
- nodes={
- "ext_localconf.php": {"is_entry_point": False, "symbol_count": 1, "symbols": []},
- },
- )
- g.add_node("framework:typo3-core", language="external")
- g.add_edge("framework:typo3-core", "ext_localconf.php", edge_type="framework")
-
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze({"min_confidence": 0.0})
-
- paths = [f.file_path for f in report.findings]
- assert "framework:typo3-core" not in paths
- # ext_localconf.php should also not be flagged: it has a framework: predecessor.
- assert "ext_localconf.php" not in paths
-
-
-# ---------------------------------------------------------------------------
-# 10. test_whitelist_respected
-# ---------------------------------------------------------------------------
-
-
-def test_whitelist_respected():
- """A file in the whitelist should NOT be flagged even if it is unreachable."""
- g = _build_graph(
- nodes={
- "pkg/legacy.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 20,
- "symbols": [],
- },
- },
- )
-
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {
- "detect_unused_exports": False,
- "detect_zombie_packages": False,
- "whitelist": ["pkg/legacy.py"],
- }
- )
-
- assert all(f.file_path != "pkg/legacy.py" for f in report.findings)
-
-
-# ---------------------------------------------------------------------------
-# 11. test_safe_to_delete_conservative
-# ---------------------------------------------------------------------------
-
-
-def test_safe_to_delete_conservative():
- """safe_to_delete is True only when confidence >= 0.7 AND file does not match dynamic patterns."""
- g = _build_graph(
- nodes={
- # High confidence, no dynamic pattern match -> safe
- "pkg/old_unused.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 5,
- "symbols": [],
- },
- # High confidence, but file stem matches *Handler -> NOT safe
- "pkg/RequestHandler.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 5,
- "symbols": [],
- },
- # Low confidence (recently touched) -> NOT safe
- "pkg/fresh.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 5,
- "symbols": [],
- },
- },
- )
-
- git_meta = {
- "pkg/old_unused.py": {
- "commit_count_90d": 0,
- "last_commit_at": _old_date(days=365),
- "age_days": 500,
- },
- "pkg/RequestHandler.py": {
- "commit_count_90d": 0,
- "last_commit_at": _old_date(days=365),
- "age_days": 500,
- },
- "pkg/fresh.py": {
- "commit_count_90d": 5,
- "last_commit_at": _now() - timedelta(days=3),
- "age_days": 60,
- },
- }
-
- analyzer = DeadCodeAnalyzer(g, git_meta_map=git_meta)
- report = analyzer.analyze(
- {
- "detect_unused_exports": False,
- "detect_zombie_packages": False,
- "min_confidence": 0.0,
- }
- )
-
- by_path = {f.file_path: f for f in report.findings}
- # High confidence + no dynamic pattern -> safe
- assert by_path["pkg/old_unused.py"].safe_to_delete is True
- # High confidence but matches *Handler -> not safe
- assert by_path["pkg/RequestHandler.py"].safe_to_delete is False
- # Low confidence (0.4) -> not safe
- assert by_path["pkg/fresh.py"].safe_to_delete is False
-
-
-# ---------------------------------------------------------------------------
-# 12. test_report_deletable_lines_sum
-# ---------------------------------------------------------------------------
-
-
-def test_report_deletable_lines_sum():
- """report.deletable_lines should equal the sum of lines for safe_to_delete findings."""
- g = _build_graph(
- nodes={
- "pkg/dead1.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 10, # lines = 10 * 10 = 100
- "symbols": [],
- },
- "pkg/dead2.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 20, # lines = 20 * 10 = 200
- "symbols": [],
- },
- "pkg/alive.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 15, # lines = 15 * 10 = 150, but NOT safe
- "symbols": [],
- },
- },
- )
-
- git_meta = {
- "pkg/dead1.py": {
- "commit_count_90d": 0,
- "last_commit_at": _old_date(days=365),
- "age_days": 400,
- },
- "pkg/dead2.py": {
- "commit_count_90d": 0,
- "last_commit_at": _old_date(days=365),
- "age_days": 400,
- },
- # Recently touched -> confidence 0.4, safe_to_delete=False
- "pkg/alive.py": {
- "commit_count_90d": 5,
- "last_commit_at": _now() - timedelta(days=2),
- "age_days": 60,
- },
- }
-
- analyzer = DeadCodeAnalyzer(g, git_meta_map=git_meta)
- report = analyzer.analyze(
- {
- "detect_unused_exports": False,
- "detect_zombie_packages": False,
- "min_confidence": 0.0,
- }
- )
-
- safe_findings = [f for f in report.findings if f.safe_to_delete]
- expected_lines = sum(f.lines for f in safe_findings)
- assert report.deletable_lines == expected_lines
- # Verify that the safe findings include the two stale files
- safe_paths = {f.file_path for f in safe_findings}
- assert "pkg/dead1.py" in safe_paths
- assert "pkg/dead2.py" in safe_paths
- assert "pkg/alive.py" not in safe_paths
- # Verify the actual sum
- assert report.deletable_lines == 100 + 200
-
-
-# ---------------------------------------------------------------------------
-# 13. test_dynamic_edge_clamps_unreachable_confidence
-# ---------------------------------------------------------------------------
-
-
-def test_dynamic_edge_clamps_unreachable_confidence():
- """A file in a package that has dynamic graph edges should have confidence clamped to 0.4."""
- g = _build_graph(
- nodes={
- "pkg/orphan.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 5,
- "symbols": [],
- },
- "pkg/dispatcher.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 3,
- "symbols": [],
- },
- "pkg/handler.py": {
- "is_entry_point": True,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 3,
- "symbols": [],
- },
- },
- edges=[
- ("pkg/dispatcher.py", "pkg/handler.py", {"edge_type": "dynamic"}),
- ],
- )
-
- git_meta = {
- "pkg/orphan.py": {
- "commit_count_90d": 0,
- "last_commit_at": _old_date(days=400),
- "age_days": 500,
- },
- }
-
- analyzer = DeadCodeAnalyzer(g, git_meta_map=git_meta)
- report = analyzer.analyze(
- {
- "detect_unused_exports": False,
- "detect_zombie_packages": False,
- "min_confidence": 0.0,
- }
- )
-
- findings = [f for f in report.findings if f.file_path == "pkg/orphan.py"]
- assert len(findings) == 1
- assert findings[0].confidence == pytest.approx(0.4)
- assert any("dynamic" in e.lower() for e in findings[0].evidence)
-
-
-# ---------------------------------------------------------------------------
-# 14. test_find_dynamic_edge_files_handles_subtypes
-# ---------------------------------------------------------------------------
-
-
-def test_find_dynamic_edge_files_handles_subtypes():
- """find_dynamic_edge_files picks up edges with dynamic_* sub-type prefixes."""
- from repowise.core.analysis.dead_code.dynamic_markers import find_dynamic_edge_files
-
- g = nx.DiGraph()
- g.add_node("a.py")
- g.add_node("b.py")
- g.add_node("c.py")
- g.add_node("d.py")
- g.add_node("external:something")
- g.add_edge("a.py", "b.py", edge_type="dynamic_uses")
- g.add_edge("c.py", "d.py", edge_type="dynamic_imports")
- g.add_edge("a.py", "external:something", edge_type="dynamic")
- # Non-dynamic edges should not contribute
- g.add_edge("b.py", "c.py", edge_type="calls")
-
- files = find_dynamic_edge_files(g)
- assert {"a.py", "b.py", "c.py", "d.py"} <= files
- assert "external:something" not in files
-
-
-# ---------------------------------------------------------------------------
-# 15. test_dynamic_markers_per_language_coverage
-# ---------------------------------------------------------------------------
-
-
- "suffix,expected_markers",
- [
- (".go", ("plugin.Open(", "reflect.New(", "reflect.TypeOf(", "reflect.ValueOf(")),
- (
- ".rb",
- ("autoload ", "const_get(", "Object.send(", "Kernel.const_get(", ".public_send("),
- ),
- (
- ".php",
- (
- "class_exists(",
- "call_user_func(",
- "call_user_func_array(",
- "new $",
- "ReflectionClass(",
- ),
- ),
- (
- ".kt",
- ("Class.forName(", "ServiceLoader.load(", "KClass.createInstance(", "::class.java"),
- ),
- (
- ".swift",
- ("NSClassFromString(", "Selector(", "#selector(", "NSStringFromClass("),
- ),
- (".scala", ("Class.forName(", "runtimeMirror(", "reflect.runtime")),
- ],
-)
-def test_dynamic_markers_per_language_coverage(suffix, expected_markers):
- """Each language's marker tuple must contain the documented Phase 2 entries."""
- from repowise.core.analysis.dead_code.dynamic_markers import _DYNAMIC_IMPORT_MARKERS
-
- markers = _DYNAMIC_IMPORT_MARKERS.get(suffix, ())
- for expected in expected_markers:
- assert expected in markers, f"missing marker {expected!r} for {suffix}"
-
-
-# ---------------------------------------------------------------------------
-# 16. test_unused_internal_default_on
-# ---------------------------------------------------------------------------
-
-
-def test_unused_internal_default_on():
- """detect_unused_internals defaults to True; private symbols with no callers are flagged."""
- g = _build_graph(
- nodes={
- "pkg/utils.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 1,
- "symbols": [
- {
- "name": "_helper",
- "kind": "function",
- "visibility": "private",
- "decorators": [],
- "start_line": 1,
- "end_line": 12,
- "complexity_estimate": 1,
- },
- ],
- },
- },
- )
-
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {
- "detect_unreachable_files": False,
- "detect_unused_exports": False,
- "detect_zombie_packages": False,
- "min_confidence": 0.0,
- }
- )
-
- internals = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL]
- assert any(f.symbol_name == "_helper" for f in internals)
- assert all(f.safe_to_delete is False for f in internals)
-
-
-# ---------------------------------------------------------------------------
-# 17. test_unused_internal_explicit_opt_out
-# ---------------------------------------------------------------------------
-
-
-def test_unused_internal_explicit_opt_out():
- """Setting detect_unused_internals=False disables the detector."""
- g = _build_graph(
- nodes={
- "pkg/utils.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 1,
- "symbols": [
- {
- "name": "_helper",
- "kind": "function",
- "visibility": "private",
- "decorators": [],
- "start_line": 1,
- "end_line": 12,
- "complexity_estimate": 1,
- },
- ],
- },
- },
- )
-
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {
- "detect_unreachable_files": False,
- "detect_unused_exports": False,
- "detect_zombie_packages": False,
- "detect_unused_internals": False,
- "min_confidence": 0.0,
- }
- )
-
- internals = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL]
- assert internals == []
-
-
-# ---------------------------------------------------------------------------
-# D3. Alembic migration scripts are never flagged
-# ---------------------------------------------------------------------------
-
-
-def test_alembic_versions_never_flagged_as_unreachable():
- """Files under <root>/alembic/versions/*.py are loaded reflectively by
- Alembic at runtime — they have no static importer and must not be
- surfaced as unreachable on any Alembic-using repo (generic Python
- convention)."""
- g = _build_graph(
- nodes={
- "myapp/alembic/versions/0001_init.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 2,
- "symbols": [],
- },
- "myapp/alembic/versions/0002_add_users.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 2,
- "symbols": [],
- },
- },
- edges=[],
- )
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {"detect_unused_exports": False, "detect_zombie_packages": False}
- )
- paths = {f.file_path for f in report.findings}
- assert "myapp/alembic/versions/0001_init.py" not in paths
- assert "myapp/alembic/versions/0002_add_users.py" not in paths
-
-
-def test_alembic_upgrade_downgrade_never_flagged_as_unused():
- """``upgrade()`` / ``downgrade()`` in Alembic migration scripts are
- called via reflection by the Alembic runner — the file pattern
- exemption (``*/alembic/versions/*.py``) already covers them, so the
- symbols inside must not surface as unused exports either."""
- g = _build_graph(
- nodes={
- "myapp/alembic/versions/0001_init.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 2,
- "symbols": [
- {
- "name": "upgrade",
- "kind": "function",
- "visibility": "public",
- "decorators": [],
- "start_line": 1, "end_line": 5,
- "complexity_estimate": 1,
- },
- {
- "name": "downgrade",
- "kind": "function",
- "visibility": "public",
- "decorators": [],
- "start_line": 7, "end_line": 11,
- "complexity_estimate": 1,
- },
- ],
- },
- },
- edges=[],
- )
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {"detect_unreachable_files": False, "detect_zombie_packages": False}
- )
- names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
- assert "upgrade" not in names
- assert "downgrade" not in names
-
-
-# ---------------------------------------------------------------------------
-# D4. Click @<group>.command(...) decorator suffix detection
-# ---------------------------------------------------------------------------
-
-
-def test_click_group_command_decorator_excluded():
- """Subcommands registered on a locally-named Click ``Group`` are
- decorated as e.g. ``@my_cli.command("add")``. The receiver name is
- project-local, so the matcher needs to recognise the ``.command``
- suffix rather than a hard-coded ``click.command`` prefix. Same shape
- covers Typer (``.command``/``.callback``) and any user-named
- dispatcher."""
- g = _build_graph(
- nodes={
- "pkg/cli.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 3,
- "symbols": [
- {
- "name": "decision_add",
- "kind": "function",
- "visibility": "public",
- "decorators": ["decision_group.command"],
- "start_line": 1, "end_line": 10,
- "complexity_estimate": 1,
- },
- {
- "name": "decision_list",
- "kind": "function",
- "visibility": "public",
- # Real-world capture sometimes includes the call
- # arguments — the matcher must strip them.
- "decorators": ['my_cli.group("decision")'],
- "start_line": 12, "end_line": 20,
- "complexity_estimate": 1,
- },
- {
- "name": "after_cmd",
- "kind": "function",
- "visibility": "public",
- "decorators": ["app.callback"],
- "start_line": 22, "end_line": 28,
- "complexity_estimate": 1,
- },
- ],
- },
- },
- edges=[],
- )
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {"detect_unreachable_files": False, "detect_zombie_packages": False}
- )
- names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
- assert "decision_add" not in names
- assert "decision_list" not in names
- assert "after_cmd" not in names
-
-
-def test_unrelated_dot_command_function_still_flagged():
- """A decorator suffix-match must not accidentally whitelist symbols
- with unrelated decorators. ``@functools.lru_cache`` does not end with
- ``.command/.group/.callback``, so a plain unused public helper with
- that decorator is still surfaced."""
- g = _build_graph(
- nodes={
- "pkg/helpers.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 1,
- "symbols": [
- {
- "name": "expensive_lookup",
- "kind": "function",
- "visibility": "public",
- "decorators": ["functools.lru_cache"],
- "start_line": 1, "end_line": 20,
- "complexity_estimate": 1,
- },
- ],
- },
- },
- edges=[],
- )
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {"detect_unreachable_files": False, "detect_zombie_packages": False}
- )
- names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
- assert "expensive_lookup" in names
-
-
-# ---------------------------------------------------------------------------
-# D7. unused_internal: imports-by-name into the symbol's file means used
-# ---------------------------------------------------------------------------
-
-
-def test_unused_internal_skipped_when_imported_by_name():
- """A private helper imported by name into a sibling module (typical
- dispatch-table pattern: ``HANDLERS = {"python": _extract_py, ...}``)
- is reached at runtime via dict lookup — no direct ``calls`` edge
- will exist, but the ``imports`` edge carries the symbol name. Such
- helpers must not be flagged as unused internals."""
- g = _build_graph(
- nodes={
- "pkg/python_handler.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 1,
- "symbols": [
- {
- "name": "_extract_python",
- "kind": "function",
- "visibility": "private",
- "decorators": [],
- "start_line": 1, "end_line": 15,
- "complexity_estimate": 1,
- },
- ],
- },
- "pkg/dispatch.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 0,
- "symbols": [],
- },
- },
- edges=[
- (
- "pkg/dispatch.py",
- "pkg/python_handler.py",
- {"edge_type": "imports", "imported_names": ["_extract_python"]},
- ),
- ],
- )
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {
- "detect_unreachable_files": False,
- "detect_unused_exports": False,
- "detect_zombie_packages": False,
- "min_confidence": 0.0,
- }
- )
- names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL}
- assert "_extract_python" not in names
-
-
-def test_unused_export_skipped_when_file_imported_as_namespace():
- """A public symbol in a file that is imported by its module name
- (``from . import cargo``) is a dispatch-table candidate — the
- importer holds a binding to the module and can call any public
- attribute via ``cargo.<attr>(...)``. We cannot tell statically
- which attribute is used, so every public symbol in the file must
- be treated as live."""
- g = _build_graph(
- nodes={
- "pkg/external_systems/cargo.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 1,
- "symbols": [
- {
- "name": "parse",
- "kind": "function",
- "visibility": "public",
- "decorators": [],
- "start_line": 1, "end_line": 12,
- "complexity_estimate": 1,
- },
- ],
- },
- "pkg/external_systems/__init__.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 0,
- "symbols": [],
- },
- },
- edges=[
- (
- "pkg/external_systems/__init__.py",
- "pkg/external_systems/cargo.py",
- {"edge_type": "imports", "imported_names": ["cargo"]},
- ),
- ],
- )
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {
- "detect_unreachable_files": False,
- "detect_unused_internals": False,
- "detect_zombie_packages": False,
- "min_confidence": 0.0,
- }
- )
- names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
- assert "parse" not in names
-
-
-def test_unused_export_still_flagged_when_namespace_name_differs():
- """Negative test for the namespace-import rescue: if the importer
- pulls a *different* sibling module, the public symbol's file is
- still effectively orphan and the symbol must be flagged."""
- g = _build_graph(
- nodes={
- "pkg/external_systems/cargo.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 1,
- "symbols": [
- {
- "name": "parse",
- "kind": "function",
- "visibility": "public",
- "decorators": [],
- "start_line": 1, "end_line": 12,
- "complexity_estimate": 1,
- },
- ],
- },
- "pkg/external_systems/__init__.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 0,
- "symbols": [],
- },
- },
- edges=[
- # importer pulled "npm" only — does NOT mention "cargo"
- (
- "pkg/external_systems/__init__.py",
- "pkg/external_systems/cargo.py",
- {"edge_type": "imports", "imported_names": ["npm"]},
- ),
- ],
- )
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {
- "detect_unreachable_files": False,
- "detect_unused_internals": False,
- "detect_zombie_packages": False,
- "min_confidence": 0.0,
- }
- )
- names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
- assert "parse" in names
-
-
-def test_unused_export_not_rescued_for_index_stem():
- """``index.ts`` is the barrel filename in JS/TS package layouts —
- every workspace package's source root has one, and most imports of
- a package land on it. We must not over-rescue every public export
- of every ``index.ts`` just because a downstream importer happens
- to use the literal name ``index``. Same applies to Python
- ``__init__`` (already covered by the global never-flag list)."""
- g = _build_graph(
- nodes={
- "pkg/ui/src/index.ts": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "language": "typescript",
- "symbol_count": 1,
- "symbols": [
- {
- "name": "stranded_export",
- "kind": "function",
- "visibility": "public",
- "language": "typescript",
- "decorators": [],
- "start_line": 1, "end_line": 5,
- "complexity_estimate": 1,
- },
- ],
- },
- "pkg/web/src/page.ts": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "language": "typescript",
- "symbol_count": 0,
- "symbols": [],
- },
- },
- edges=[
- (
- "pkg/web/src/page.ts",
- "pkg/ui/src/index.ts",
- {"edge_type": "imports", "imported_names": ["index"]},
- ),
- ],
- )
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {
- "detect_unreachable_files": False,
- "detect_unused_internals": False,
- "detect_zombie_packages": False,
- "min_confidence": 0.0,
- }
- )
- names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
- assert "stranded_export" in names
-
-
-def test_unused_internal_still_flagged_when_imports_dont_carry_name():
- """Sanity check: an ``imports`` edge that does NOT list the private
- symbol's name (e.g. the importer pulls a different sibling symbol)
- must not rescue the helper from the unused-internal pass."""
- g = _build_graph(
- nodes={
- "pkg/helpers.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 2,
- "symbols": [
- {
- "name": "_unused_helper",
- "kind": "function",
- "visibility": "private",
- "decorators": [],
- "start_line": 1, "end_line": 8,
- "complexity_estimate": 1,
- },
- ],
- },
- "pkg/consumer.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 0,
- "symbols": [],
- },
- },
- edges=[
- (
- "pkg/consumer.py",
- "pkg/helpers.py",
- {"edge_type": "imports", "imported_names": ["something_else"]},
- ),
- ],
- )
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {
- "detect_unreachable_files": False,
- "detect_unused_exports": False,
- "detect_zombie_packages": False,
- "min_confidence": 0.0,
- }
- )
- names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL}
- assert "_unused_helper" in names
-
-
-# ---------------------------------------------------------------------------
-# D10. WSGI / ASGI / app-factory names treated as entry points
-# ---------------------------------------------------------------------------
-
-
- "factory_name",
- [
- "create_app",
- "make_app",
- "application",
- "asgi_app",
- "wsgi_app",
- "get_asgi_application",
- "get_wsgi_application",
- ],
-)
-def test_python_web_factory_not_flagged(factory_name):
- """FastAPI / Flask / Tornado / aiohttp / Django entry symbols are
- loaded by an external server via dotted-path string
- (``module:create_app`` / ``module:application``) — no graph edge
- exists from the launching server. These conventional names must be
- in the entry-point allowlist so the unused-export pass skips them."""
- g = _build_graph(
- nodes={
- "myapp/server.py": {
- "is_entry_point": False,
- "is_test": False,
- "is_api_contract": False,
- "symbol_count": 1,
- "symbols": [
- {
- "name": factory_name,
- "kind": "function",
- "visibility": "public",
- "decorators": [],
- "start_line": 1, "end_line": 20,
- "complexity_estimate": 1,
- },
- ],
- },
- },
- edges=[],
- )
- analyzer = DeadCodeAnalyzer(g, git_meta_map={})
- report = analyzer.analyze(
- {"detect_unreachable_files": False, "detect_zombie_packages": False}
- )
- names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
- assert factory_name not in names