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(server): resolve workspace repos in chat tool calls (#971)
Raghav Chamadiyad4bc9c8e7e99
diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.pyindex f2ce0d196..d01209d6e 100644--- a/packages/server/src/repowise/server/app.py+++ b/packages/server/src/repowise/server/app.py@@ -219,7 +219,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:app.state.scheduler = scheduler# Initialize chat tool state (bridges FastAPI state to MCP tool globals)- from repowise.server.chat_tools import init_tool_state+ from repowise.server.chat_tools import init_tool_state, set_tool_workspaceinit_tool_state(session_factory=session_factory,@@ -231,6 +231,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:app.state.workspace_config = Noneapp.state.workspace_root = Noneapp.state.cross_repo_enricher = None+ app.state.repo_registry = None # RepoRegistry, workspace mode onlyapp.state.workspace_sessions = {} # repo_id → session_factoryapp.state.workspace_engines = [] # engines to dispose on shutdown# Per-repo FTS instances keyed by repo_id, used by the search router@@ -313,6 +314,27 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:extra={"count": len(app.state.workspace_sessions)},)+ # Give the MCP tool functions a RepoRegistry, the same one the+ # stdio MCP lifespan builds (_server.py). Without it every chat+ # tool call falls into the single-repo branch of+ # _resolve_repo_context() and dies with "Repository not found:+ # <alias>", because the alias is looked up in the primary repo's+ # wiki.db only (issue #970). Contexts load lazily, so the repo+ # the first chat call names pays the engine/FTS open cost inline.+ # The registry holds its own handles on each repo's wiki.db,+ # separate from app.state.workspace_sessions above; collapsing+ # the two onto one set of connections is worth doing but is a+ # bigger change than this fix.+ from repowise.core.workspace.registry import RepoRegistry++ repo_registry = RepoRegistry(+ workspace_root=_Path(ws_root),+ ws_config=ws_config,+ embedder_factory=_build_embedder,+ )+ app.state.repo_registry = repo_registry+ set_tool_workspace(registry=repo_registry, workspace_root=str(ws_root))+# Reset stale jobs in non-primary workspace DBs too. The primary# DB was handled before workspace detection, but each secondary# repo has its own generation_jobs table and stale running rows@@ -347,6 +369,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:)if enricher.has_data or enricher.has_contract_data or enricher.has_system_graph:app.state.cross_repo_enricher = enricher+ set_tool_workspace(cross_repo_enricher=enricher)logger.info("repowise_workspace_detected",extra={@@ -379,24 +402,35 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:logger.debug("repo_db_rediscovery_skipped", exc_info=True)logger.info("repowise_server_started", extra={"version": __version__})- yield-- # Shutdown- scheduler.shutdown(wait=False)- await vector_store.close()- # Close cached per-repo vector stores (LanceDB connections).try:- from repowise.server.search_helpers import close_workspace_vector_stores-- await close_workspace_vector_stores(app)- except Exception:- logger.debug("workspace_vector_store_close_failed", exc_info=True)- # Dispose workspace repo engines first- for ws_engine in getattr(app.state, "workspace_engines", []):+ yield+ finally:+ # Shutdown. The finally matters for the workspace globals below: they+ # outlive the app object, so skipping this on a shutdown exception+ # would leave the tool layer pointing at disposed engines.+ scheduler.shutdown(wait=False)with suppress(Exception):- await ws_engine.dispose()- await engine.dispose()- logger.info("repowise_server_stopped")+ await vector_store.close()+ # Close cached per-repo vector stores (LanceDB connections).+ try:+ from repowise.server.search_helpers import close_workspace_vector_stores++ await close_workspace_vector_stores(app)+ except Exception:+ logger.debug("workspace_vector_store_close_failed", exc_info=True)+ # Release the per-repo contexts the chat tools resolved through+ _repo_registry = getattr(app.state, "repo_registry", None)+ if _repo_registry is not None:+ with suppress(Exception):+ await _repo_registry.close()+ # The enricher is only ever published alongside the registry.+ set_tool_workspace(registry=None, workspace_root=None, cross_repo_enricher=None)+ # Dispose workspace repo engines first+ for ws_engine in getattr(app.state, "workspace_engines", []):+ with suppress(Exception):+ await ws_engine.dispose()+ await engine.dispose()+ logger.info("repowise_server_stopped")def create_app() -> FastAPI:diff --git a/packages/server/src/repowise/server/chat_tools.py b/packages/server/src/repowise/server/chat_tools.pyindex 8a7b92732..45b063eab 100644--- a/packages/server/src/repowise/server/chat_tools.py+++ b/packages/server/src/repowise/server/chat_tools.py@@ -304,14 +304,45 @@ def _make_json_serializable(obj: Any) -> Any:return str(obj)-async def execute_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:- """Execute a tool by name and return JSON-serializable result."""+def _scope_repo_arg(tool_def: ToolDef, arguments: dict[str, Any], repo: str | None) -> None:+ """Point a tool call at the repo the chat page is on.++ The model only sees the repo *name* in the system prompt, so left to+ itself it passes a string that may not be a workspace alias at all. We+ keep its value when it names a real repo (so "compare with gateway"+ still works) and otherwise substitute the caller's alias.+ """+ if not repo or "repo" not in tool_def.parameters.get("properties", {}):+ return++ import repowise.server.mcp_server as mcp_mod++ workspace = mcp_mod._registry+ if workspace is None:+ return++ requested = arguments.get("repo")+ if requested == "all" or requested in workspace.get_all_aliases():+ return+ arguments["repo"] = repo+++async def execute_tool(+ name: str, arguments: dict[str, Any], repo: str | None = None+) -> dict[str, Any]:+ """Execute a tool by name and return JSON-serializable result.++ ``repo`` is the alias of the repo the request is scoped to (workspace+ mode). It backstops the ``repo`` argument the model supplies.+ """registry = get_tool_registry()tool_def = registry.get(name)if not tool_def:return {"error": f"Unknown tool: {name}"}try:+ arguments = dict(arguments)+ _scope_repo_arg(tool_def, arguments, repo)result = await tool_def.function(**arguments)return _make_json_serializable(result)except Exception as exc:@@ -348,3 +379,27 @@ def init_tool_state(if repo_path is not None:mcp_mod._repo_path = repo_pathlogger.info("Chat tool state initialized")+++_UNSET = object()+++def set_tool_workspace(+ registry: Any = _UNSET,+ workspace_root: Any = _UNSET,+ cross_repo_enricher: Any = _UNSET,+) -> None:+ """Publish workspace state to the MCP tool globals.++ The stdio MCP server sets these in its own lifespan; the HTTP server has+ to do the same or the tools resolve every alias against the primary+ repo's database alone (issue #970). Arguments left out are untouched.+ """+ import repowise.server.mcp_server as mcp_mod++ if registry is not _UNSET:+ mcp_mod._registry = registry+ if workspace_root is not _UNSET:+ mcp_mod._workspace_root = workspace_root+ if cross_repo_enricher is not _UNSET:+ mcp_mod._cross_repo_enricher = cross_repo_enricherdiff --git a/packages/server/src/repowise/server/routers/chat.py b/packages/server/src/repowise/server/routers/chat.pyindex 964791608..3404df9a8 100644--- a/packages/server/src/repowise/server/routers/chat.py+++ b/packages/server/src/repowise/server/routers/chat.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport jsonimport logging+from pathlib import Pathfrom typing import Anyfrom fastapi import APIRouter, Depends, HTTPException, Request@@ -71,6 +72,34 @@ async def _get_repo_info(factory: Any, repo_id: str) -> tuple[str, str]:# ---------------------------------------------------------------------------+def _workspace_alias(request: Request, repo_path: str, repo_name: str) -> str | None:+ """Return the workspace alias owning *repo_path*, or None outside a workspace.++ ``local_path`` is stored verbatim at index time, so it can be relative+ (``repowise init .`` records ``"."``) and resolve against the server's+ cwd rather than the repo. The name fallback covers that; a miss only+ costs us the repo scoping, so it is logged rather than raised.+ """+ ws_config = getattr(request.app.state, "workspace_config", None)+ ws_root = getattr(request.app.state, "workspace_root", None)+ if ws_config is None or ws_root is None:+ return None++ resolved = Path(repo_path).resolve()+ for entry in ws_config.repos:+ if (Path(ws_root) / entry.path).resolve() == resolved:+ return entry.alias+ for entry in ws_config.repos:+ if entry.alias == repo_name:+ return entry.alias++ logger.warning(+ "chat_workspace_alias_unresolved",+ extra={"repo_path": repo_path, "repo_name": repo_name},+ )+ return None++@router.post("/api/repos/{repo_id}/chat/messages")async def chat_messages(repo_id: str, body: ChatRequest, request: Request):"""Stream an agentic chat response via SSE."""@@ -83,6 +112,9 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):# Resolve reporepo_name, repo_path = await _get_repo_info(factory, repo_id)+ # In workspace mode the MCP tools address repos by alias, not by the id+ # in this URL, so resolve it once and scope every tool call to it.+ repo_alias = _workspace_alias(request, repo_path, repo_name)# Resolve provider. A per-request override (the UI model picker) applies to# THIS request only and is not persisted — an explicit selection is@@ -151,7 +183,7 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):# Tool executor callback — used by providers that run the# agentic loop internally (e.g. Gemini for thought_signature).async def _tool_executor(name: str, args: dict) -> dict:- return await execute_tool(name, args)+ return await execute_tool(name, args, repo=repo_alias)# Agentic loopassistant_text_parts: list[str] = []@@ -271,7 +303,7 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):# Execute each tool and add resultsfor tc in pending_tool_calls:- result = await execute_tool(tc["name"], tc["arguments"])+ result = await execute_tool(tc["name"], tc["arguments"], repo=repo_alias)artifact_type = get_artifact_type(tc["name"])# Build summary from resultdiff --git a/tests/unit/server/test_app_workspace_registry.py b/tests/unit/server/test_app_workspace_registry.pynew file mode 100644index 000000000..ce694101e--- /dev/null+++ b/tests/unit/server/test_app_workspace_registry.py@@ -0,0 +1,113 @@+"""Regression test for issue #970 — ``repowise serve`` over a workspace.++The HTTP lifespan used to leave ``_state._registry`` unset, so chat tool+calls resolved aliases against the primary repo's database only and blew up+with ``LookupError: Repository not found: <alias>`` for every repo.+"""++from __future__ import annotations++from datetime import UTC, datetime+from pathlib import Path++import pytest+from fastapi import FastAPI+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine++import repowise.server.mcp_server as mcp_mod+from repowise.core.persistence.database import init_db+from repowise.core.persistence.models import Repository+from repowise.server.app import lifespan++_NOW = datetime(2026, 7, 21, 10, 0, 0, tzinfo=UTC)+++async def _make_repo(root: Path, alias: str) -> None:+ """Create ``<root>/<alias>/.repowise/wiki.db`` with one repository row."""+ repo_path = root / alias+ (repo_path / ".repowise").mkdir(parents=True)+ db = repo_path / ".repowise" / "wiki.db"+ engine = create_async_engine(f"sqlite+aiosqlite:///{db.as_posix()}")+ await init_db(engine)+ factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)+ async with factory() as session:+ session.add(+ Repository(+ id=f"{alias}-id",+ name=alias,+ url=f"https://example.com/{alias}",+ local_path=str(repo_path),+ default_branch="main",+ settings_json="{}",+ created_at=_NOW,+ updated_at=_NOW,+ )+ )+ await session.commit()+ await engine.dispose()++[email protected](autouse=True)+def restore_tool_globals():+ """The real lifespan writes process-global MCP tool state — put it back."""+ saved = (+ mcp_mod._registry,+ mcp_mod._workspace_root,+ mcp_mod._cross_repo_enricher,+ mcp_mod._session_factory,+ mcp_mod._fts,+ mcp_mod._vector_store,+ )+ yield+ (+ mcp_mod._registry,+ mcp_mod._workspace_root,+ mcp_mod._cross_repo_enricher,+ mcp_mod._session_factory,+ mcp_mod._fts,+ mcp_mod._vector_store,+ ) = saved+++def workspace(tmp_path, monkeypatch):+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)+ monkeypatch.chdir(tmp_path)+ (tmp_path / ".repowise-workspace.yaml").write_text(+ "version: 1\n"+ "default_repo: boot\n"+ "repos:\n"+ "- path: boot\n"+ " alias: boot\n"+ " is_primary: true\n"+ "- path: gateway\n"+ " alias: gateway\n",+ encoding="utf-8",+ )+ return tmp_path+++async def test_lifespan_publishes_the_repo_registry(workspace):+ await _make_repo(workspace, "boot")+ await _make_repo(workspace, "gateway")++ from repowise.server.mcp_server._helpers import _resolve_repo_context++ app = FastAPI()+ async with lifespan(app):+ registry = mcp_mod._registry+ assert registry is not None, "workspace mode never reached the chat tools"+ assert sorted(registry.get_all_aliases()) == ["boot", "gateway"]+ assert mcp_mod._workspace_root == str(workspace)++ # Both repos resolve — the non-primary one is the case that used to+ # raise LookupError no matter what.+ for alias in ("boot", "gateway"):+ ctx = await _resolve_repo_context(alias)+ assert ctx.alias == alias++ # Shutdown puts the globals back so a later single-repo server is clean.+ assert mcp_mod._registry is None+ assert mcp_mod._workspace_root is Nonediff --git a/tests/unit/server/test_chat_tool_repo_scope.py b/tests/unit/server/test_chat_tool_repo_scope.pynew file mode 100644index 000000000..5bd1219b2--- /dev/null+++ b/tests/unit/server/test_chat_tool_repo_scope.py@@ -0,0 +1,190 @@+"""Regression tests for issue #970 — chat tools in workspace mode.++Two things were broken when the HTTP server (``repowise serve``) ran over a+workspace:++1. Only the stdio MCP lifespan published a ``RepoRegistry`` to the tool+ globals, so every chat tool call took the single-repo branch of+ ``_resolve_repo_context`` and raised ``LookupError: Repository not+ found: <alias>``. ``set_tool_workspace`` now lets the HTTP lifespan+ publish the same state.+2. Nothing told the tools which repo the chat page was on, so the model's+ guess at the ``repo`` argument was the only input.+"""++from __future__ import annotations++from types import SimpleNamespace+from typing import Any++import pytest++import repowise.server.mcp_server as mcp_mod+from repowise.server import chat_tools+from repowise.server.routers import chat+++class _FakeRegistry:+ def __init__(self, aliases: list[str]) -> None:+ self._aliases = aliases++ def get_all_aliases(self) -> list[str]:+ return list(self._aliases)+++def workspace_registry():+ """Publish a fake workspace registry, restoring the globals afterwards."""+ previous = mcp_mod._registry+ chat_tools.set_tool_workspace(registry=_FakeRegistry(["boot", "gateway"]))+ yield+ chat_tools.set_tool_workspace(registry=previous)+++def captured_call(monkeypatch):+ """Replace get_overview with a recorder and return the recorded kwargs."""+ seen: dict[str, Any] = {}++ async def _fake_get_overview(**kwargs):+ seen.update(kwargs)+ return {"ok": True}++ tool_def = chat_tools.get_tool_registry()["get_overview"]+ monkeypatch.setattr(tool_def, "function", _fake_get_overview)+ return seen+++async def test_missing_repo_arg_is_filled_from_the_request(workspace_registry, captured_call):+ result = await chat_tools.execute_tool("get_overview", {}, repo="gateway")++ assert "error" not in result+ assert captured_call["repo"] == "gateway"+++async def test_unknown_repo_arg_is_replaced_by_the_request_repo(workspace_registry, captured_call):+ # The model only sees the repo *name* in the system prompt, so it can+ # produce a string that is not an alias at all.+ await chat_tools.execute_tool("get_overview", {"repo": "hpaddle-boot"}, repo="boot")++ assert captured_call["repo"] == "boot"+++async def test_valid_alias_from_the_model_is_kept(workspace_registry, captured_call):+ """Cross-repo questions must still be answerable from either page."""+ await chat_tools.execute_tool("get_overview", {"repo": "gateway"}, repo="boot")++ assert captured_call["repo"] == "gateway"+++async def test_repo_all_is_kept(workspace_registry, captured_call):+ await chat_tools.execute_tool("get_overview", {"repo": "all"}, repo="boot")++ assert captured_call["repo"] == "all"+++async def test_single_repo_mode_arguments_are_untouched(captured_call):+ """No registry means no aliases — leave the call exactly as the model made it."""+ previous = mcp_mod._registry+ chat_tools.set_tool_workspace(registry=None)+ try:+ await chat_tools.execute_tool("get_overview", {"repo": "whatever"}, repo="boot")+ finally:+ chat_tools.set_tool_workspace(registry=previous)++ assert captured_call["repo"] == "whatever"+++async def test_callers_arguments_are_not_mutated(workspace_registry, captured_call):+ arguments: dict[str, Any] = {"repo": "hpaddle-boot"}+ await chat_tools.execute_tool("get_overview", arguments, repo="boot")++ assert arguments == {"repo": "hpaddle-boot"}+++class _Entry:+ def __init__(self, path: str, alias: str) -> None:+ self.path = path+ self.alias = alias+++class _WsConfig:+ def __init__(self, repos: list[_Entry]) -> None:+ self.repos = repos+++def _request_with_workspace(ws_root, repos):+ app = SimpleNamespace(+ state=SimpleNamespace(+ workspace_config=_WsConfig(repos),+ workspace_root=str(ws_root),+ )+ )+ return SimpleNamespace(app=app)+++def test_workspace_alias_matches_on_path(tmp_path):+ request = _request_with_workspace(tmp_path, [_Entry("boot", "boot"), _Entry("gw", "gateway")])++ alias = chat._workspace_alias(request, str(tmp_path / "gw"), "gateway")++ assert alias == "gateway"+++def test_workspace_alias_falls_back_to_the_repo_name(tmp_path, monkeypatch):+ """`repowise init .` stores local_path as ".", which resolves to the cwd."""+ request = _request_with_workspace(tmp_path, [_Entry("boot", "boot")])+ monkeypatch.chdir(tmp_path)++ assert chat._workspace_alias(request, ".", "boot") == "boot"+++def test_workspace_alias_is_none_outside_a_workspace(tmp_path):+ request = SimpleNamespace(+ app=SimpleNamespace(state=SimpleNamespace(workspace_config=None, workspace_root=None))+ )++ assert chat._workspace_alias(request, str(tmp_path), "boot") is None+++def test_workspace_alias_is_none_when_nothing_matches(tmp_path):+ request = _request_with_workspace(tmp_path, [_Entry("boot", "boot")])++ assert chat._workspace_alias(request, "/elsewhere/other", "other") is None+++def test_set_tool_workspace_publishes_and_clears_state():+ previous = (mcp_mod._registry, mcp_mod._workspace_root, mcp_mod._cross_repo_enricher)+ registry = _FakeRegistry(["boot"])+ enricher = object()+ try:+ chat_tools.set_tool_workspace(+ registry=registry,+ workspace_root="/workspace",+ cross_repo_enricher=enricher,+ )+ assert mcp_mod._registry is registry+ assert mcp_mod._workspace_root == "/workspace"+ assert mcp_mod._cross_repo_enricher is enricher++ # Omitted arguments stay as they are.+ chat_tools.set_tool_workspace(workspace_root="/elsewhere")+ assert mcp_mod._registry is registry+ assert mcp_mod._workspace_root == "/elsewhere"++ chat_tools.set_tool_workspace(registry=None, workspace_root=None, cross_repo_enricher=None)+ assert mcp_mod._registry is None+ assert mcp_mod._workspace_root is None+ assert mcp_mod._cross_repo_enricher is None+ finally:+ (+ mcp_mod._registry,+ mcp_mod._workspace_root,+ mcp_mod._cross_repo_enricher,+ ) = previous