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): four agent-facing audit issues in get_overview, get_why, get_answer, decision extraction (#158)
Raghav Chamadiyadcc22d9ce4cd
diff --git a/packages/core/src/repowise/core/analysis/decision_extractor.py b/packages/core/src/repowise/core/analysis/decision_extractor.pyindex 75809f673..696fe55ae 100644--- a/packages/core/src/repowise/core/analysis/decision_extractor.py+++ b/packages/core/src/repowise/core/analysis/decision_extractor.py@@ -807,6 +807,11 @@ class DecisionExtractor:dirnames[:] = [d for d in dirnamesif d not in _SKIP_DIRS+ # Skip setuptools build metadata: PKG-INFO embeds the README+ # verbatim, so example marker lines in docs become spurious+ # decisions. Same risk for *.dist-info from wheels.+ and not d.endswith(".egg-info")+ and not d.endswith(".dist-info")# Skip nested git repositories — they are separate codebases# and should not contribute decisions to the parent repo.and not (Path(dirpath) / d / ".git").exists()diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.pyindex 21e3e8afa..a2de96d3a 100644--- a/packages/server/src/repowise/server/mcp_server/_helpers.py+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py@@ -23,6 +23,29 @@ from repowise.server.mcp_server import _state_CODE_EXTS = _LANG_REGISTRY.all_code_extensions()+# Words that mark a string as a natural-language question rather than a path.+# Keep this small — false positives here send genuine paths to the NL branch,+# which is harmless (path lookup also runs as a fallback) but slower.+_NL_QUESTION_TOKENS = frozenset(+ {+ "why",+ "how",+ "what",+ "when",+ "where",+ "who",+ "which",+ "should",+ "can",+ "does",+ "do",+ "is",+ "are",+ "was",+ "were",+ }+)+# ---------------------------------------------------------------------------# Repository resolution@@ -62,10 +85,41 @@ async def _get_repo(session: AsyncSession, repo: str | None = None) -> Repositordef _is_path(query: str) -> bool:- """Heuristic: does this string look like a file or module path?"""- if "/" in query:+ """Heuristic: does this string look like a file or module path?++ Natural-language questions take precedence over the slash heuristic+ because phrases like "two-phase plan/apply flow" or "client/server+ boundary" contain a slash without being paths. We treat anything with+ a question mark, that starts with a question word, or that has 4++ whitespace-separated tokens including a question word, as NL.+ """+ stripped = query.strip()+ if not stripped:+ return False++ # Trailing "?" is an unambiguous NL signal.+ if stripped.endswith("?"):+ return False++ tokens = stripped.split()++ # First token is a question word → NL.+ if tokens and tokens[0].lower().rstrip(",.;:") in _NL_QUESTION_TOKENS:+ return False++ # Sentence-shaped input (multiple words including a question word) → NL.+ if len(tokens) >= 4 and any(+ t.lower().rstrip(",.;:") in _NL_QUESTION_TOKENS for t in tokens+ ):+ return False++ # A path can't contain whitespace.+ if any(ch.isspace() for ch in stripped):+ return False++ if "/" in stripped or "\\" in stripped:return True- _, ext = os.path.splitext(query)+ _, ext = os.path.splitext(stripped)return ext in _CODE_EXTSdiff --git a/packages/server/src/repowise/server/mcp_server/tool_answer.py b/packages/server/src/repowise/server/mcp_server/tool_answer.pyindex c99084719..a38e4b6b9 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer.py@@ -286,11 +286,67 @@ docstring, or source body in the excerpts is relevant."""-def _resolve_provider_for_answer():+def _load_repo_provider_config(+ repo_path: Path | None,+) -> tuple[str | None, str | None, dict[str, str]]:+ """Read persisted provider config for a repo.++ `repowise init` writes the chosen provider + model into+ ``.repowise/state.json`` and the corresponding API key into+ ``.repowise/.env``. The MCP server doesn't load that .env at startup,+ so without this helper get_answer can't reach an LLM unless the user+ also exports REPOWISE_PROVIDER / OPENAI_API_KEY in the shell that+ launched Claude Code. This recovers the persisted values so the same+ provider used for init / update is reused for get_answer.++ Returns ``(provider_name, model, env_overlay)``. Any field may be+ None / empty — callers should fall back to process env when missing.+ """+ if repo_path is None:+ return None, None, {}++ state_path = repo_path / ".repowise" / "state.json"+ env_path = repo_path / ".repowise" / ".env"++ name: str | None = None+ model: str | None = None+ overlay: dict[str, str] = {}++ try:+ if state_path.is_file():+ data = _json.loads(state_path.read_text(encoding="utf-8"))+ name = data.get("provider") or None+ model = data.get("model") or None+ except Exception:+ _log.debug("Failed to read %s", state_path, exc_info=True)++ try:+ if env_path.is_file():+ for raw_line in env_path.read_text(encoding="utf-8").splitlines():+ line = raw_line.strip()+ if not line or line.startswith("#") or "=" not in line:+ continue+ key, _, val = line.partition("=")+ key = key.strip()+ val = val.strip().strip("'").strip('"')+ if key:+ overlay[key] = val+ except Exception:+ _log.debug("Failed to read %s", env_path, exc_info=True)++ return name, model, overlay+++def _resolve_provider_for_answer(repo_path: Path | None = None):"""Best-effort provider lookup mirroring cli/helpers.resolve_provider.Avoids the click dependency from the cli package. Returns a BaseProvideror None if no API key / provider is configured.++ Resolution order: process env vars first, then ``.repowise/state.json``+ + ``.repowise/.env`` for the active repo. The persisted values are the+ same ones ``repowise init`` and ``repowise update`` use, so get_answer+ follows the user's existing provider choice without a separate config."""try:from repowise.core.providers.llm.registry import get_provider@@ -298,8 +354,21 @@ def _resolve_provider_for_answer():_log.debug("Provider registry import failed", exc_info=True)return None- name = os.environ.get("REPOWISE_PROVIDER")- model = os.environ.get("REPOWISE_DOC_MODEL") or os.environ.get("REPOWISE_MODEL")+ persisted_name, persisted_model, env_overlay = _load_repo_provider_config(+ repo_path+ )++ def _env(key: str) -> str | None:+ # Prefer real process env so an explicit shell export still wins;+ # fall back to .repowise/.env only when the process env is empty.+ return os.environ.get(key) or env_overlay.get(key) or None++ name = os.environ.get("REPOWISE_PROVIDER") or persisted_name+ model = (+ os.environ.get("REPOWISE_DOC_MODEL")+ or os.environ.get("REPOWISE_MODEL")+ or persisted_model+ )def _try(provider_name: str, **kwargs: Any):try:@@ -317,7 +386,7 @@ def _resolve_provider_for_answer():"litellm": ["LITELLM_BASE_URL", "LITELLM_API_BASE"],}for env_var in mapping.get(provider_name, []):- val = os.environ.get(env_var)+ val = _env(env_var)if val:return valreturn None@@ -327,51 +396,46 @@ def _resolve_provider_for_answer():kw: dict[str, Any] = {}if model:kw["model"] = model- if name == "anthropic" and os.environ.get("ANTHROPIC_API_KEY"):- kw["api_key"] = os.environ["ANTHROPIC_API_KEY"]- elif name == "openai" and os.environ.get("OPENAI_API_KEY"):- kw["api_key"] = os.environ["OPENAI_API_KEY"]+ if name == "anthropic" and _env("ANTHROPIC_API_KEY"):+ kw["api_key"] = _env("ANTHROPIC_API_KEY")+ elif name == "openai" and _env("OPENAI_API_KEY"):+ kw["api_key"] = _env("OPENAI_API_KEY")elif name == "gemini" and (- os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")+ _env("GEMINI_API_KEY") or _env("GOOGLE_API_KEY")):- kw["api_key"] = os.environ.get("GEMINI_API_KEY") or os.environ.get(- "GOOGLE_API_KEY"- )+ kw["api_key"] = _env("GEMINI_API_KEY") or _env("GOOGLE_API_KEY")base_url = _resolve_base_url(name)if base_url:kw["base_url"] = base_urlreturn _try(name, **kw)# Auto-detect from API keys.- if os.environ.get("ANTHROPIC_API_KEY"):- kw = {"api_key": os.environ["ANTHROPIC_API_KEY"]}+ if _env("ANTHROPIC_API_KEY"):+ kw = {"api_key": _env("ANTHROPIC_API_KEY")}if model:kw["model"] = modelbase_url = _resolve_base_url("anthropic")if base_url:kw["base_url"] = base_urlreturn _try("anthropic", **kw)- if os.environ.get("OPENAI_API_KEY"):- kw = {"api_key": os.environ["OPENAI_API_KEY"]}+ if _env("OPENAI_API_KEY"):+ kw = {"api_key": _env("OPENAI_API_KEY")}if model:kw["model"] = modelbase_url = _resolve_base_url("openai")if base_url:kw["base_url"] = base_urlreturn _try("openai", **kw)- if os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY"):- kw = {- "api_key": os.environ.get("GEMINI_API_KEY")- or os.environ.get("GOOGLE_API_KEY")- }+ if _env("GEMINI_API_KEY") or _env("GOOGLE_API_KEY"):+ kw = {"api_key": _env("GEMINI_API_KEY") or _env("GOOGLE_API_KEY")}if model:kw["model"] = modelbase_url = _resolve_base_url("gemini")if base_url:kw["base_url"] = base_urlreturn _try("gemini", **kw)- if os.environ.get("OLLAMA_BASE_URL"):- kw = {"base_url": os.environ["OLLAMA_BASE_URL"]}+ if _env("OLLAMA_BASE_URL"):+ kw = {"base_url": _env("OLLAMA_BASE_URL")}if model:kw["model"] = modelreturn _try("ollama", **kw)@@ -921,7 +985,7 @@ async def get_answer(# own reasoning loop.# --- Synthesis (LLM) ---------------------------------------------------- provider = _resolve_provider_for_answer()+ provider = _resolve_provider_for_answer(getattr(ctx, "path", None))if provider is None:# Retrieval-only mode (no provider). Return the hits so the agent can# at least skip the search_codebase step.diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview.py b/packages/server/src/repowise/server/mcp_server/tool_overview.pyindex 9af827c3d..5b3c73aaf 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py@@ -42,14 +42,20 @@ async def _workspace_overview() -> dict:async with get_session(ctx.session_factory) as session:repo_obj = await _get_repo(session)- # One-line summary from repo_overview page+ # One-line summary from repo_overview page. Same multi-row+ # safety as the single-repo path below.ov_result = await session.execute(- select(Page.content).where(+ select(Page.content)+ .where(Page.repository_id == repo_obj.id,Page.page_type == "repo_overview",)+ .order_by(+ (Page.target_path == repo_obj.name).desc(),+ Page.updated_at.desc(),+ ))- ov_content = ov_result.scalar_one_or_none() or ""+ ov_content = ov_result.scalars().first() or ""summary = ov_content.split("\n")[0].strip("# ").strip()[:200] if ov_content else ""# File and symbol counts@@ -182,14 +188,24 @@ async def get_overview(repo: str | None = None) -> dict:async with get_session(ctx.session_factory) as session:repository = await _get_repo(session)- # Get repo overview page+ # Get repo overview page. Older indexes occasionally left a stale+ # row with target_path='repo' alongside the canonical+ # target_path=<repo_name> row, so prefer the row matching the repo+ # name and fall back to the most recently updated one. Using+ # scalar_one_or_none here would crash with MultipleResultsFound on+ # those legacy DBs.result = await session.execute(- select(Page).where(+ select(Page)+ .where(Page.repository_id == repository.id,Page.page_type == "repo_overview",)+ .order_by(+ (Page.target_path == repository.name).desc(),+ Page.updated_at.desc(),+ ))- overview_page = result.scalar_one_or_none()+ overview_page = result.scalars().first()# Get module pagesresult = await session.execute(