Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(cli): resolve the embedder name through the global config (#2074)

Raghav Chamadiya7d1befd1d917
diff --git a/packages/cli/src/repowise/cli/providers/embedders.py b/packages/cli/src/repowise/cli/providers/embedders.py
index fa1c115c1..a17a2a340 100644
--- a/packages/cli/src/repowise/cli/providers/embedders.py
+++ b/packages/cli/src/repowise/cli/providers/embedders.py
@@ -6,7 +6,11 @@ import os
from collections.abc import Mapping
from typing import Any
-from repowise.cli.providers.keys import embedder_key_env_vars, resolve_embedder_api_key
+from repowise.cli.providers.keys import (
+ embedder_key_env_vars,
+ global_config_embedder,
+ resolve_embedder_api_key,
+)
def _embedder_kwargs(embedder_name: str, repo_path: Any = None) -> dict[str, Any]:
@@ -55,12 +59,16 @@ def resolve_embedding_model(embedder_name: str) -> str | None:
def resolve_embedder(embedder_flag: str | None, env: Mapping[str, str] | None = None) -> str:
- """Auto-detect embedder from env vars, or use the flag value.
+ """Auto-detect the embedder backend, or use the flag value.
*env* layers a repo's persisted ``.repowise/.env`` under the process
environment for callers that must not merge it into ``os.environ``. The
process still wins on every key, so an exported variable keeps overriding
the file, exactly as ``load_dotenv``'s non-overwriting merge did.
+
+ ``~/.repowise/config.yaml``'s ``embedder`` is the last tier, below every
+ environment source and above the keyless fallback. See
+ :func:`~repowise.cli.providers.keys.global_config_embedder`.
"""
if embedder_flag:
return embedder_flag
@@ -81,7 +89,7 @@ def resolve_embedder(embedder_flag: str | None, env: Mapping[str, str] | None =
return "ollama"
if _get("EDENAI_API_KEY"):
return "edenai"
- return "mock"
+ return global_config_embedder() or "mock"
def pin_names_an_embedder(pinned_embedder: Any) -> bool:
diff --git a/packages/cli/src/repowise/cli/providers/keys.py b/packages/cli/src/repowise/cli/providers/keys.py
index ef524ff60..1ff83ec87 100644
--- a/packages/cli/src/repowise/cli/providers/keys.py
+++ b/packages/cli/src/repowise/cli/providers/keys.py
@@ -26,6 +26,11 @@ import os
from pathlib import Path
from typing import Any, NamedTuple
+
+def _global_config_path() -> Path:
+ """Resolved per call, never at import: tests redirect ``Path.home``."""
+ return Path.home() / ".repowise" / "config.yaml"
+
# Mirrors ``mcp_server/_server.py::_EMBEDDER_KEY_ENV``. The two copies are the
# shape this module exists to stop spreading, but the server cannot import the
# CLI and neither can reach a shared home without moving the map into
@@ -103,21 +108,62 @@ def resolve_embedder_api_key(embedder_name: str, repo_path: Any = None) -> KeyLo
if value:
return KeyLookup(value, tuple(searched))
- global_config = Path.home() / ".repowise" / "config.yaml"
- searched.append(f"embedder_api_key in {global_config}")
+ searched.append(f"embedder_api_key in {_global_config_path()}")
+ cfg = _load_global_config()
+ if str(cfg.get("embedder") or "").strip().lower() == embedder_name:
+ key = str(cfg.get("embedder_api_key") or "").strip()
+ if key:
+ return KeyLookup(key, tuple(searched))
+
+ return KeyLookup(None, tuple(searched))
+
+
+def _load_global_config() -> dict[str, Any]:
+ """``~/.repowise/config.yaml`` as a mapping, or empty when it is not one.
+
+ Absent is the normal case, so this is silent. The ``isinstance`` matters:
+ ``safe_load`` returns whatever the document is, so a hand-edited file
+ holding a bare scalar or a list parses fine and then raises ``AttributeError``
+ on ``.get`` -- out through ``resolve_embedder``, which every command calls.
+ """
try:
- if global_config.is_file():
- import yaml # type: ignore[import-untyped]
-
- cfg = yaml.safe_load(global_config.read_text(encoding="utf-8")) or {}
- if str(cfg.get("embedder") or "").strip().lower() == embedder_name:
- key = str(cfg.get("embedder_api_key") or "").strip()
- if key:
- return KeyLookup(key, tuple(searched))
+ path = _global_config_path()
+ if not path.is_file():
+ return {}
+ import yaml # type: ignore[import-untyped]
+
+ cfg = yaml.safe_load(path.read_text(encoding="utf-8"))
except Exception:
- pass
+ return {}
+ return cfg if isinstance(cfg, dict) else {}
- return KeyLookup(None, tuple(searched))
+def global_config_embedder() -> str | None:
+ """The ``embedder`` backend pinned in ``~/.repowise/config.yaml``.
+
+ ``resolve_embedder_api_key`` above already parses this file for the *key*;
+ the *name* beside it had no reader at all. ``repowise serve`` writes both
+ fields together, so a user who configured through that prompt had a valid
+ key ``init`` could not see.
-__all__ = ["KeyLookup", "embedder_key_env_vars", "resolve_embedder_api_key"]
+ ``None`` for ``mock``: that is what a keyless run persists on its way out,
+ not a backend anyone chose. ``None`` too for a backend that needs a key and
+ has none here, because callers reach this only after the environment and
+ the repo ``.env`` came up empty, so the build is certain to fail and the
+ name would still be persisted as the repo's pin.
+ """
+ cfg = _load_global_config()
+ name = str(cfg.get("embedder") or "").strip().lower()
+ if not name or name == "mock":
+ return None
+ if name in _EMBEDDER_KEY_ENV and not str(cfg.get("embedder_api_key") or "").strip():
+ return None
+ return name
+
+
+__all__ = [
+ "KeyLookup",
+ "embedder_key_env_vars",
+ "global_config_embedder",
+ "resolve_embedder_api_key",
+]
diff --git a/packages/cli/src/repowise/cli/ui/mode_selection.py b/packages/cli/src/repowise/cli/ui/mode_selection.py
index 0f4db64db..045ad9879 100644
--- a/packages/cli/src/repowise/cli/ui/mode_selection.py
+++ b/packages/cli/src/repowise/cli/ui/mode_selection.py
@@ -663,7 +663,11 @@ def _resolve_embedder_from_env() -> str:
# already resolving to.
if os.environ.get("EDENAI_API_KEY"):
return "edenai"
- return "mock"
+ # Same last tier as the shared resolver, or the advanced prompt would
+ # default to mock on a machine whose run header just said otherwise.
+ from repowise.cli.providers.keys import global_config_embedder
+
+ return global_config_embedder() or "mock"
def print_index_only_intro(console: Console, has_provider: bool = False) -> None:
diff --git a/tests/unit/cli/test_embedder_resolution.py b/tests/unit/cli/test_embedder_resolution.py
index b3e7a0329..f313221b1 100644
--- a/tests/unit/cli/test_embedder_resolution.py
+++ b/tests/unit/cli/test_embedder_resolution.py
@@ -654,3 +654,191 @@ def test_build_embedder_is_silent_for_the_keyless_default(monkeypatch):
assert isinstance(embedder, KeylessEmbedder)
assert printed == []
+
+
+# --- the global config's ``embedder`` name, which had no reader -------------
+
+
+def _clear_embedder_env(monkeypatch: pytest.MonkeyPatch) -> None:
+ for var in (
+ "REPOWISE_EMBEDDER",
+ "GEMINI_API_KEY",
+ "GOOGLE_API_KEY",
+ "OPENAI_API_KEY",
+ "OPENROUTER_API_KEY",
+ "OLLAMA_EMBEDDING_MODEL",
+ "EDENAI_API_KEY",
+ ):
+ monkeypatch.delenv(var, raising=False)
+
+
+def _write_global_config(home: Path, **keys: object) -> None:
+ global_dir = home / ".repowise"
+ global_dir.mkdir(parents=True, exist_ok=True)
+ (global_dir / "config.yaml").write_text(yaml.safe_dump(keys), encoding="utf-8")
+
+
+def test_global_config_embedder_is_used_when_nothing_is_exported(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The defect: a configured backend resolved to ``mock``, then pinned it."""
+ from repowise.cli.providers.embedders import resolve_embedder
+
+ _clear_embedder_env(monkeypatch)
+ _write_global_config(tmp_path, embedder="openai", embedder_api_key="sk-test")
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: tmp_path))
+
+ assert resolve_embedder(None) == "openai"
+
+
+def test_a_pinned_mock_is_not_a_choice_anyone_made(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A stored ``mock`` is what a keyless run persisted, not a choice."""
+ from repowise.cli.providers.keys import global_config_embedder
+
+ _clear_embedder_env(monkeypatch)
+ _write_global_config(tmp_path, embedder="mock")
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: tmp_path))
+
+ assert global_config_embedder() is None
+
+
+def test_the_environment_still_outranks_the_global_config(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """An exported key is an explicit override and nothing may outrank it."""
+ from repowise.cli.providers.embedders import resolve_embedder
+
+ _clear_embedder_env(monkeypatch)
+ _write_global_config(tmp_path, embedder="openai", embedder_api_key="sk-test")
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: tmp_path))
+ monkeypatch.setenv("GEMINI_API_KEY", "gk-test")
+
+ assert resolve_embedder(None) == "gemini"
+
+
+def test_an_explicit_flag_still_outranks_the_global_config(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from repowise.cli.providers.embedders import resolve_embedder
+
+ _clear_embedder_env(monkeypatch)
+ _write_global_config(tmp_path, embedder="openai", embedder_api_key="sk-test")
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: tmp_path))
+
+ assert resolve_embedder("ollama") == "ollama"
+
+
+def test_no_global_config_still_resolves_keyless(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The keyless default has to survive: it is the advertised no-key path."""
+ from repowise.cli.providers.embedders import resolve_embedder
+
+ _clear_embedder_env(monkeypatch)
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: tmp_path))
+
+ assert resolve_embedder(None) == "mock"
+
+
+ "body",
+ [
+ "embedder: [unclosed", # throws inside safe_load
+ "just a bare string", # parses to str, then .get raises
+ "- a", # parses to list, same
+ ],
+)
+def test_a_malformed_global_config_resolves_keyless(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, body: str
+) -> None:
+ """A hand-edited config must not take the run down.
+
+ The scalar and list cases parse *successfully*, so only an isinstance
+ check catches them, and ``resolve_embedder`` is on every command's path.
+ """
+ from repowise.cli.providers.embedders import resolve_embedder
+ from repowise.cli.providers.keys import global_config_embedder
+
+ _clear_embedder_env(monkeypatch)
+ global_dir = tmp_path / ".repowise"
+ global_dir.mkdir(parents=True, exist_ok=True)
+ (global_dir / "config.yaml").write_text(body, encoding="utf-8")
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: tmp_path))
+
+ assert global_config_embedder() is None
+ assert resolve_embedder(None) == "mock"
+
+
+def test_a_global_backend_with_no_key_is_not_selected(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """``serve`` writes ``embedder`` unconditionally, the key only if given.
+
+ By this tier the environment and the repo ``.env`` are known empty, so a
+ keyed backend with no ``embedder_api_key`` can only fail to build, and the
+ name would still be pinned against a store the fallback wrote at 8-wide.
+ """
+ from repowise.cli.providers.embedders import resolve_embedder
+
+ _clear_embedder_env(monkeypatch)
+ _write_global_config(tmp_path, embedder="openai")
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: tmp_path))
+
+ assert resolve_embedder(None) == "mock"
+
+
+def test_a_keyless_global_backend_is_still_selected(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Ollama needs no key, so the absent-key rule must not swallow it."""
+ from repowise.cli.providers.embedders import resolve_embedder
+
+ _clear_embedder_env(monkeypatch)
+ _write_global_config(tmp_path, embedder="ollama")
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: tmp_path))
+
+ assert resolve_embedder(None) == "ollama"
+
+
+def test_the_repo_env_overlay_outranks_the_global_config(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The precedence edge this change actually introduces."""
+ from repowise.cli.providers.embedders import resolve_embedder
+
+ _clear_embedder_env(monkeypatch)
+ _write_global_config(tmp_path, embedder="gemini", embedder_api_key="gk-test")
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: tmp_path))
+
+ assert resolve_embedder(None, {"OPENAI_API_KEY": "sk-x"}) == "openai"
+
+
+def test_repowise_embedder_outranks_the_global_config(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from repowise.cli.providers.embedders import resolve_embedder
+
+ _clear_embedder_env(monkeypatch)
+ _write_global_config(tmp_path, embedder="openai", embedder_api_key="sk-test")
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: tmp_path))
+ monkeypatch.setenv("REPOWISE_EMBEDDER", "edenai")
+
+ assert resolve_embedder(None) == "edenai"
+
+
+def test_a_repo_pin_outranks_the_global_config(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The width invariant: the pin wrote the table, so the pin queries it."""
+ from repowise.cli.providers.embedders import resolve_embedder_for_repo
+
+ _clear_embedder_env(monkeypatch)
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _write_config(repo, embedder="mock")
+ _write_global_config(tmp_path, embedder="openai", embedder_api_key="sk-test")
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: tmp_path))
+
+ assert resolve_embedder_for_repo(repo) == "mock"