Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(mcp): tell the agent to restart a server whose loaded code predates the checkout (#2844)
Raghav Chamadiyaeb13e88ac4b0
diff --git a/packages/cli/src/repowise/cli/tool_bridge.py b/packages/cli/src/repowise/cli/tool_bridge.pyindex 0cccca5df..f7f7c2e8e 100644--- a/packages/cli/src/repowise/cli/tool_bridge.py+++ b/packages/cli/src/repowise/cli/tool_bridge.py@@ -85,7 +85,7 @@ async def _acall_tool()return _budgeted(tool_name, await factory())except Exception as exc:- return _shape_exception(tool_name, exc)+ return _shape_exception(tool_name, exc, long_running=False)finally:close = getattr(store, "close", None)if close is not None:diff --git a/packages/server/src/repowise/server/mcp_server/_failure_shield.py b/packages/server/src/repowise/server/mcp_server/_failure_shield.pyindex fa85fa789..114ba6fc9 100644--- a/packages/server/src/repowise/server/mcp_server/_failure_shield.py+++ b/packages/server/src/repowise/server/mcp_server/_failure_shield.py@@ -139,6 +139,50 @@ def _shape_stale_index(exc: Exception) -> dict[str, Any]:}+def is_stale_server_import(exc: BaseException) -> bool:+ """True when a lazy import of repowise's own code failed.++ A long-running server keeps the modules it loaded at start. When the+ checkout moves under it, a module imported later comes from the new tree+ and can ask for a name the old in-memory module lacks (``ImportError``),+ or the old code can ask for a module the new tree removed+ (``ModuleNotFoundError``). Both resolve on restart. A third-party import+ failure is a missing dependency instead, so it keeps the generic shape.+ """+ name = getattr(exc, "name", None) or ""+ return isinstance(exc, ImportError) and (name == "repowise" or name.startswith("repowise."))+++def stale_server_notice(exc: BaseException) -> str:+ """Plain explanation and next step for :func:`is_stale_server_import`."""+ return (+ "The MCP server is running older repowise code than this checkout "+ f"({exc}). Restart the MCP server (or the editor session) and retry."+ )+++def _shape_stale_server(exc: Exception) -> dict[str, Any]:+ """Success-shaped response for a server whose loaded code predates the checkout."""+ return {+ "error": stale_server_notice(exc),+ "remedy": (+ "Restarting the MCP server is the user's step: ask them once. "+ "The index itself is fine and needs no rebuild."+ ),+ }+++def _shape_broken_install(exc: Exception) -> dict[str, Any]:+ """The same failure in a process that imported fresh: the install itself is broken."""+ return {+ "error": f"This repowise install is incomplete or mixed ({exc}).",+ "remedy": (+ "Reinstall repowise, or repair the environment it runs from, and "+ "retry. That is the user's step: ask them once."+ ),+ }++def _shape_internal_error(tool: str, exc: Exception) -> dict[str, Any]:"""Success-shaped response for an unexpected internal failure."""return {@@ -151,7 +195,8 @@ def _shape_internal_error(tool: str, exc: Exception) -> dict[str, Any]:}-def _shape_exception(tool: str, exc: Exception) -> dict[str, Any]:+def _shape_exception(tool: str, exc: Exception, *, long_running: bool = True) -> dict[str, Any]:+ """*long_running* is False for a process that imports fresh on every run (the CLI)."""if isinstance(exc, LookupError):if _NOT_INDEXED_MARKER in str(exc):return _shape_not_indexed()@@ -162,6 +207,8 @@ def _shape_exception(tool: str, exc: Exception) -> dict[str, Any]:return _shape_unknown_repo(exc)if _is_stale_index_error(exc):return _shape_stale_index(exc)+ if is_stale_server_import(exc):+ return _shape_stale_server(exc) if long_running else _shape_broken_install(exc)return _shape_internal_error(tool, exc)diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.pyindex 37c76a35b..0a298c573 100644--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py@@ -51,6 +51,10 @@ from repowise.server.mcp_server._change_health import (from repowise.server.mcp_server._change_health import (patch_coverage_action as _patch_coverage_action,)+from repowise.server.mcp_server._failure_shield import (+ is_stale_server_import,+ stale_server_notice,+)from repowise.server.mcp_server._helpers import (_get_repo,_is_workspace_mode,@@ -342,9 +346,14 @@ def _compare_health()except Exception as exc:log.warning("change_health_comparison_failed", revspec=revspec, error=str(exc))+ explanation = (+ stale_server_notice(exc)+ if is_stale_server_import(exc)+ else f"Health comparison failed: {exc}"+ )return ChangeHealthDelta(status="unavailable",- explanation=f"Health comparison failed: {exc}",+ explanation=explanation,base=None,head=None,comparison_basis="not_compared",diff --git a/tests/unit/cli/test_tool_bridge.py b/tests/unit/cli/test_tool_bridge.pyindex 1292ddbbe..a4e1607bd 100644--- a/tests/unit/cli/test_tool_bridge.py+++ b/tests/unit/cli/test_tool_bridge.py@@ -136,6 +136,19 @@ def test_an_unindexed_repo_gets_the_shields_run_init_advice(wired):assert "repowise init" in result["remedy"]+def test_a_failed_repowise_import_points_at_the_install_not_a_server(wired):+ """The CLI imports fresh each run, so no older server is holding stale code."""+ _engine, _store, _published, repo = wired++ async def _tool():+ from repowise.core.ingestion.type_names import name_missing_from_install # noqa: F401++ result = tool_bridge.call_tool(repo, _tool, "get_change_risk")+ assert "install is incomplete" in result["error"]+ assert "Reinstall repowise" in result["remedy"]+ assert "MCP server" not in repr(result)++def test_a_store_that_fails_to_open_still_disposes_the_engine(wired, monkeypatch):"""Building the embedder happens before the tool call and can raise."""engine, _store, _published, repo = wireddiff --git a/tests/unit/server/mcp/test_failure_shield.py b/tests/unit/server/mcp/test_failure_shield.pyindex 85215da0b..269af1964 100644--- a/tests/unit/server/mcp/test_failure_shield.py+++ b/tests/unit/server/mcp/test_failure_shield.py@@ -145,6 +145,52 @@ async def test_the_users_own_question_cannot_fake_a_stale_index():assert "Retry this call once" in result["guidance"]+async def test_a_server_older_than_the_checkout_says_restart_not_give_up():+ """A long-running server's lazy import of a name only the new checkout has.++ The generic shape tells the caller to drop the tool for the session; a+ restart fixes it, so say that instead.+ """++ async def stale_server_tool() -> dict:+ from repowise.core.ingestion.type_names import name_added_after_server_start # noqa: F401++ return {}++ result = await shield(stale_server_tool)()++ assert "older repowise code than this checkout" in result["error"]+ assert "Restart the MCP server" in result["error"]+ assert "user" in result["remedy"]+ assert "guidance" not in result+++async def test_a_removed_repowise_module_is_also_a_stale_server():+ async def stale_server_tool() -> dict:+ import repowise.core.module_removed_from_checkout # noqa: F401++ return {}++ result = await shield(stale_server_tool)()++ assert "Restart the MCP server" in result["error"]+++async def test_a_missing_dependency_keeps_the_internal_error_shape():+ async def missing_dep_tool() -> dict:+ import repowise_no_such_dependency # noqa: F401++ return {}++ result = await shield(missing_dep_tool)()++ assert "ModuleNotFoundError" in result["error"]+ assert "Retry this call once" in result["guidance"]++@pytest.mark.asyncioasync def test_unexpected_exception_is_success_shaped():async def exploding_tool(x: int) -> dict:diff --git a/tests/unit/server/mcp/test_tool_change_risk.py b/tests/unit/server/mcp/test_tool_change_risk.pyindex 1a1db8bf5..e6b1df2d7 100644--- a/tests/unit/server/mcp/test_tool_change_risk.py+++ b/tests/unit/server/mcp/test_tool_change_risk.py@@ -73,6 +73,31 @@ def test_a_failed_health_comparison_degrades_to_unavailable(monkeypatch):assert delta.findings == []+def test_a_server_older_than_the_checkout_says_restart(monkeypatch):+ """A lazy import asking the loaded module for a name only the checkout has."""++ def _stale(_path):+ from repowise.core.ingestion.type_names import name_added_after_server_start # noqa: F401++ monkeypatch.setattr(tool, "_delta_service", _stale)+ delta = tool._compare_health("/repo", "HEAD", (), ())+ assert delta.status == "unavailable"+ assert delta.explanation.startswith("The MCP server is running older repowise code")+ assert "name_added_after_server_start" in delta.explanation+ assert "Restart the MCP server" in delta.explanation+++def test_a_missing_third_party_module_keeps_the_raw_failure(monkeypatch):+ """Not a stale server: restarting would not install a dependency."""++ def _missing(_path):+ import repowise_no_such_dependency # noqa: F401++ monkeypatch.setattr(tool, "_delta_service", _missing)+ delta = tool._compare_health("/repo", "HEAD", (), ())+ assert delta.explanation.startswith("Health comparison failed: No module named")++def _finding(path, biomarker, symbol, start, end):return SimpleNamespace(path=path,