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
refactor(providers): one resolver for LLM and embedder configuration (#3847)
Raghav Chamadiyabe939c111928
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 61d738226..e018265f8 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -9,6 +9,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0---+## [Unreleased]++### Changed++- **One provider order everywhere.** The CLI, `repowise serve` chat and jobs, and the MCP server now resolve provider, model and base URL as flag or UI choice, then `.repowise/config.yaml`, then the web UI's global default, then `REPOWISE_PROVIDER` / `REPOWISE_MODEL`, so `config.yaml` now wins over those env vars in the CLI. Choosing a model or base URL for a repo in the web UI writes that repo's `config.yaml`, which makes switching models on a local OpenAI-compatible server such as LM Studio a single edit. A base URL in `config.yaml` now beats `OPENAI_BASE_URL` and the other `*_BASE_URL` variables. The default provider and model saved in the web UI settings now also apply to CLI runs in repos whose `config.yaml` names none. A `config.yaml` base URL receives an API key from outside that repo's `.repowise/.env` only when it is a local address or was confirmed in Settings or with `repowise init`.+## [0.56.0] - 2026-10-12repowise 0.56 hands agents the exact thing they need to act on. Search returns matching source lines and finds every file in the repository, `get_context` lists every edit site of a symbol verified against live files, caller rows carry the calling line, and `repowise update --working-tree` brings uncommitted work into the index in seconds. `repowise impacted-tests` selects a targeted subset on far more changes, with `--prioritize` and `--explain`.diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.mdindex e9b533717..6a4278428 100644--- a/docs/architecture/ARCHITECTURE.md+++ b/docs/architecture/ARCHITECTURE.md@@ -1624,17 +1624,14 @@ Full configuration with defaults (`.repowise/config.yaml`):```yamlprovider: anthropic # anthropic | openai | openrouter | gemini | deepseek | kimi | ollama | litellm | codex_cli | opencode | edenai | mockmodel: claude-sonnet-4-5 # passed through to the provider-embedding_provider: anthropic-embedding_model: voyage-3+embedder: gemini # gemini | openai | openrouter | ollama | edenai | mock+embedding_model: gemini-embedding-001prompt_caching: true-anthropic:- api_key: ${ANTHROPIC_API_KEY}-+# API keys are read from the environment or .repowise/.env, never from here.openai:- api_key: ${OPENAI_API_KEY}- base_url: https://api.openai.com/v1+ base_url: https://api.openai.com/v1 # any OpenAI-compatible endpointollama:base_url: http://localhost:11434diff --git a/docs/architecture/chat.md b/docs/architecture/chat.mdindex 38c9b4b6b..efb059c9c 100644--- a/docs/architecture/chat.md+++ b/docs/architecture/chat.md@@ -193,19 +193,19 @@ TOOL_REGISTRY: dict[str, ToolDef] # name -> ToolDef(name, description, paramete## 5. Provider Configuration-Defined in `packages/server/src/repowise/server/provider_config.py`.--API keys and active provider/model selection are stored in a server-side-`provider_config.json` file. Environment variables take precedence over stored-keys.--**Resolution order for API keys:**-1. Environment variable (e.g. `GEMINI_API_KEY`, `ANTHROPIC_API_KEY`)-2. Stored key in `provider_config.json`--**Active provider resolution:**-1. Explicitly set via `PATCH /api/providers/active`-2. Auto-detect from first configured provider+Defined in `packages/server/src/repowise/server/provider_config.py`, on top of+the resolver every entry point shares (`core/providers/llm/resolve.py`).++**Provider, model and base URL** (first match wins):+1. A per-request override from the chat model picker+2. The repo's `.repowise/config.yaml` (`PATCH /api/providers/active` with `repo_id` writes here)+3. The global default in `provider_config.json` (`PATCH` without `repo_id`)+4. `REPOWISE_PROVIDER` / `REPOWISE_MODEL` and the provider's `*_BASE_URL`+5. The provider's default model, or auto-detection from the keys present++**API keys:** environment variable, then the repo's `.repowise/.env`, then the+key stored in `provider_config.json`. `GET /api/providers` reports the resolved+values with the layer each came from (`active.provenance`).**Provider catalog:** Gemini, Anthropic, OpenAI, Ollama (local, no key), LiteLLM.diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.mdindex ed37560e1..2cd3d0b49 100644--- a/docs/reference/CONFIG.md+++ b/docs/reference/CONFIG.md@@ -953,12 +953,20 @@ routed through Eden (e.g. `openai/gpt-5*`); other models expose only `auto`.### Provider auto-detection-If you don't pass `--provider`, repowise detects your provider by checking, in-order:+The CLI, `repowise serve` chat and jobs, and the MCP server resolve provider,+model, and base URL the same way, first match wins:-1. `REPOWISE_PROVIDER` environment variable-2. `provider` in `.repowise/config.yaml`-3. API key env vars: `ANTHROPIC_API_KEY` → `OPENAI_API_KEY` → `OPENROUTER_API_KEY` → `OLLAMA_BASE_URL` → `GEMINI_API_KEY` → `DEEPSEEK_API_KEY` → `KIMI_API_KEY` → `EDENAI_API_KEY`+1. `--provider` / `--model` flags, or a per-request choice in the web UI+2. `provider`, `model`, and `<provider>: {base_url: ...}` in `.repowise/config.yaml`+3. the global default saved from the web UI (`~/.repowise/provider_config.json`)+4. `REPOWISE_PROVIDER` / `REPOWISE_MODEL` and the provider's `*_BASE_URL` variable+5. API key env vars: `ANTHROPIC_API_KEY` → `OPENAI_API_KEY` → `OPENROUTER_API_KEY` → `OLLAMA_BASE_URL` → `GEMINI_API_KEY` → `DEEPSEEK_API_KEY` → `KIMI_API_KEY` → `EDENAI_API_KEY`++Picking a model in the web UI for a repo writes it to that repo's `config.yaml`,+so the CLI uses it too. A local OpenAI-compatible server such as LM Studio works+as `provider: openai` with `openai: {base_url: http://localhost:1234/v1}`.+Because `config.yaml` may be committed, a non-local base URL there only receives a key+that is not in the repo's `.repowise/.env` after you confirm it in Settings or with `repowise init`.---@@ -1043,8 +1051,8 @@ The `.repowise/.env` file is gitignored automatically.| Variable | Description ||----------|-------------|-| `REPOWISE_PROVIDER` | Override provider (skips auto-detection) |-| `REPOWISE_MODEL` | Override model |+| `REPOWISE_PROVIDER` | Provider when neither a flag nor `config.yaml` names one (skips auto-detection) |+| `REPOWISE_MODEL` | Model when neither a flag nor `config.yaml` names one || `REPOWISE_DOC_MODEL` | Override the model used for `get_answer` synthesis specifically || `REPOWISE_REASONING` | Override `reasoning` (see valid values above) || `REPOWISE_ANSWER_TIMEOUT_S` | Seconds `get_answer` waits for synthesis before giving up. Defaults to a per-provider budget: 60s for the remote API providers, 120s for `ollama` and `litellm`, 180s for `codex_cli` and `opencode`. Raise it if your model is slower than its class suggests, lower it if you would rather an agent fail fast than block. Capped at 600s. Note your MCP client enforces its own tool timeout underneath this one, so setting a value above it produces a client-side error instead of repowise's diagnosable "synthesis exceeded its budget" response |diff --git a/packages/api-client/src/providers.ts b/packages/api-client/src/providers.tsindex a2689f2a2..830aa064a 100644--- a/packages/api-client/src/providers.ts+++ b/packages/api-client/src/providers.ts@@ -12,15 +12,22 @@ export async function getProviders(return apiGet<ProvidersResponse>(`/api/providers${qs}`);}+/** Set the provider and model (any id the provider accepts). With `repoId`+ * the choice is written to that repo's `.repowise/config.yaml`, which the CLI+ * reads too; without it, the server-wide default. `baseUrl` is an http(s)+ * endpoint such as an OpenAI-compatible LM Studio server: omit it to keep the+ * current one, pass `""` to clear it. */export async function setActiveProvider(provider: string,model?: string,repoId?: string,+ options: { baseUrl?: string } = {},): Promise<ProvidersResponse> {return apiPatch<ProvidersResponse>("/api/providers/active", {provider,model: model ?? null,repo_id: repoId ?? null,+ ...(options.baseUrl !== undefined ? { base_url: options.baseUrl } : {}),});}diff --git a/packages/api-client/src/types/misc.ts b/packages/api-client/src/types/misc.tsindex 6fb315bb1..2a4c88b85 100644--- a/packages/api-client/src/types/misc.ts+++ b/packages/api-client/src/types/misc.ts@@ -43,10 +43,21 @@ export interface EmbedderInfo {semantic?: boolean;}+/** Where a resolved value came from: `request`, `config.yaml`, `global`,+ * `env:<VAR>`, `default` or `autodetect`; null when the value is unset. */+export interface SelectionProvenance {+ provider: string | null;+ model: string | null;+ base_url: string | null;+}+export interface ProvidersResponse {active: {provider: string | null;model: string | null;+ /** Endpoint requests go to; null means the provider's own default. */+ base_url?: string | null;+ provenance?: SelectionProvenance;/** USD per 1K tokens for `model`; null when no model resolves. */input_cost_per_1k?: number | null;output_cost_per_1k?: number | null;diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.pyindex 51b97cb96..61990d381 100644--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py@@ -184,7 +184,7 @@ def _provider_checks(repo_path: _DoctorPath) -> list[DoctorCheck]:from repowise.cli.helpers import validate_provider_config- config_warnings = validate_provider_config()+ config_warnings = validate_provider_config(repo_path=repo_path)config_ok = not config_warningsconfig_detail = "No misconfigured provider keys" if config_ok else "; ".join(config_warnings)checks.append(_check("Provider config", config_ok, config_detail))diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd.py b/packages/cli/src/repowise/cli/commands/serve_cmd.pyindex d11226460..5abe23086 100644--- a/packages/cli/src/repowise/cli/commands/serve_cmd.py+++ b/packages/cli/src/repowise/cli/commands/serve_cmd.py@@ -245,12 +245,13 @@ def _save_global_embedder(embedder: str, api_key: str) -> None:def _load_local_provider_config() -> None:- """Load ``.repowise/.env`` and seed the chat provider from ``config.yaml``.+ """Load ``.repowise/.env`` and seed the embedder from ``config.yaml``.- The API server runs in-process here, so env vars set now are inherited by- the provider-resolution code. ``load_dotenv`` never overwrites an existing- var, and we only set ``REPOWISE_PROVIDER``/``REPOWISE_MODEL`` when unset, so- explicit environment configuration always wins.+ The API server runs in-process here and builds one process-wide embedder+ at startup from env vars, so those are set now. ``load_dotenv`` never+ overwrites an existing var, and the embedder vars are only set when unset,+ so explicit environment configuration always wins. The chat provider+ needs no seeding: it is resolved per repo from that repo's own files."""from repowise.cli.helpers import load_configfrom repowise.cli.ui import load_dotenv@@ -261,18 +262,9 @@ def _load_local_provider_config() -> None:# 1) API keys (OPENAI_API_KEY, ANTHROPIC_API_KEY, …) from .repowise/.envload_dotenv(cwd)-- # 2) Provider/model from .repowise/config.yaml → env vars the server readscfg = load_config(cwd)- provider = cfg.get("provider")- if provider and not os.environ.get("REPOWISE_PROVIDER"):- os.environ["REPOWISE_PROVIDER"] = str(provider)- model = cfg.get("model")- if model and not os.environ.get("REPOWISE_MODEL"):- os.environ["REPOWISE_MODEL"] = str(model)- console.print(f"[dim]Using provider from config: {provider}[/dim]")-- # 3) Embedder from config so chat/search work without an interactive prompt.++ # 2) Embedder from config so chat/search work without an interactive prompt.# Including "mock": that pin is not a preference to be talked out of, it is# the width the table on disk was written at. Skipping it sent a keyless# repo down _setup_embedder's detection path, which picks up any exported@@ -282,7 +274,7 @@ def _load_local_provider_config() -> None:if embedder and not os.environ.get("REPOWISE_EMBEDDER"):os.environ["REPOWISE_EMBEDDER"] = str(embedder)- # 4) Embedding model from config — without this the server rebuilds the+ # 3) Embedding model from config — without this the server rebuilds the# embedder with a provider default (e.g. text-embedding-3-small) that# mismatches the indexed vectors, degrading chat/search retrieval (#426).embedding_model = cfg.get("embedding_model")diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd.py b/packages/cli/src/repowise/cli/commands/workspace_cmd.pyindex f42b1134b..b5da921c8 100644--- a/packages/cli/src/repowise/cli/commands/workspace_cmd.py+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd.py@@ -427,10 +427,10 @@ def _resolve_docs_flag(Priority:1. Explicit ``--docs`` or ``--no-docs``.2. ``--provider`` flag forces docs ON.- 3. Primary repo's ``.repowise/config.yaml`` has a provider → docs ON,- reusing the same provider settings.- 4. ``REPOWISE_PROVIDER`` env var or detectable API key → docs ON.- 5. Otherwise docs OFF, with a skip reason for the completion notice.+ 3. A provider resolves for the primary repo (its ``config.yaml``, the+ global default, ``REPOWISE_PROVIDER``, or a detectable API key) →+ docs ON, reusing the same provider settings.+ 4. Otherwise docs OFF, with a skip reason for the completion notice."""if run_docs is True:return True, None@@ -439,34 +439,14 @@ def _resolve_docs_flag(if provider_name is not None:return True, None- # Check primary repo config- from repowise.cli.helpers import load_config+ # The shared resolver: the primary repo's config.yaml, the global default,+ # REPOWISE_PROVIDER, or a detectable API key.+ from repowise.core.providers.llm.resolve import resolve_llmprimary = ws_config.get_primary()- if primary is not None:- primary_path = (ws_root / primary.path).resolve()- cfg = load_config(primary_path)- if cfg.get("provider"):- return True, None-- # Env-detected provider- import os as _os-- env_provider = _os.environ.get("REPOWISE_PROVIDER")- if env_provider:+ primary_path = (ws_root / primary.path).resolve() if primary is not None else None+ if resolve_llm(primary_path).provider is not None:return True, None- for key in (- "ANTHROPIC_API_KEY",- "OPENAI_API_KEY",- "OPENROUTER_API_KEY",- "GEMINI_API_KEY",- "GOOGLE_API_KEY",- "DEEPSEEK_API_KEY",- "KIMI_API_KEY",- "OLLAMA_BASE_URL",- ):- if _os.environ.get(key):- return True, Nonereturn False, "no provider configured"diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.pyindex a5cac39d8..add3e5e71 100644--- a/packages/cli/src/repowise/cli/helpers.py+++ b/packages/cli/src/repowise/cli/helpers.py@@ -922,13 +922,14 @@ def save_config((single-repo init, workspace init, ``workspace add``). All three otherwiseleave an indexed repo their MCP server cannot authenticate against."""+ from repowise.core.providers.llm.resolve import apply_llm_selection+ from repowise.core.repo_config import save_repo_config+ensure_repowise_dir(repo_path)- config_path = get_repowise_dir(repo_path) / CONFIG_FILENAME- # Round-trip: preserve any existing keys (e.g. exclude_patterns set via CLI)- existing = load_config(repo_path)- existing["provider"] = provider- existing["model"] = model+ # Round-trip: preserve any existing keys (e.g. exclude_patterns set via CLI).+ # provider/model go through the writer the web UI uses too.+ existing = apply_llm_selection(load_config(repo_path), provider, model)existing["embedder"] = embedderif embedding_model:existing["embedding_model"] = embedding_model@@ -944,26 +945,35 @@ def save_config(if reasoning is not None:existing["reasoning"] = resolve_reasoning(reasoning)- try:- import yaml # type: ignore[import-untyped]-- config_path.write_text(- yaml.dump(existing, default_flow_style=False, sort_keys=False),- encoding="utf-8",- )- except ImportError:- # Fallback: write simple key-value format (lists not supported)- lines = [f"provider: {provider}", f"model: {model}", f"embedder: {embedder}"]- if embedding_model:- lines.append(f"embedding_model: {embedding_model}")- if reasoning is not None:- lines.append(f"reasoning: {resolve_reasoning(reasoning)}")- config_path.write_text("\n".join(lines) + "\n", encoding="utf-8")+ save_repo_config(repo_path, existing)+ _trust_configured_base_url(repo_path, existing, provider)if save_key:_persist_provider_key(repo_path, provider)+def _trust_configured_base_url(repo_path: Path, config: dict[str, Any], provider: str) -> None:+ """Record ``<provider>.base_url`` as confirmed: this init run chose to use it.++ A config.yaml base URL only receives a key from outside the repo's own+ ``.env`` once the user confirmed it on this machine; running ``init``+ with it in place is that confirmation. An invalid URL is left unconfirmed,+ and resolution reports it.+ """+ from repowise.core.providers.llm.resolve import trust_base_url, validate_base_url++ section = config.get(provider)+ if not isinstance(section, dict):+ return+ try:+ url = validate_base_url(section.get("base_url"))+ except ValueError:+ return+ if url:+ with contextlib.suppress(OSError):+ trust_base_url(repo_path, url)++def save_config_partial(repo_path: Path,*,@@ -1075,117 +1085,76 @@ def resolve_provider(model: str | None,repo_path: Path | None = None,) -> Any:- """Resolve a provider instance from CLI flags or environment variables.+ """Resolve a provider instance from CLI flags, the repo config, or env.- Resolution order:- 1. Explicit ``--provider`` / ``--model`` flag- 2. ``REPOWISE_PROVIDER`` / ``REPOWISE_MODEL`` env var- 3. ``.repowise/config.yaml`` (written by ``repowise init``)- 4. Auto-detect from API key env vars+ The order is the shared one in :mod:`repowise.core.providers.llm.resolve`:+ ``--provider`` / ``--model`` > ``.repowise/config.yaml`` > the global+ default in ``provider_config.json`` > ``REPOWISE_PROVIDER`` /+ ``REPOWISE_MODEL`` > auto-detection from API keys."""- from repowise.core.providers import get_provider- from repowise.core.providers.llm.registry import (- PROVIDER_AUTODETECT_ORDER,- provider_credentials_present,- provider_kwargs,- )-- cfg: dict[str, Any] = {}- if repo_path is not None:- cfg = load_config(repo_path)-- if provider_name is None:- # An empty or whitespace-only value means "not set", not "a provider- # named ''". CI systems and agent harnesses declare env vars with empty- # values routinely (``REPOWISE_PROVIDER: ""`` in a workflow matrix),- # and the explicit-provider branch below keys off ``is not None``, so- # an empty string reached get_provider() and raised a bare ValueError- # traceback instead of falling through to auto-detection.- provider_name = (os.environ.get("REPOWISE_PROVIDER") or "").strip() or None+ from repowise.core.providers.llm.resolve import resolve_llm- if provider_name is None and cfg.get("provider"):- provider_name = cfg["provider"]+ selection = resolve_llm(repo_path, provider=provider_name, model=model)+ if selection.provider is None:+ # Not fatal on every path: `init` catches this and renders a template+ # wiki instead, so the reason must not be recorded until it ends a+ # command.+ raise reasoned_error(_no_provider_message(), reason="no_provider_configured")+ return _build_provider(selection, _provider_kwargs_or_error(selection, repo_path))- if model is None:- model = (os.environ.get("REPOWISE_MODEL") or "").strip() or None- # Honor the config model regardless of how the provider was resolved (#416).- if model is None and cfg.get("model"):- model = cfg["model"]+def _provider_kwargs_or_error(selection: Any, repo_path: Path | None) -> dict[str, Any]:+ """Constructor kwargs, warning when a configured provider has no key anywhere."""+ from repowise.core.providers.llm.resolve import llm_provider_kwargs- def _config_base_url(name: str) -> str | None:- """Return a base_url the repo config sets for the provider, if any.+ try:+ kwargs = llm_provider_kwargs(selection, repo_path)+ except ValueError as exc:+ # A base URL the repo's config.yaml sets that is malformed, or that+ # nobody on this machine confirmed for a key from elsewhere.+ raise reasoned_error(str(exc), reason="provider_setup_failed") from exc+ if selection.provider_source != "autodetect" and "api_key" not in kwargs:+ # A configured provider whose key is nowhere still gets built: the+ # constructor says what it needs. Agent CLIs are checked for install.+ for warning in validate_provider_config(selection.provider):+ warn(warning)+ return kwargs+++def _build_provider(selection: Any, kwargs: dict[str, Any]) -> Any:+ """Construct the provider, turning a setup failure into a config error."""+ from repowise.core.providers import get_provider- Env vars are handled by :func:`provider_kwargs` from the shared- registry mapping; this covers only the config-file source, which is- CLI-specific.- """- section = cfg.get(name)- if isinstance(section, dict):- base_url = section.get("base_url")- if base_url:- return base_url- return None+ try:+ return get_provider(selection.provider, **kwargs)+ except click.ClickException:+ raise+ except Exception as exc:+ # Everything this constructor reads is user input: env vars and+ # .repowise/config.yaml, base_url above all. A typo there is a+ # configuration error, not a repowise bug, but it used to surface as+ # a raw traceback that escaped every caller's handler.+ raise reasoned_error(+ f"Could not set up the {selection.provider} provider: {exc}. "+ f"Resolved {selection.describe()}. Check those settings.",+ reason="provider_setup_failed",+ ) from exc+++def _no_provider_message() -> str:+ """The no-provider error, listing every env var that would configure one."""+ from repowise.core.providers.llm.registry import (+ PROVIDER_AUTODETECT_ORDER,+ provider_required_envs,+ )- def _build(name: str) -> Any:- """Instantiate ``name`` with env-derived kwargs plus config fallbacks."""- kwargs = provider_kwargs(name, model=model, repo_path=repo_path)- # Applied to any name, as before: openrouter takes a base_url without- # having an env var for one, so gating this on the env map would drop a- # config value that used to be honored. (A stray `mock: {base_url: …}`- # in config.yaml still reaches a constructor that has no such- # parameter and raises TypeError. Longstanding, orthogonal to #1119.)- config_base_url = _config_base_url(name)- if config_base_url:- kwargs.setdefault("base_url", config_base_url)- try:- return get_provider(name, **kwargs)- except click.ClickException:- raise- except Exception as exc:- # Everything this constructor reads is user input: env vars and- # .repowise/config.yaml, base_url above all. A typo there is a- # configuration error, not a repowise bug, but it used to surface- # as a raw traceback that escaped every caller's handler —- # OLLAMA_BASE_URL=http://localhost:abc makes httpx raise- # InvalidURL, which killed `init` outright.- raise reasoned_error(- f"Could not set up the {name} provider: {exc}. Check its "- "settings in your environment and .repowise/config.yaml.",- reason="provider_setup_failed",- ) from exc-- if provider_name is not None:- # Validate configuration before attempting to create provider- warnings = validate_provider_config(provider_name)- if warnings:- for warning in warnings:- warn(warning)- # For explicit provider requests, we still try to create it- # The provider constructor will fail if the API key is actually required-- return _build(provider_name)-- # Auto-detect from whatever credentials the env carries, in the shared- # priority order. The per-provider env-var mapping lives in the registry- # beside the provider table, so adding a provider wires it into the CLI and- # the MCP server at once instead of into whichever copy got remembered.- for candidate in PROVIDER_AUTODETECT_ORDER:- if provider_credentials_present(candidate):- return _build(candidate)-- # Not fatal on every path: `init` catches this and renders a template wiki- # instead, so the reason must not be recorded until it ends a command.- raise reasoned_error(- "No provider configured. Use --provider, set REPOWISE_PROVIDER, "- "or set ANTHROPIC_API_KEY / OPENAI_API_KEY / OPENROUTER_API_KEY / "- "OLLAMA_BASE_URL / GEMINI_API_KEY / GOOGLE_API_KEY / DEEPSEEK_API_KEY / "- "KIMI_API_KEY / EDENAI_API_KEY / LITELLM_API_KEY. Use "- "REPOWISE_PROVIDER=claude_cli to use an "- "authenticated Claude Code subscription, REPOWISE_PROVIDER=codex_cli to use "- "an authenticated Codex CLI subscription, or REPOWISE_PROVIDER=opencode "- "to use opencode.",- reason="no_provider_configured",+ env_vars = [var for name in PROVIDER_AUTODETECT_ORDER for var in provider_required_envs(name)]+ return (+ "No provider configured. Use --provider, set provider in .repowise/config.yaml or "+ f"REPOWISE_PROVIDER, or set one of {' / '.join(env_vars)}. Use "+ "REPOWISE_PROVIDER=claude_cli to use an authenticated Claude Code subscription, "+ "REPOWISE_PROVIDER=codex_cli to use an authenticated Codex CLI subscription, or "+ "REPOWISE_PROVIDER=opencode to use opencode.")@@ -1304,11 +1273,14 @@ def resolve_provider_or_prompt(# ----------------------------------------------------------------------------def validate_provider_config(provider_name: str | None = None) -> list[str]:+def validate_provider_config(+ provider_name: str | None = None, repo_path: Path | None = None+) -> list[str]:"""Validate that required API keys/environment variables are set for the provider.Args:provider_name: The provider name to validate. If None, checks all possible providers.+ repo_path: The repo whose configured provider counts as explicitly requested.Returns:List of warning messages for missing or invalid configuration.@@ -1362,13 +1334,16 @@ def validate_provider_config(provider_name: str | None = None) -> list[str]:warnings.append(f"Provider '{provider_name}' requires {' or '.join(env_vars)}")else:# Check all providers - warn about any that could be configured but are missing keys+ from repowise.core.providers.llm.resolve import resolve_llm++ configured = resolve_llm(repo_path, autodetect=False).providerfor name, env_vars in provider_env_vars.items():if any(_is_env_var_set(var) for var in env_vars):continue# Only warn if this provider is explicitly requested OR# if the env var exists but is invalid (empty)env_var_exists = any(_is_env_var_exists(var) for var in env_vars)- explicitly_requested = os.environ.get("REPOWISE_PROVIDER") == name+ explicitly_requested = configured == nameif explicitly_requested or env_var_exists:warnings.append(f"Provider '{name}' requires {' or '.join(env_vars)}")diff --git a/packages/cli/src/repowise/cli/providers/embedders.py b/packages/cli/src/repowise/cli/providers/embedders.pyindex d689d9143..aa5f356d8 100644--- a/packages/cli/src/repowise/cli/providers/embedders.py+++ b/packages/cli/src/repowise/cli/providers/embedders.py@@ -8,54 +8,27 @@ from typing import Anyfrom 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]:- kwargs: dict[str, Any] = {}- model = os.environ.get("REPOWISE_EMBEDDING_MODEL")- if embedder_name == "ollama":- model = os.environ.get("OLLAMA_EMBEDDING_MODEL") or model- base_url = os.environ.get("OLLAMA_BASE_URL")- dimensions = os.environ.get("OLLAMA_EMBEDDING_DIMS") or os.environ.get(- "REPOWISE_EMBEDDING_DIMS"- )- if base_url:- kwargs["base_url"] = base_url- if dimensions:- kwargs["dimensions"] = int(dimensions)- elif embedder_name == "gemini":- dimensions = os.environ.get("REPOWISE_EMBEDDING_DIMS")- if dimensions:- kwargs["output_dimensionality"] = int(dimensions)- if model:- kwargs["model"] = model- # Passed explicitly rather than left to the adapter's own ``os.environ``- # read, which is the only route this had and the reason a key persisted to- # ``.repowise/.env`` never reached the embedder from a command that had not- # called ``load_dotenv``. Absent keys stay absent: the adapter still raises- # its own "API key required", which is the message worth showing.- lookup = resolve_embedder_api_key(embedder_name, repo_path)- if lookup.key:- kwargs["api_key"] = lookup.key- return kwargs+ """Constructor kwargs, from the resolver the servers share."""+ from repowise.core.providers.embedding.resolve import embedder_kwargs++ return embedder_kwargs(embedder_name, repo_path)def resolve_embedding_model(embedder_name: str) -> str | None:"""Return the configured embedding model for *embedder_name*, if any.- Mirrors the precedence in :func:`_embedder_kwargs` so the value persisted- to ``config.yaml`` at init time is exactly what the embedder would build- with. Returns ``None`` when no model is configured (the embedder then uses- its own default), which keeps ``config.yaml`` free of empty keys.+ The same value :func:`_embedder_kwargs` builds with, so what ``init``+ persists to ``config.yaml`` is what the embedder used. ``None`` when no+ model is configured (the embedder then uses its own default)."""- if embedder_name == "ollama":- return os.environ.get("OLLAMA_EMBEDDING_MODEL") or os.environ.get(- "REPOWISE_EMBEDDING_MODEL"- )- return os.environ.get("REPOWISE_EMBEDDING_MODEL")+ from repowise.core.providers.embedding.resolve import embedding_model_for++ return embedding_model_for(embedder_name)def resolve_embedder(embedder_flag: str | None, env: Mapping[str, str] | None = None) -> str:@@ -63,33 +36,18 @@ def resolve_embedder(embedder_flag: str | None, env: Mapping[str, str] | None =*env* layers a repo's persisted ``.repowise/.env`` under the processenvironment 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`.+ process still wins on every key. The repo's own pin is not consulted:+ this is the choice ``init`` makes afresh. Order: flag > ``REPOWISE_EMBEDDER``+ > detection from keys > ``~/.repowise/config.yaml``'s ``embedder`` > mock."""- if embedder_flag:- return embedder_flag-- def _get(name: str) -> str:- return os.environ.get(name) or (env or {}).get(name) or ""-- configured = _get("REPOWISE_EMBEDDER").strip().lower()- if configured:- return configured- if _get("GEMINI_API_KEY") or _get("GOOGLE_API_KEY"):- return "gemini"- if _get("OPENAI_API_KEY"):- return "openai"- if _get("OPENROUTER_API_KEY"):- return "openrouter"- if _get("OLLAMA_EMBEDDING_MODEL"):- return "ollama"- if _get("EDENAI_API_KEY"):- return "edenai"- return global_config_embedder() or "mock"+ from repowise.core.providers.embedding.resolve import resolve_embedder_name++ overlay = env or {}++ def getenv(name: str) -> str | None:+ return os.environ.get(name) or overlay.get(name) or None++ return resolve_embedder_name(embedder_flag, getenv=getenv, use_pin=False)[0]def pin_names_an_embedder(pinned_embedder: Any) -> bool:@@ -148,43 +106,13 @@ def resolve_embedder_for_repo(repo_path: Any) -> str:with whatever API key happens to be exported: the 1536-wide query vectorfinds nothing in an 8-wide table, and search just returns nothing.- Precedence matches :func:`resolve_embedder` and what ``serve`` already- does, so the same repo in the same shell never resolves two different ways:- an explicitly set ``REPOWISE_EMBEDDER`` wins (it is the documented escape- hatch after a manual re-embed), then the pin, then env detection.+ An explicitly set ``REPOWISE_EMBEDDER`` wins (the documented escape hatch+ after a manual re-embed), then the pin, then detection, with this repo's+ own ``.env`` counted as evidence without merging it into ``os.environ``."""- from pathlib import Path-- from repowise.cli.helpers import load_config-- override = os.environ.get("REPOWISE_EMBEDDER", "").strip().lower()- if override:- return override- try:- pinned = load_config(Path(repo_path)).get("embedder")- except Exception:- pinned = None- if pinned:- return str(pinned)- # No pin, so fall back to detection — and let this repo's own persisted- # ``.env`` count as evidence. Read purely rather than merged into- # ``os.environ``: a workspace resolves several repos in one process, and a- # merge is first-writer-wins, so the first repo's key would silently answer- # for every sibling afterwards.- from repowise.core.repo_config import RepoConfigError, load_repo_env-- try:- overlay = load_repo_env(repo_path)- except RepoConfigError as exc:- # A broken .env must surface — the embedder it pins would silently- # fall back to detection (issue #852).- from repowise.cli.helpers import err_console+ from repowise.core.providers.embedding.resolve import resolve_embedder_name- err_console.print(f"[yellow]Warning:[/yellow] {exc}")- overlay = {}- except Exception:- overlay = {}- return resolve_embedder(None, overlay)+ return resolve_embedder_name(repo_path=repo_path)[0]def build_embedder(embedder_name_resolved: str, repo_path: Any = None) -> Any:diff --git a/packages/cli/src/repowise/cli/providers/keys.py b/packages/cli/src/repowise/cli/providers/keys.pyindex 1ff83ec87..9995c0b15 100644--- a/packages/cli/src/repowise/cli/providers/keys.py+++ b/packages/cli/src/repowise/cli/providers/keys.py@@ -1,164 +1,33 @@-"""One resolver for the embedder credential every CLI command needs.--The CLI used to have no resolver at all: :func:`_embedder_kwargs` never set-``api_key``, so the only route was ``OpenAIEmbedder.__init__`` reading-``os.environ`` directly. A command that forgot ``load_dotenv`` therefore built a-``KeylessEmbedder`` against an index written with real 1536-wide vectors, and-said so in a warning that named the one place the key was *not*-(``OPENAI_API_KEY``) rather than the two places it was.--The MCP server already resolved this correctly-(``mcp_server/_server.py::_persisted_embedder_key``). Centralising *persistence*-without centralising *consumption* is what let the two halves drift: the same-repo, in the same shell, answers semantically through MCP and lexically through-``repowise search``. This module is the consumption half, and it deliberately-mirrors the server's precedence rather than inventing a new one.--Pure by construction: nothing here mutates ``os.environ``. ``load_dotenv``'s-merge-into-the-process semantics are first-writer-wins, so in a workspace one-repo's key would answer for every sibling. Resolving per call with an explicit-``repo_path`` cannot do that.+"""The embedder credential every CLI command needs.++Resolution is shared with the HTTP and MCP servers in+:mod:`repowise.core.providers.embedding.resolve`: process env > the repo's+``.repowise/.env`` > ``~/.repowise/config.yaml``'s ``embedder_api_key``. These+names stay importable for the CLI's callers. Nothing here mutates+``os.environ``: a workspace resolves several repos in one process, and a merge+would let the first repo's key answer for every sibling."""from __future__ import annotations-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-# ``core.providers.embedding`` — a wider change than the defect needs. Ceiling-# noted deliberately: fold both into core when a third consumer appears.-_EMBEDDER_KEY_ENV: dict[str, tuple[str, ...]] = {- "openai": ("OPENAI_API_KEY",),- "gemini": ("GEMINI_API_KEY", "GOOGLE_API_KEY"),- "openrouter": ("OPENROUTER_API_KEY",),- "edenai": ("EDENAI_API_KEY",),-}-+from typing import Any-class KeyLookup(NamedTuple):- """The resolved key, and the places that were consulted to find it.-- ``searched`` exists so the degraded-run message can name what it looked at.- A user whose key sits in ``.repowise/.env`` was previously told to "set- OPENAI_API_KEY", advice that does not apply to them and sends them to fix- something that is not broken.- """-- key: str | None- searched: tuple[str, ...]+from repowise.core.providers.embedding.resolve import (+ EMBEDDER_KEY_ENVS,+ KeyLookup,+ global_config_embedder,+ resolve_embedder_key,+)def embedder_key_env_vars(embedder_name: str) -> tuple[str, ...]:- """Environment variables that carry *embedder_name*'s credential.-- Empty when the embedder needs no key (``ollama``, ``mock``), which callers- use to skip the whole resolution rather than report a missing key for a- backend that never wanted one.- """- return _EMBEDDER_KEY_ENV.get(embedder_name, ())+ """Env vars carrying *embedder_name*'s credential; empty when it needs none."""+ return EMBEDDER_KEY_ENVS.get(embedder_name, ())def resolve_embedder_api_key(embedder_name: str, repo_path: Any = None) -> KeyLookup:- """Find *embedder_name*'s API key, in the order the MCP server uses.-- 1. the process environment — an exported key is an explicit override and- nothing may outrank it;- 2. ``<repo>/.repowise/.env`` — where ``save_config`` persists the key at- init time, read without merging it into ``os.environ``;- 3. ``~/.repowise/config.yaml``'s ``embedder_api_key``, and only when its- ``embedder`` names this same backend. Handing an OpenAI key to Gemini- fails in a way that reads as a bad key rather than a mismatched one.- """- env_vars = embedder_key_env_vars(embedder_name)- if not env_vars:- return KeyLookup(None, ())-- searched: list[str] = [" or ".join(env_vars) + " in the environment"]- for var in env_vars:- value = os.environ.get(var)- if value:- return KeyLookup(value, tuple(searched))-- if repo_path is not None:- searched.append(f"{Path(repo_path) / '.repowise' / '.env'}")- from repowise.core.repo_config import RepoConfigError, load_repo_env-- try:- overlay = load_repo_env(repo_path)- except RepoConfigError as exc:- # A broken .env must surface — a key silently read as missing is- # indistinguishable from "not configured" (issue #852).- from repowise.cli.helpers import err_console-- err_console.print(f"[yellow]Warning:[/yellow] {exc}")- overlay = {}- except Exception:- overlay = {}- for var in env_vars:- value = overlay.get(var)- if value:- return KeyLookup(value, tuple(searched))-- 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:- 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:- return {}- return cfg if isinstance(cfg, dict) else {}---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.-- ``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+ """Find *embedder_name*'s API key, in the order the servers use."""+ return resolve_embedder_key(embedder_name, repo_path)__all__ = [diff --git a/packages/core/src/repowise/core/fsutils.py b/packages/core/src/repowise/core/fsutils.pyindex 9e5778557..7cd5c1094 100644--- a/packages/core/src/repowise/core/fsutils.py+++ b/packages/core/src/repowise/core/fsutils.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport osimport tempfile+import timefrom collections.abc import Iterablefrom pathlib import Pathfrom typing import Any@@ -41,6 +42,22 @@ def atomic_write_text(raise+def replace_with_retry(src: Path | str, dst: Path | str) -> None:+ """``os.replace``, retried while a reader briefly holds *dst* open.++ Windows refuses to replace a file another thread or process has open, and+ the config files written through this are read on every request, so a+ write can land mid-read. Gives up after about half a second.+ """+ for _attempt in range(50):+ try:+ os.replace(src, dst)+ return+ except PermissionError:+ time.sleep(0.01)+ os.replace(src, dst)++def relative_files(files: Iterable[str], repo_root: Any) -> list[str]:"""Repo-relative POSIX paths, in first-seen order; outsiders dropped.diff --git a/packages/core/src/repowise/core/providers/embedding/resolve.py b/packages/core/src/repowise/core/providers/embedding/resolve.pynew file mode 100644index 000000000..109b4265f--- /dev/null+++ b/packages/core/src/repowise/core/providers/embedding/resolve.py@@ -0,0 +1,269 @@+"""Which embedder a repo uses, its credential, and its constructor kwargs.++Shared by the CLI, the HTTP server and the MCP server, which each used to keep+their own env-var table and precedence. Unlike the LLM provider, the embedder+pin in ``config.yaml`` names the backend that *wrote* the vector table, and an+exported ``REPOWISE_EMBEDDER`` stays the documented override for after a+manual re-embed, so the order here is:++flag > ``REPOWISE_EMBEDDER`` > the repo's ``embedder`` pin > detection from+the keys present > ``~/.repowise/config.yaml``'s ``embedder`` > ``mock``.++Credentials: process env > the repo's ``.repowise/.env`` >+``~/.repowise/config.yaml``'s ``embedder_api_key`` (only when its ``embedder``+names the same backend). File reads go through the LLM resolver's+content-keyed cache.+"""++from __future__ import annotations++import logging+import os+import sys+from collections.abc import Callable, Mapping+from pathlib import Path+from typing import Any, NamedTuple++from repowise.core.providers.embedding.registry import _BUILTIN_EMBEDDERS, DEFAULT_EMBEDDER+from repowise.core.providers.llm.registry import EnvLookup+from repowise.core.providers.llm.resolve import (+ Step,+ cached_read,+ first_found,+ found,+ read_repo_config,+ read_repo_env,+ repo_getenv,+)+from repowise.core.providers.llm.specs import PROVIDER_SPECS++logger = logging.getLogger(__name__)++#: Keyed embedders and the env vars carrying their credential. A built-in+#: embedder reads the same key as the LLM provider of the same name; the first+#: var is the canonical one the CLI persists. Absent: needs no key.+EMBEDDER_KEY_ENVS: dict[str, tuple[str, ...]] = {+ name: PROVIDER_SPECS[name].api_key_envs+ for name in _BUILTIN_EMBEDDERS+ if name in PROVIDER_SPECS and PROVIDER_SPECS[name].api_key_envs+}++# Detection order when nothing names an embedder, and the env var that counts+# as evidence for each. Ollama needs no key, so an embedding model is its signal.+_DETECT_SIGNALS: tuple[tuple[str, tuple[str, ...]], ...] = (+ ("gemini", EMBEDDER_KEY_ENVS["gemini"]),+ ("openai", EMBEDDER_KEY_ENVS["openai"]),+ ("openrouter", EMBEDDER_KEY_ENVS["openrouter"]),+ ("ollama", ("OLLAMA_EMBEDDING_MODEL",)),+ ("edenai", EMBEDDER_KEY_ENVS["edenai"]),+)+++def global_config_path() -> Path:+ """``~/.repowise/config.yaml``, resolved per call so tests can move home."""+ return Path.home() / ".repowise" / "config.yaml"+++def _parse_yaml_mapping(path: Path) -> dict[str, Any]:+ try:+ import yaml # type: ignore[import-untyped]++ data = yaml.safe_load(path.read_text(encoding="utf-8"))+ except Exception:+ return {}+ # A hand-edited file holding a scalar or a list parses fine; ignore it.+ return data if isinstance(data, dict) else {}+++def read_global_embedder_config() -> Mapping[str, Any]:+ """``~/.repowise/config.yaml`` as a mapping, empty when absent or not one."""+ return cached_read(global_config_path(), _parse_yaml_mapping)+++def global_config_embedder() -> str | None:+ """The backend pinned in ``~/.repowise/config.yaml``, if it can be built.++ ``None`` for ``mock`` (what a keyless run persists, not a choice) and for+ a keyed backend saved without its key.+ """+ cfg = read_global_embedder_config()+ name = str(cfg.get("embedder") or "").strip().lower()+ if not name or name == "mock":+ return None+ if name in EMBEDDER_KEY_ENVS and not str(cfg.get("embedder_api_key") or "").strip():+ return None+ return name+++def detect_embedder(getenv: EnvLookup) -> str | None:+ """The first embedder whose credential (or ollama model) is present."""+ for name, env_vars in _DETECT_SIGNALS:+ if any(getenv(var) for var in env_vars):+ return name+ return None+++def resolve_embedder_name(+ flag: str | None = None,+ *,+ repo_path: Path | str | None = None,+ getenv: EnvLookup | None = None,+ use_pin: bool = True,+ detect: bool = True,+) -> tuple[str, str]:+ """``(name, source)`` for the embedder, in the order the module states.++ ``use_pin=False`` skips the repo's pin (``init`` choosing afresh), and+ ``detect=False`` stops before key detection and the global file (a reader+ that must not guess a backend the index was not built with).+ """+ lookup = getenv or repo_getenv(repo_path)+ steps: list[Step] = [+ lambda: found(flag, "flag"),+ lambda: found(lookup("REPOWISE_EMBEDDER"), "env:REPOWISE_EMBEDDER"),+ ]+ if use_pin and repo_path is not None:+ steps.append(lambda: found(read_repo_config(repo_path).get("embedder"), "config.yaml"))+ if detect:+ steps.append(lambda: found(detect_embedder(lookup), "autodetect"))+ steps.append(lambda: found(global_config_embedder(), "global"))+ name, source = first_found(steps)+ return (name.lower(), source) if name and source else (DEFAULT_EMBEDDER, "default")+++class KeyLookup(NamedTuple):+ """The resolved key, and the places consulted, for a degraded-run message."""++ key: str | None+ searched: tuple[str, ...]+++def resolve_embedder_key(name: str, repo_path: Path | str | None = None) -> KeyLookup:+ """Find *name*'s API key: process env > repo ``.env`` > global config."""+ env_vars = EMBEDDER_KEY_ENVS.get(name, ())+ if not env_vars:+ return KeyLookup(None, ())++ places: list[tuple[str, Callable[[], str | None]]] = [+ (" or ".join(env_vars) + " in the environment", lambda: _first_var(os.environ, env_vars))+ ]+ if repo_path is not None:+ places.append(+ (+ str(Path(repo_path) / ".repowise" / ".env"),+ lambda: _first_var(read_repo_env(repo_path), env_vars),+ )+ )+ places.append((f"embedder_api_key in {global_config_path()}", lambda: _global_key(name)))++ searched: list[str] = []+ for place, lookup in places:+ searched.append(place)+ key = lookup()+ if key:+ return KeyLookup(key, tuple(searched))+ return KeyLookup(None, tuple(searched))+++def _first_var(source: Mapping[str, str], env_vars: tuple[str, ...]) -> str | None:+ for var in env_vars:+ value = (source.get(var) or "").strip()+ if value:+ return value+ return None+++def _global_key(name: str) -> str | None:+ """The global config's key, only when it was saved for this same backend.++ An openai key handed to gemini fails in a way that reads as a bad key,+ not a mismatched one.+ """+ cfg = read_global_embedder_config()+ if str(cfg.get("embedder") or "").strip().lower() != name:+ return None+ return str(cfg.get("embedder_api_key") or "").strip() or None+++def _positive_int(var: str) -> int | None:+ raw = os.environ.get(var)+ if not raw:+ return None+ try:+ value = int(raw)+ except (ValueError, OverflowError):+ value = 0+ if value > 0:+ return value+ logger.warning("embedding_dims_invalid", extra={"var": var, "value": raw})+ print(+ f"{var}={raw!r} is not a positive integer; using the embedder's default width.",+ file=sys.stderr,+ )+ return None+++def embedding_model_for(name: str) -> str | None:+ """The configured embedding model for *name*, or ``None`` for its default."""+ if name == "ollama":+ return os.environ.get("OLLAMA_EMBEDDING_MODEL") or os.environ.get(+ "REPOWISE_EMBEDDING_MODEL"+ )+ return os.environ.get("REPOWISE_EMBEDDING_MODEL")+++def _ollama_kwargs() -> dict[str, Any]:+ kwargs: dict[str, Any] = {}+ base_url = os.environ.get("OLLAMA_BASE_URL")+ if base_url:+ kwargs["base_url"] = base_url+ dims = _positive_int("OLLAMA_EMBEDDING_DIMS") or _positive_int("REPOWISE_EMBEDDING_DIMS")+ if dims:+ kwargs["dimensions"] = dims+ return kwargs+++def _gemini_kwargs() -> dict[str, Any]:+ # Gemini spells the width ``output_dimensionality``; openai and ollama+ # read REPOWISE_EMBEDDING_DIMS in their own constructors.+ dims = _positive_int("REPOWISE_EMBEDDING_DIMS")+ return {"output_dimensionality": dims} if dims else {}+++#: Constructor arguments only some embedders take.+_EXTRA_KWARGS: dict[str, Callable[[], dict[str, Any]]] = {+ "ollama": _ollama_kwargs,+ "gemini": _gemini_kwargs,+}+++def embedder_kwargs(name: str, repo_path: Path | str | None = None) -> dict[str, Any]:+ """Constructor kwargs for *name*: model, width, endpoint, key.++ Only what is configured is passed; everything else falls through to the+ embedder's own defaults, which are declared once in its constructor.+ """+ model = embedding_model_for(name)+ kwargs: dict[str, Any] = {"model": model} if model else {}+ extra = _EXTRA_KWARGS.get(name)+ if extra is not None:+ kwargs.update(extra())+ # Passed explicitly so a key in the repo's .env or the global config+ # reaches the embedder, not only an exported one.+ key = resolve_embedder_key(name, repo_path).key+ if key:+ kwargs["api_key"] = key+ return kwargs+++__all__ = [+ "EMBEDDER_KEY_ENVS",+ "KeyLookup",+ "detect_embedder",+ "embedder_kwargs",+ "embedding_model_for",+ "global_config_embedder",+ "read_global_embedder_config",+ "resolve_embedder_key",+ "resolve_embedder_name",+]diff --git a/packages/core/src/repowise/core/providers/llm/anthropic.py b/packages/core/src/repowise/core/providers/llm/anthropic.pyindex 7d7a987d6..2793ce71d 100644--- a/packages/core/src/repowise/core/providers/llm/anthropic.py+++ b/packages/core/src/repowise/core/providers/llm/anthropic.py@@ -43,6 +43,7 @@ from repowise.core.providers.llm.base import (temperature_kwargs,translate_sdk_errors,)+from repowise.core.providers.llm.specs import PROVIDER_SPECSfrom repowise.core.rate_limiter import RateLimiterfrom repowise.core.reasoning import ReasoningMode@@ -109,7 +110,7 @@ class AnthropicProvider(SdkClientOwner, BaseProvider):Args:api_key: Anthropic API key. Falls back to ANTHROPIC_API_KEY env var.- model: Model identifier. Defaults to claude-haiku-5-5.+ model: Model identifier. Defaults to the spec's default_model.base_url: Optional custom API base URL (for proxies/self-hosted endpoints).rate_limiter: Optional pre-configured RateLimiter. If None, no rate limitingis applied (useful when the caller manages concurrency via semaphore).@@ -118,7 +119,7 @@ class AnthropicProvider(SdkClientOwner, BaseProvider):def __init__(self,api_key: str | None = None,- model: str = "claude-haiku-5-5",+ model: str = PROVIDER_SPECS["anthropic"].default_model,base_url: str | None = None,rate_limiter: RateLimiter | None = None,cost_tracker: CostTracker | None = None,diff --git a/packages/core/src/repowise/core/providers/llm/claude_cli.py b/packages/core/src/repowise/core/providers/llm/claude_cli.pyindex 56dbb59d2..c8474149c 100644--- a/packages/core/src/repowise/core/providers/llm/claude_cli.py+++ b/packages/core/src/repowise/core/providers/llm/claude_cli.py@@ -43,6 +43,7 @@ from repowise.core.providers.llm.base import (ProviderModelOption,normalize_stop_reason,)+from repowise.core.providers.llm.specs import PROVIDER_SPECSfrom repowise.core.rate_limiter import RateLimiterfrom repowise.core.reasoning import ReasoningMode, normalize_reasoning@@ -50,7 +51,7 @@ log = structlog.get_logger(__name__)# Matches the anthropic provider's default, whose docstring calls haiku "ample# for doc pages". Overridable with --model / REPOWISE_MODEL.-_DEFAULT_MODEL = "claude-haiku-5-5"+_DEFAULT_MODEL = PROVIDER_SPECS["claude_cli"].default_model.removeprefix("claude_cli/")_EXEC_TIMEOUT_SECONDS = EXEC_TIMEOUT_SECONDS# This is a one-shot text generation: the prompt already carries the context.diff --git a/packages/core/src/repowise/core/providers/llm/deepseek.py b/packages/core/src/repowise/core/providers/llm/deepseek.pyindex 36b8f3b35..db8ba4fa7 100644--- a/packages/core/src/repowise/core/providers/llm/deepseek.py+++ b/packages/core/src/repowise/core/providers/llm/deepseek.py@@ -19,6 +19,7 @@ from repowise.core.providers.llm.openai_compat import (OpenAICompatibleProvider,listed_model_options,)+from repowise.core.providers.llm.specs import PROVIDER_SPECSfrom repowise.core.rate_limiter import RateLimiterfrom repowise.core.reasoning import ReasoningMode, normalize_reasoning@@ -91,7 +92,7 @@ class DeepSeekProvider(OpenAICompatibleProvider):Args:api_key: DeepSeek API key. Falls back to DEEPSEEK_API_KEY env var.- model: Model identifier. Defaults to deepseek-v4-flash.+ model: Model identifier. Defaults to the spec's default_model.base_url: Override the DeepSeek API URL (rarely needed).rate_limiter: Optional RateLimiter instance.cost_tracker: Optional CostTracker instance for usage recording.@@ -109,7 +110,7 @@ class DeepSeekProvider(OpenAICompatibleProvider):def __init__(self,api_key: str | None = None,- model: str = "deepseek-v4-flash",+ model: str = PROVIDER_SPECS["deepseek"].default_model,base_url: str | None = None,rate_limiter: RateLimiter | None = None,cost_tracker: CostTracker | None = None,diff --git a/packages/core/src/repowise/core/providers/llm/edenai.py b/packages/core/src/repowise/core/providers/llm/edenai.pyindex 60a09aa8c..bbc5a9de3 100644--- a/packages/core/src/repowise/core/providers/llm/edenai.py+++ b/packages/core/src/repowise/core/providers/llm/edenai.py@@ -30,6 +30,7 @@ from repowise.core.providers.llm.openai_compat import (OpenAICompatibleProvider,listed_model_options,)+from repowise.core.providers.llm.specs import PROVIDER_SPECSfrom repowise.core.rate_limiter import RateLimiterfrom repowise.core.reasoning import ReasoningMode, normalize_reasoning@@ -104,7 +105,7 @@ class EdenAIProvider(OpenAICompatibleProvider):Args:api_key: Eden AI API key. Falls back to EDENAI_API_KEY env var.model: Model identifier in ``vendor/model`` form. Defaults to- ``mistral/mistral-small-latest``.+ the spec's default_model.base_url: Override the Eden AI API URL. Falls back to EDENAI_BASE_URL,then the global endpoint. Set the EU endpoint(``https://api.eu.edenai.run/v3``) for data residency.@@ -129,7 +130,7 @@ class EdenAIProvider(OpenAICompatibleProvider):def __init__(self,api_key: str | None = None,- model: str = "mistral/mistral-small-latest",+ model: str = PROVIDER_SPECS["edenai"].default_model,base_url: str | None = None,rate_limiter: RateLimiter | None = None,cost_tracker: CostTracker | None = None,diff --git a/packages/core/src/repowise/core/providers/llm/gemini.py b/packages/core/src/repowise/core/providers/llm/gemini.pyindex e60aabd4c..a15a1ce47 100644--- a/packages/core/src/repowise/core/providers/llm/gemini.py+++ b/packages/core/src/repowise/core/providers/llm/gemini.py@@ -37,6 +37,7 @@ from repowise.core.providers.llm.base import (provider_should_retry,record_generation_cost,)+from repowise.core.providers.llm.specs import PROVIDER_SPECSfrom repowise.core.rate_limiter import RateLimiterfrom repowise.core.reasoning import ReasoningMode, normalize_reasoning@@ -227,7 +228,7 @@ class GeminiProvider(BaseProvider):"""Native Gemini provider using the google-genai SDK.Args:- model: Gemini model name. Defaults to gemini-3.5-flash-lite.+ model: Gemini model name. Defaults to the spec's default_model.api_key: Google API key. Falls back to GEMINI_API_KEY or GOOGLE_API_KEY env var.base_url: Optional custom base URL (e.g., for proxy/self-hosted endpoints).rate_limiter: Optional RateLimiter instance.@@ -236,7 +237,7 @@ class GeminiProvider(BaseProvider):def __init__(self,- model: str = "gemini-3.5-flash-lite",+ model: str = PROVIDER_SPECS["gemini"].default_model,api_key: str | None = None,base_url: str | None = None,rate_limiter: RateLimiter | None = None,diff --git a/packages/core/src/repowise/core/providers/llm/kimi.py b/packages/core/src/repowise/core/providers/llm/kimi.pyindex 117d6f3c4..3cc97a180 100644--- a/packages/core/src/repowise/core/providers/llm/kimi.py+++ b/packages/core/src/repowise/core/providers/llm/kimi.py@@ -22,6 +22,7 @@ from repowise.core.providers.llm.openai_compat import (OpenAICompatibleProvider,listed_model_options,)+from repowise.core.providers.llm.specs import PROVIDER_SPECSfrom repowise.core.rate_limiter import RateLimiterfrom repowise.core.reasoning import ReasoningMode, normalize_reasoning@@ -90,7 +91,7 @@ class KimiProvider(OpenAICompatibleProvider):Args:api_key: Kimi API key. Falls back to KIMI_API_KEY env var.- model: Model identifier. Defaults to kimi-for-coding.+ model: Model identifier. Defaults to the spec's default_model.base_url: Override the Kimi API URL (rarely needed).rate_limiter: Optional RateLimiter instance.cost_tracker: Optional CostTracker instance for usage recording.@@ -110,7 +111,7 @@ class KimiProvider(OpenAICompatibleProvider):def __init__(self,api_key: str | None = None,- model: str = "kimi-for-coding",+ model: str = PROVIDER_SPECS["kimi"].default_model,base_url: str | None = None,rate_limiter: RateLimiter | None = None,cost_tracker: CostTracker | None = None,diff --git a/packages/core/src/repowise/core/providers/llm/ollama.py b/packages/core/src/repowise/core/providers/llm/ollama.pyindex d29e03012..aaedd346c 100644--- a/packages/core/src/repowise/core/providers/llm/ollama.py+++ b/packages/core/src/repowise/core/providers/llm/ollama.py@@ -50,6 +50,7 @@ from repowise.core.providers.llm.base import (record_generation_cost,)from repowise.core.providers.llm.openai_compat import stream_openai_chat+from repowise.core.providers.llm.specs import PROVIDER_SPECSfrom repowise.core.rate_limiter import RateLimiterfrom repowise.core.reasoning import ReasoningMode@@ -154,7 +155,7 @@ class OllamaProvider(SdkClientOwner, BaseProvider):def __init__(self,- model: str = "qwen3.5:4b",+ model: str = PROVIDER_SPECS["ollama"].default_model,base_url: str | None = None,rate_limiter: RateLimiter | None = None,) -> None:diff --git a/packages/core/src/repowise/core/providers/llm/openai.py b/packages/core/src/repowise/core/providers/llm/openai.pyindex b7b035fda..38d8cf58a 100644--- a/packages/core/src/repowise/core/providers/llm/openai.py+++ b/packages/core/src/repowise/core/providers/llm/openai.py@@ -42,6 +42,7 @@ from repowise.core.providers.llm.openai_compat import (stream_openai_chat,translate_openai_errors,)+from repowise.core.providers.llm.specs import PROVIDER_SPECSfrom repowise.core.rate_limiter import RateLimiterfrom repowise.core.reasoning import ReasoningMode, normalize_reasoning@@ -288,7 +289,7 @@ class OpenAIProvider(SdkClientOwner, BaseProvider):Args:api_key: OpenAI API key. Falls back to OPENAI_API_KEY env var.- model: Model identifier. Defaults to gpt-5.6-luna.+ model: Model identifier. Defaults to the spec's default_model.base_url: Optional custom base URL for OpenAI-compatible endpoints.rate_limiter: Optional RateLimiter instance."""@@ -296,7 +297,7 @@ class OpenAIProvider(SdkClientOwner, BaseProvider):def __init__(self,api_key: str | None = None,- model: str = "gpt-5.6-luna",+ model: str = PROVIDER_SPECS["openai"].default_model,base_url: str | None = None,rate_limiter: RateLimiter | None = None,cost_tracker: CostTracker | None = None,diff --git a/packages/core/src/repowise/core/providers/llm/openrouter.py b/packages/core/src/repowise/core/providers/llm/openrouter.pyindex 7eeb3608f..854116d4e 100644--- a/packages/core/src/repowise/core/providers/llm/openrouter.py+++ b/packages/core/src/repowise/core/providers/llm/openrouter.py@@ -45,6 +45,7 @@ from repowise.core.providers.llm.openai_compat import (stream_openai_chat,translate_openai_errors,)+from repowise.core.providers.llm.specs import PROVIDER_SPECSfrom repowise.core.rate_limiter import RateLimiterfrom repowise.core.reasoning import ReasoningMode, normalize_reasoning@@ -181,7 +182,7 @@ class OpenRouterProvider(SdkClientOwner, BaseProvider):Args:api_key: OpenRouter API key. Falls back to OPENROUTER_API_KEY env var.- model: Model identifier (vendor/model format). Defaults to google/gemini-3.5-flash-lite.+ model: Model identifier (vendor/model format). Defaults to the spec's default_model.base_url: Override the OpenRouter API URL (rarely needed).rate_limiter: Optional RateLimiter instance.http_referer: Optional site URL for OpenRouter rankings/leaderboards.@@ -194,7 +195,7 @@ class OpenRouterProvider(SdkClientOwner, BaseProvider):def __init__(self,api_key: str | None = None,- model: str = "google/gemini-3.5-flash-lite",+ model: str = PROVIDER_SPECS["openrouter"].default_model,base_url: str = "https://openrouter.ai/api/v1",rate_limiter: RateLimiter | None = None,http_referer: str | None = None,diff --git a/packages/core/src/repowise/core/providers/llm/registry.py b/packages/core/src/repowise/core/providers/llm/registry.pyindex d915f9139..4d808832f 100644--- a/packages/core/src/repowise/core/providers/llm/registry.py+++ b/packages/core/src/repowise/core/providers/llm/registry.py@@ -296,8 +296,9 @@ def list_providers() -> list[str]:def provider_available_for_repo(repo_path: Path | str) -> bool:"""Whether a provider would resolve for *repo_path*, constructing nothing.- Mirrors the CLI's resolution order: an explicit choice is checked for- usability, auto-detection asks only whether credentials name a provider.+ Uses the shared resolver (``resolve.resolve_llm``): a configured choice is+ checked for usability, auto-detection asks only whether credentials name a+ provider.Reporting-only, so it answers False rather than raising on a broken config.Resolution reads the repo's own ``.repowise/.env`` as well as the process@@ -307,16 +308,9 @@ def provider_available_for_repo(repo_path: Path | str) -> bool:``git_archaeology`` lanes had no provider while those lanes were running."""try:- from repowise.core.repo_config import load_repo_config-- getenv = repo_env_lookup(repo_path)- configured = (getenv("REPOWISE_PROVIDER") or "").strip()- if not configured:- configured = str(load_repo_config(repo_path).get("provider") or "").strip()- if configured:- return provider_is_usable(configured, getenv)- return any(- provider_credentials_present(name, getenv) for name in PROVIDER_AUTODETECT_ORDER- )+ from repowise.core.providers.llm.resolve import provider_ready, resolve_llm++ selection = resolve_llm(repo_path)+ return selection.provider is not None and provider_ready(selection.provider, repo_path)except Exception:return Falsediff --git a/packages/core/src/repowise/core/providers/llm/resolve.py b/packages/core/src/repowise/core/providers/llm/resolve.pynew file mode 100644index 000000000..a1057a0e7--- /dev/null+++ b/packages/core/src/repowise/core/providers/llm/resolve.py@@ -0,0 +1,668 @@+"""Where a repo's LLM provider, model and endpoint come from, decided once.++Every entry point (CLI init/update, ``repowise serve`` chat and jobs, the MCP+server's ``get_answer``) asks :func:`resolve_llm`, so one repo resolves the+same way from all of them. Precedence, highest first:++1. an explicit choice: a CLI flag, or a per-request override from the web UI+2. the repo's ``.repowise/config.yaml`` (``provider``, ``model``, and+ ``<provider>: {base_url: ...}``)+3. the global default in ``provider_config.json`` (``active_provider``,+ ``active_model``, ``active_base_url``)+4. ``REPOWISE_PROVIDER`` / ``REPOWISE_MODEL`` and the provider's own+ ``*_BASE_URL`` variable, from the process env or the repo's ``.env``+5. the spec's default model, or auto-detection from the credentials present++API keys resolve on their own chain (:func:`resolve_api_key`): process env,+then the repo's ``.repowise/.env``, then keys stored in ``provider_config.json``.++Chat resolves on every request, so the three files are parsed once per+version: reads are cached by path and a digest of the bytes. Nothing in this+module touches the network.+"""++from __future__ import annotations++import contextlib+import hashlib+import ipaddress+import json+import logging+import os+import threading+from collections.abc import Callable, Collection, Iterable, Mapping+from dataclasses import dataclass+from pathlib import Path+from typing import Any+from urllib.parse import urlparse++from repowise.core.fsutils import replace_with_retry+from repowise.core.providers.llm.registry import (+ PROVIDER_API_KEY_ENVS,+ PROVIDER_AUTODETECT_ORDER,+ PROVIDER_BASE_URL_ENVS,+ EnvLookup,+ provider_credentials_present,+ provider_is_usable,+ provider_kwargs,+)+from repowise.core.providers.llm.specs import PROVIDER_SPECS++logger = logging.getLogger(__name__)++GLOBAL_CONFIG_FILENAME = "provider_config.json"++# ---------------------------------------------------------------------------+# Cached reads+# ---------------------------------------------------------------------------++_cache: dict[Path, tuple[bytes, Any]] = {}+_cache_lock = threading.Lock()+++def cached_read(path: Path, parse: Callable[[Path], Any]) -> Any:+ """``parse(path)``, reused while the file's bytes are unchanged.++ Keyed on a digest of the content, not mtime: these files are a few hundred+ bytes, so reading them is cheap and parsing is the cost, and a same-size+ rewrite by another process inside one timestamp tick is still seen. The+ value is shared between callers, so it is read-only by contract. A missing+ file is ``{}``. ``parse`` handles its own errors, which lets a broken file+ warn once per version instead of on every request.+ """+ try:+ digest = hashlib.blake2b(path.read_bytes(), digest_size=16).digest()+ except OSError:+ return {}+ with _cache_lock:+ hit = _cache.get(path)+ if hit is not None and hit[0] == digest:+ return hit[1]+ value = parse(path)+ with _cache_lock:+ _cache[path] = (digest, value)+ return value+++def forget_cached(path: Path | str) -> None:+ """Drop *path* from the read cache, for a writer that wants it gone now."""+ with _cache_lock:+ _cache.pop(Path(path), None)+++def clear_cache() -> None:+ with _cache_lock:+ _cache.clear()+++def global_config_path() -> Path:+ """``$REPOWISE_CONFIG_DIR/provider_config.json``, else ``~/.repowise/``."""+ config_dir = os.environ.get("REPOWISE_CONFIG_DIR", "")+ base = Path(config_dir) if config_dir else Path.home() / ".repowise"+ return base / GLOBAL_CONFIG_FILENAME+++def _parse_json(path: Path) -> dict[str, Any]:+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except Exception:+ logger.warning("Could not read %s; using no stored provider settings", path)+ return {}+ return data if isinstance(data, dict) else {}+++def _parse_repo_config(path: Path) -> dict[str, Any]:+ from repowise.core.repo_config import RepoConfigError, load_repo_config++ try:+ return load_repo_config(path.parent.parent)+ except RepoConfigError as exc:+ # A broken config must surface, not resolve as defaults silently.+ logger.warning("%s; using no repo provider settings", exc)+ except Exception:+ logger.warning("Could not read %s; using no repo provider settings", path)+ return {}+++def _parse_repo_env(path: Path) -> dict[str, str]:+ from repowise.core.repo_config import RepoConfigError, load_repo_env++ try:+ return load_repo_env(path.parent.parent)+ except RepoConfigError as exc:+ logger.warning("%s; using the process environment only", exc)+ except Exception:+ logger.warning("Could not read %s; using the process environment only", path)+ return {}+++def read_global_config() -> Mapping[str, Any]:+ """The parsed ``provider_config.json``. Read-only: copy before editing."""+ return cached_read(global_config_path(), _parse_json)+++_global_write_lock = threading.RLock()+++def update_global_config(change: Callable[[dict[str, Any]], Any]) -> None:+ """Apply *change* to ``provider_config.json`` under one lock, atomically.++ Every writer (keys, the global default, migration, trusted URLs) goes+ through here, so two requests' read-modify-writes cannot interleave and+ lose one another's edit. The lock is per process; a second server process+ writing the same file at the same instant is the remaining ceiling.+ """+ with _global_write_lock:+ path = global_config_path()+ config = json.loads(json.dumps(dict(read_global_config())))+ change(config)+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp = path.with_suffix(f"{path.suffix}.tmp.{os.getpid()}.{threading.get_ident()}")+ tmp.write_text(json.dumps(config, indent=2), encoding="utf-8")+ # Keys are sensitive: owner read/write only where the OS honours it.+ with contextlib.suppress(OSError):+ os.chmod(tmp, 0o600)+ replace_with_retry(tmp, path)+ forget_cached(path)+++def _repo_key(repo_path: Path | str) -> str:+ return str(Path(repo_path).resolve())+++def base_url_trusted(repo_path: Path | str | None, url: str) -> bool:+ """Whether the user confirmed *url* for this repo (web UI or ``repowise init``)."""+ if repo_path is None:+ return False+ trusted = read_global_config().get("trusted_base_urls")+ if not isinstance(trusted, Mapping):+ return False+ urls = trusted.get(_repo_key(repo_path))+ return isinstance(urls, list) and url in urls+++def trust_base_url(repo_path: Path | str, url: str) -> None:+ """Record that the user chose *url* for this repo, so stored keys may go there."""+ if base_url_trusted(repo_path, url):+ return++ def change(config: dict[str, Any]) -> None:+ trusted = config.get("trusted_base_urls")+ if not isinstance(trusted, dict):+ trusted = config["trusted_base_urls"] = {}+ urls = trusted.setdefault(_repo_key(repo_path), [])+ if url not in urls:+ urls.append(url)++ update_global_config(change)+++def read_repo_config(repo_path: Path | str | None) -> Mapping[str, Any]:+ """The parsed ``.repowise/config.yaml``, ``{}`` when absent or broken."""+ if repo_path is None:+ return {}+ return cached_read(Path(repo_path) / ".repowise" / "config.yaml", _parse_repo_config)+++def read_repo_env(repo_path: Path | str | None) -> Mapping[str, str]:+ """The parsed ``.repowise/.env``, never merged into ``os.environ``."""+ if repo_path is None:+ return {}+ return cached_read(Path(repo_path) / ".repowise" / ".env", _parse_repo_env)+++def repo_getenv(repo_path: Path | str | None) -> EnvLookup:+ """Process env first, then *repo_path*'s ``.repowise/.env``; blanks are unset."""+ overlay = read_repo_env(repo_path)++ def getenv(name: str) -> str | None:+ return _clean(os.environ.get(name)) or _clean(overlay.get(name))++ return getenv+++def _clean(value: Any) -> str | None:+ if value is None:+ return None+ text = str(value).strip()+ return text or None+++# ---------------------------------------------------------------------------+# Resolution+# ---------------------------------------------------------------------------+++@dataclass(frozen=True, slots=True)+class LLMSelection:+ """The resolved provider, model and endpoint, and where each came from.++ Sources: the override label (``"flag"``, ``"request"``, or an env name for+ an override variable), ``"config.yaml"``, ``"global"``,+ ``"env:<VAR>"``, ``"default"``, ``"autodetect"``. ``None`` when unset.+ """++ provider: str | None = None+ model: str | None = None+ base_url: str | None = None+ provider_source: str | None = None+ model_source: str | None = None+ base_url_source: str | None = None++ @property+ def provenance(self) -> dict[str, str | None]:+ return {+ "provider": self.provider_source,+ "model": self.model_source,+ "base_url": self.base_url_source,+ }++ @property+ def display_base_url(self) -> str | None:+ """``base_url`` safe to show: any user name or password removed."""+ return without_credentials(self.base_url) if self.base_url else None++ def describe(self) -> str:+ """One line for a CLI summary, e.g. ``openai (config.yaml), model x (default)``."""+ if not self.provider:+ return "no provider"+ text = f"{self.provider} ({self.provider_source})"+ if self.model:+ text += f", model {self.model} ({self.model_source})"+ if self.base_url:+ text += f", base URL {self.display_base_url} ({self.base_url_source})"+ return text+++#: ``(value, source)`` from one precedence step, or ``None`` when it has nothing.+Found = tuple[str, str] | None+Step = Callable[[], Found]+++def first_found(steps: Iterable[Step]) -> tuple[str | None, str | None]:+ """The first step's ``(value, source)``, walking *steps* in precedence order."""+ for step in steps:+ found = step()+ if found:+ return found+ return None, None+++def found(value: Any, source: str) -> Found:+ """``(value, source)`` for a non-blank *value*, else ``None``."""+ text = _clean(value)+ return (text, source) if text else None+++@dataclass(frozen=True, slots=True)+class _Layer:+ """One configured layer: what it names, and the label each field reports."""++ source: str+ provider: str | None+ model: str | None+ base_url: str | None = None+ provider_source: str | None = None+ model_source: str | None = None++ def names(self, chosen: str) -> bool:+ """Whether this layer's model and URL belong to *chosen*."""+ return self.provider is None or self.provider == chosen+++@dataclass(frozen=True, slots=True)+class _Context:+ """Everything one resolution reads, gathered once."""++ override: _Layer+ repo: _Layer+ glob: _Layer+ env: _Layer+ repo_config: Mapping[str, Any]+ global_config: Mapping[str, Any]+ getenv: EnvLookup+ known: Collection[str] | None++ @property+ def layers(self) -> tuple[_Layer, ...]:+ return (self.override, self.repo, self.glob, self.env)++ def counts(self, name: str | None) -> bool:+ return bool(name) and (self.known is None or name in self.known)+++def _context(+ repo_path: Path | str | None,+ override: _Layer,+ known: Collection[str] | None,+ repo_layer: Mapping[str, Any] | None,+) -> _Context:+ getenv = repo_getenv(repo_path)+ if repo_layer is not None and repo_path is None:+ cfg, repo_source = repo_layer, GLOBAL_CONFIG_FILENAME+ else:+ cfg, repo_source = read_repo_config(repo_path), "config.yaml"+ glob = read_global_config()+ return _Context(+ override=override,+ repo=_Layer(repo_source, _clean(cfg.get("provider")), _clean(cfg.get("model"))),+ glob=_Layer(+ "global",+ _clean(glob.get("active_provider")),+ _clean(glob.get("active_model")),+ _clean(glob.get("active_base_url")),+ ),+ env=_Layer(+ "env",+ getenv("REPOWISE_PROVIDER"),+ getenv("REPOWISE_MODEL"),+ provider_source="env:REPOWISE_PROVIDER",+ model_source="env:REPOWISE_MODEL",+ ),+ repo_config=cfg,+ global_config=glob,+ getenv=getenv,+ known=known,+ )+++def resolve_llm(+ repo_path: Path | str | None = None,+ *,+ provider: str | None = None,+ model: str | None = None,+ base_url: str | None = None,+ override_source: str = "flag",+ known: Collection[str] | None = None,+ autodetect: bool = True,+ repo_layer: Mapping[str, Any] | None = None,+) -> LLMSelection:+ """Resolve the provider, model and base URL for *repo_path*.++ ``provider`` / ``model`` / ``base_url`` are the explicit choice, labelled+ ``override_source``. A model only applies to the provider it was chosen+ with: a layer naming a different provider contributes nothing, so a flag+ switching provider never inherits the repo's model for another provider.+ ``known`` limits which provider names count (the server's catalog), and+ ``autodetect=False`` stops at the configured layers. ``repo_layer`` stands+ in for ``config.yaml`` for a repo with no checkout to hold one (the+ server's stored choice for it), labelled ``provider_config.json``.+ """+ override = _Layer(override_source, _clean(provider), _clean(model), _clean(base_url))+ ctx = _context(repo_path, override, known, repo_layer)+ chosen, chosen_source = first_found(_provider_steps(ctx, autodetect))+ if chosen is None:+ return LLMSelection()+ resolved_model, model_source = first_found(_model_steps(ctx, chosen))+ resolved_url, url_source = first_found(_base_url_steps(ctx, chosen))+ return LLMSelection(+ provider=chosen,+ model=resolved_model,+ base_url=resolved_url,+ provider_source=chosen_source,+ model_source=model_source,+ base_url_source=url_source,+ )+++def _provider_steps(ctx: _Context, autodetect: bool) -> list[Step]:+ steps: list[Step] = [+ lambda layer=layer: (+ found(layer.provider, layer.provider_source or layer.source)+ if ctx.counts(layer.provider)+ else None+ )+ for layer in ctx.layers+ ]+ if autodetect:+ steps.append(lambda: found(_autodetect(ctx), "autodetect"))+ return steps+++def _model_steps(ctx: _Context, chosen: str) -> list[Step]:+ steps: list[Step] = [+ lambda layer=layer: (+ found(layer.model, layer.model_source or layer.source) if layer.names(chosen) else None+ )+ for layer in ctx.layers+ ]+ spec = PROVIDER_SPECS.get(chosen)+ steps.append(lambda: found(spec.default_model, "default") if spec else None)+ return steps+++def _base_url_steps(ctx: _Context, chosen: str) -> list[Step]:+ section = ctx.repo_config.get(chosen)+ repo_url = section.get("base_url") if isinstance(section, Mapping) else None+ steps: list[Step] = [+ lambda: (+ found(ctx.override.base_url, ctx.override.source)+ if ctx.override.names(chosen)+ else None+ ),+ lambda: found(repo_url, ctx.repo.source),+ lambda: found(ctx.glob.base_url, "global") if ctx.glob.provider == chosen else None,+ ]+ steps.extend(+ lambda var=var: found(ctx.getenv(var), f"env:{var}")+ for var in PROVIDER_BASE_URL_ENVS.get(chosen, ())+ )+ return steps+++def _autodetect(ctx: _Context) -> str | None:+ keys = ctx.global_config.get("keys")+ stored = keys if isinstance(keys, Mapping) else {}+ for name in PROVIDER_AUTODETECT_ORDER:+ if not ctx.counts(name):+ continue+ if provider_credentials_present(name, ctx.getenv) or _clean(stored.get(name)):+ return name+ return None+++def resolve_api_key(+ provider: str, repo_path: Path | str | None = None+) -> tuple[str | None, str | None]:+ """``(key, source)``: process env > repo ``.repowise/.env`` > stored key."""+ env_vars = PROVIDER_API_KEY_ENVS.get(provider, ())+ for var in env_vars:+ value = _clean(os.environ.get(var))+ if value:+ return value, f"env:{var}"+ overlay = read_repo_env(repo_path)+ for var in env_vars:+ value = _clean(overlay.get(var))+ if value:+ return value, ".repowise/.env"+ keys = read_global_config().get("keys")+ value = _clean(keys.get(provider)) if isinstance(keys, Mapping) else None+ if value:+ return value, GLOBAL_CONFIG_FILENAME+ return None, None+++def provider_ready(provider: str, repo_path: Path | str | None = None) -> bool:+ """Whether *provider* has what it needs, counting stored keys too."""+ return provider_is_usable(provider, repo_getenv(repo_path)) or bool(+ resolve_api_key(provider, repo_path)[0]+ )+++def llm_provider_kwargs(+ selection: LLMSelection, repo_path: Path | str | None = None+) -> dict[str, Any]:+ """Constructor kwargs for *selection*: model, key, base URL, repo path."""+ if not selection.provider:+ raise ValueError("No provider to build")+ # The registry still owns the name -> repo_path mapping; key and URL come+ # from the chains above, so its env reads are switched off.+ kwargs = provider_kwargs(+ selection.provider,+ model=selection.model,+ repo_path=repo_path,+ getenv=lambda _name: None,+ )+ api_key, key_source = resolve_api_key(selection.provider, repo_path)+ if api_key:+ kwargs["api_key"] = api_key+ if selection.base_url:+ if selection.base_url_source == "config.yaml":+ _check_repo_base_url(selection, repo_path, key_source)+ kwargs["base_url"] = selection.base_url+ return kwargs+++class UntrustedBaseUrlError(ValueError):+ """A committed ``config.yaml`` points a key from elsewhere at an unconfirmed host."""+++def _check_repo_base_url(+ selection: LLMSelection, repo_path: Path | str | None, key_source: str | None+) -> None:+ """Refuse to send a key to a ``config.yaml`` base URL nobody here confirmed.++ ``config.yaml`` can be committed, so a cloned repo could otherwise redirect+ the user's exported or stored key to any host. Allowed: no key at all, a+ key from this repo's own ``.env``, a loopback host, or a URL the user set+ through the web UI or ``repowise init`` on this machine.+ """+ url = selection.base_url or ""+ try:+ validate_base_url(url)+ except ValueError as exc:+ raise ValueError(+ f"{selection.provider} base_url in .repowise/config.yaml: {exc}"+ ) from None+ if key_source is None or key_source == ".repowise/.env":+ return+ if _is_loopback(url) or base_url_trusted(repo_path, url):+ return+ raise UntrustedBaseUrlError(+ f"This repo's .repowise/config.yaml sends {selection.provider} requests to "+ f"{selection.display_base_url}, which has not been confirmed on this machine, so "+ "your API key was not sent there. Confirm the URL in Settings or with "+ "`repowise init`, or put the key in the repo's .repowise/.env."+ )+++def _is_loopback(url: str) -> bool:+ host = (urlparse(url).hostname or "").lower()+ if host == "localhost" or host.endswith(".localhost"):+ return True+ try:+ return ipaddress.ip_address(host).is_loopback+ except ValueError:+ return False+++def without_credentials(url: str) -> str:+ """*url* with any ``user:password@`` removed, for display and errors."""+ parsed = urlparse(url)+ if not (parsed.username or parsed.password):+ return url+ host = parsed.hostname or ""+ netloc = f"{host}:{parsed.port}" if parsed.port else host+ return parsed._replace(netloc=netloc).geturl()+++# ---------------------------------------------------------------------------+# Writing a repo's selection+# ---------------------------------------------------------------------------++#: "Leave this field as it is", distinct from ``None`` (clear it).+UNSET: Any = object()+++def validate_base_url(value: str | None) -> str | None:+ """A trimmed ``http(s)://host...`` URL without credentials, or ``None`` for empty."""+ text = _clean(value)+ if text is None:+ return None+ parsed = urlparse(text)+ if parsed.username or parsed.password:+ raise ValueError(+ "Base URL must not contain a user name or password. "+ "Save the API key in Settings or .repowise/.env instead."+ )+ if parsed.scheme not in ("http", "https") or not parsed.hostname:+ raise ValueError(+ "Base URL must start with http:// or https:// and name a host, "+ f"got {without_credentials(text)!r}"+ )+ return text+++def apply_llm_selection(+ config: dict[str, Any],+ provider: str,+ model: str | None,+ base_url: Any = UNSET,+) -> dict[str, Any]:+ """Set provider/model (and optionally ``<provider>.base_url``) in *config*.++ ``model=None`` removes the key so the provider's default applies. Leaving+ ``base_url`` out keeps the section as it is; ``None`` or ``""`` clears it.+ """+ config["provider"] = provider+ if model:+ config["model"] = model+ else:+ config.pop("model", None)+ if base_url is not UNSET:+ current = config.get(provider)+ section = dict(current) if isinstance(current, Mapping) else {}+ if base_url:+ section["base_url"] = base_url+ else:+ section.pop("base_url", None)+ if section:+ config[provider] = section+ else:+ config.pop(provider, None)+ return config+++def save_repo_llm_selection(+ repo_path: Path | str,+ provider: str,+ model: str | None,+ base_url: Any = UNSET,+) -> None:+ """Persist a selection into ``.repowise/config.yaml``, keeping other keys.++ A broken file raises :class:`~repowise.core.repo_config.RepoConfigError`+ and is left untouched, never overwritten with only these keys.+ """+ from repowise.core.repo_config import load_repo_config, save_repo_config++ config = load_repo_config(repo_path)+ save_repo_config(repo_path, apply_llm_selection(config, provider, model, base_url))+++__all__ = [+ "UNSET",+ "LLMSelection",+ "UntrustedBaseUrlError",+ "apply_llm_selection",+ "base_url_trusted",+ "cached_read",+ "clear_cache",+ "first_found",+ "forget_cached",+ "found",+ "global_config_path",+ "llm_provider_kwargs",+ "provider_ready",+ "read_global_config",+ "read_repo_config",+ "read_repo_env",+ "repo_getenv",+ "resolve_api_key",+ "resolve_llm",+ "save_repo_llm_selection",+ "trust_base_url",+ "update_global_config",+ "validate_base_url",+ "without_credentials",+]diff --git a/packages/core/src/repowise/core/repo_config.py b/packages/core/src/repowise/core/repo_config.pyindex 27ef1cc2f..7c01e7363 100644--- a/packages/core/src/repowise/core/repo_config.py+++ b/packages/core/src/repowise/core/repo_config.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport contextlibimport hashlibimport json+import sysfrom pathlib import Pathfrom typing import Any@@ -44,6 +45,20 @@ CONFIG_DEPENDENCY_KEYS: dict[str, frozenset[str]] = {}+def _dependency_keys() -> dict[str, frozenset[str]]:+ """:data:`CONFIG_DEPENDENCY_KEYS` plus the per-provider endpoint sections.++ ``openai: {base_url: ...}`` says where requests go, not what a page says,+ so moving an endpoint (the web UI's base URL field) must not rebuild the+ index. Imported here, not at module load: this file is on the hook path.+ """+ from repowise.core.providers.llm.specs import PROVIDER_SPECS++ keys = dict(CONFIG_DEPENDENCY_KEYS)+ keys["state_only"] = keys["state_only"] | frozenset(PROVIDER_SPECS)+ return keys++class RepoConfigError(ValueError):"""A repo-local ``.repowise/config.yaml`` or ``.env`` could not be parsed.@@ -117,6 +132,8 @@ def save_repo_config(repo_path: Path | str, config: dict[str, Any]) -> None:import yaml # type: ignore[import-untyped]+ from repowise.core.fsutils import replace_with_retry+cfg_dir = get_repowise_dir(repo_path)cfg_dir.mkdir(parents=True, exist_ok=True)target = cfg_dir / CONFIG_FILENAME@@ -131,11 +148,17 @@ def save_repo_config(repo_path: Path | str, config: dict[str, Any]) -> None:handle.write(payload)handle.flush()os.fsync(handle.fileno())- os.replace(tmp_name, target)+ replace_with_retry(tmp_name, target)except BaseException:with contextlib.suppress(OSError):os.unlink(tmp_name)raise+ # Drop the resolver's parsed copy. Looked up, not imported: when the+ # resolver was never loaded there is no cache, and importing it here would+ # pull the provider stack into every config write.+ resolver = sys.modules.get("repowise.core.providers.llm.resolve")+ if resolver is not None:+ resolver.forget_cached(target)def config_fingerprint(repo_path: Path | str) -> str:@@ -185,10 +208,11 @@ def config_dependency_fingerprints("""if config is None:config = load_repo_config(repo_path)- known = set().union(*CONFIG_DEPENDENCY_KEYS.values())+ dependency_keys = _dependency_keys()+ known = set().union(*dependency_keys.values())grouped: dict[str, Any] = {name: {key: config[key] for key in sorted(keys) if key in config}- for name, keys in CONFIG_DEPENDENCY_KEYS.items()+ for name, keys in dependency_keys.items()}grouped["other"] = {key: config[key] for key in sorted(config) if key not in known}diff --git a/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md b/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.mdindex 61d738226..e018265f8 100644--- a/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md+++ b/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md@@ -9,6 +9,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0---+## [Unreleased]++### Changed++- **One provider order everywhere.** The CLI, `repowise serve` chat and jobs, and the MCP server now resolve provider, model and base URL as flag or UI choice, then `.repowise/config.yaml`, then the web UI's global default, then `REPOWISE_PROVIDER` / `REPOWISE_MODEL`, so `config.yaml` now wins over those env vars in the CLI. Choosing a model or base URL for a repo in the web UI writes that repo's `config.yaml`, which makes switching models on a local OpenAI-compatible server such as LM Studio a single edit. A base URL in `config.yaml` now beats `OPENAI_BASE_URL` and the other `*_BASE_URL` variables. The default provider and model saved in the web UI settings now also apply to CLI runs in repos whose `config.yaml` names none. A `config.yaml` base URL receives an API key from outside that repo's `.repowise/.env` only when it is a local address or was confirmed in Settings or with `repowise init`.+## [0.56.0] - 2026-10-12repowise 0.56 hands agents the exact thing they need to act on. Search returns matching source lines and finds every file in the repository, `get_context` lists every edit site of a symbol verified against live files, caller rows carry the calling line, and `repowise update --working-tree` brings uncommitted work into the index in seconds. `repowise impacted-tests` selects a targeted subset on far more changes, with `--prioritize` and `--explain`.diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.pyindex fe0ec5ff4..b311d6023 100644--- a/packages/server/src/repowise/server/app.py+++ b/packages/server/src/repowise/server/app.py@@ -17,7 +17,6 @@ limit_blas_threads()# ruff: noqa: E402 — the BLAS pin above is only effective before these run.import loggingimport os-import sysfrom collections.abc import AsyncGeneratorfrom contextlib import asynccontextmanager, suppress@@ -89,63 +88,24 @@ from repowise.server.workspace_startup import (logger = logging.getLogger(__name__)-def _gemini_embedder():- from repowise.core.providers.embedding.gemini import GeminiEmbedder-- dims_raw = os.environ.get("REPOWISE_EMBEDDING_DIMS")- dims = 768- if dims_raw:- try:- parsed = int(dims_raw)- except (ValueError, OverflowError):- parsed = 0- if parsed > 0:- dims = parsed- else:- print(- f"REPOWISE_EMBEDDING_DIMS={dims_raw!r} is not a positive integer; using {dims}.",- file=sys.stderr,- )- # Honour the indexed embedding model so serve doesn't silently rebuild- # the embedder with a different default than init used (issue #426).- model = os.environ.get("REPOWISE_EMBEDDING_MODEL")- if model:- return GeminiEmbedder(model=model, output_dimensionality=dims)- return GeminiEmbedder(output_dimensionality=dims)--def _build_embedder():- """Build an embedder from REPOWISE_EMBEDDER env var (default: mock).-- Supported values:- mock — deterministic 8-dim SHA-256 embedder (default, no API key needed)- gemini — GeminiEmbedder via GEMINI_API_KEY / GOOGLE_API_KEY env var- openai — OpenAIEmbedder via OPENAI_API_KEY env var- openrouter — OpenRouterEmbedder via OPENROUTER_API_KEY env var- edenai — EdenAIEmbedder via EDENAI_API_KEY env var+ """Build the server's embedder from ``REPOWISE_EMBEDDER`` (default: mock).++ Name, credential and kwargs come from the resolver the CLI and the MCP+ server share, so every registered embedder works here, including custom+ ones. ``repowise serve`` seeds ``REPOWISE_EMBEDDER`` and+ ``REPOWISE_EMBEDDING_MODEL`` from the repo's pin before startup, so the+ query vectors match the index."""- name = os.environ.get("REPOWISE_EMBEDDER", DEFAULT_EMBEDDER).lower()- if name == "ollama":- from repowise.core.providers.embedding.ollama import OllamaEmbedder-- return OllamaEmbedder()- if name == "gemini":- return _gemini_embedder()- if name == "openai":- from repowise.core.providers.embedding.openai import OpenAIEmbedder-- model = os.environ.get("REPOWISE_EMBEDDING_MODEL", "text-embedding-3-small")- return OpenAIEmbedder(model=model)- if name == "openrouter":- from repowise.core.providers.embedding.openrouter import OpenRouterEmbedder-- model = os.environ.get("REPOWISE_EMBEDDING_MODEL", "google/gemini-embedding-001")- return OpenRouterEmbedder(model=model)- if name == "edenai":- from repowise.core.providers.embedding.edenai import EdenAIEmbedder-- model = os.environ.get("REPOWISE_EMBEDDING_MODEL", "amazon/amazon.titan-embed-text-v2:0")- return EdenAIEmbedder(model=model)+ from repowise.core.providers.embedding import get_embedder, list_embedders+ from repowise.core.providers.embedding.resolve import (+ embedder_kwargs,+ resolve_embedder_name,+ )++ name, _source = resolve_embedder_name(detect=False)+ if name in list_embedders() and name != DEFAULT_EMBEDDER:+ return get_embedder(name, **embedder_kwargs(name))logger.warning("embedder.mock_active: set REPOWISE_EMBEDDER=gemini, openai, openrouter, ""ollama, or edenai for real RAG"diff --git a/packages/server/src/repowise/server/mcp_server/_server.py b/packages/server/src/repowise/server/mcp_server/_server.pyindex 17a60f5d1..fb34351f6 100644--- a/packages/server/src/repowise/server/mcp_server/_server.py+++ b/packages/server/src/repowise/server/mcp_server/_server.py@@ -5,7 +5,6 @@ from __future__ import annotationsimport asyncioimport contextlibimport os-import sysfrom contextlib import asynccontextmanagerfrom typing import Any, NoReturn@@ -85,161 +84,39 @@ _EMBEDDER_REMEDIATION: dict[str, str] = {def _configured_embedder_name() -> str:- """Read the configured embedder name from env or ``.repowise/config.yaml``.+ """The configured embedder: ``REPOWISE_EMBEDDER``, then the repo's pin.Returns a lowercased name, or ``""`` when nothing is explicitly configured(in which case MockEmbedder is the intended default, not a degradation).+ No key detection: the server must query with the backend that wrote the+ index, not one guessed from the environment."""- name = os.environ.get("REPOWISE_EMBEDDER", "").strip().lower()- if name:- return name- if _state._repo_path:- try:- from pathlib import Path+ from repowise.core.providers.embedding.resolve import resolve_embedder_name- cfg_path = Path(_state._repo_path) / ".repowise" / "config.yaml"- if cfg_path.exists():- import yaml # type: ignore[import-untyped]-- cfg = yaml.safe_load(cfg_path.read_text(encoding="utf-8")) or {}- return (cfg.get("embedder") or "").strip().lower()- except Exception:- _log.debug("Failed to read embedder from config.yaml", exc_info=True)- return ""---# Keyed embedders and the env vars each reads its credential from. The first-# entry is the canonical name the CLI persists under; the rest are accepted-# aliases. Embedders outside this map (ollama, mock, custom) need no API key.-_EMBEDDER_KEY_ENV: dict[str, tuple[str, ...]] = {- "openai": ("OPENAI_API_KEY",),- "gemini": ("GEMINI_API_KEY", "GOOGLE_API_KEY"),- "openrouter": ("OPENROUTER_API_KEY",),- "edenai": ("EDENAI_API_KEY",),-}+ name, source = resolve_embedder_name(repo_path=_state._repo_path or None, detect=False)+ return "" if source == "default" else namedef _persisted_embedder_key(name: str) -> str | None:- """Recover the configured embedder's API key from where the CLI persists it.-- ``repowise mcp`` loads ``<repo>/.repowise/.env`` before starting, but that- covers only the repo it was pointed at: a workspace serves sibling repos- whose ``.env`` is never read, and embedded callers reach :func:`run_mcp`- without going through the CLI at all. ``repowise serve`` already falls back- to the ``embedder_api_key`` saved in ``~/.repowise/config.yaml``. Without- the same fallback here the server builds a ``MockEmbedder`` and queries a- real index with vectors that cannot match it — semantic search silently- degrades to full-text-only.-- Order: the served repo's ``.repowise/.env`` first, then the global config.- Returns ``None`` when the embedder needs no key or none is persisted.+ """The configured embedder's API key: env > repo ``.env`` > global config.++ ``repowise mcp`` loads ``<repo>/.repowise/.env`` before starting, but a+ workspace serves sibling repos whose ``.env`` is never read, and embedded+ callers reach :func:`run_mcp` without the CLI at all. Without the+ fallbacks the server builds a ``MockEmbedder`` and queries a real index+ with vectors that cannot match it. ``None`` when the embedder needs no key+ or none is persisted."""- from pathlib import Path+ from repowise.core.providers.embedding.resolve import resolve_embedder_key- env_vars = _EMBEDDER_KEY_ENV.get(name)- if not env_vars:- return None- canonical = env_vars[0]-- # The process environment is the highest-precedence source, matching the- # CLI's resolver (cli/providers/keys.py): an exported key is an explicit- # override. The server used to skip this tier entirely, so on a machine- # with an exported credential it and the CLI disagreed about the same- # repo in the same shell (issue #1711).- for var in env_vars:- value = os.environ.get(var)- if value:- return value-- if _state._repo_path:- try:- # Reuse the reader get_answer already uses for the LLM credential,- # rather than a third copy of .env parsing.- from repowise.server.mcp_server.tool_answer.synthesis import (- _load_repo_provider_config,- )-- _, _, overlay = _load_repo_provider_config(Path(_state._repo_path))- for var in env_vars:- if overlay.get(var):- return overlay[var]- except Exception:- _log.debug("Failed to read repo .env for embedder key", exc_info=True)-- try:- cfg_path = Path.home() / ".repowise" / "config.yaml"- if cfg_path.is_file():- import yaml # type: ignore[import-untyped]-- cfg = yaml.safe_load(cfg_path.read_text(encoding="utf-8")) or {}- # Only honour the saved key when it belongs to the embedder being- # resolved — handing an openai key to gemini fails confusingly.- if (cfg.get("embedder") or "").strip().lower() == name:- key = str(cfg.get("embedder_api_key") or "").strip()- if key:- _log.info(- "Embedder key for '%s' recovered from ~/.repowise/config.yaml "- "(%s not set in the MCP server's environment).",- name,- canonical,- )- return key- except Exception:- _log.debug("Failed to read global config for embedder key", exc_info=True)-- return None+ return resolve_embedder_key(name, _state._repo_path or None).keydef _embedder_kwargs(name: str) -> dict[str, Any]:- """Map repowise embedding env vars onto an embedder's constructor kwargs.-- Kept backend-agnostic: ``REPOWISE_EMBEDDING_MODEL`` applies to any embedder- that accepts a ``model`` arg. ``REPOWISE_EMBEDDING_DIMS`` is read directly by- the openai and ollama embedders in their own constructors; only gemini needs- it mapped here, because its constructor spells the width- ``output_dimensionality``. Anything not set here falls through to the- embedder's own defaults.-- When the embedder needs an API key and the environment has none, the key is- recovered from the repo/global config so the server matches the index it- was pointed at instead of falling back to mock vectors.- """- kwargs: dict[str, Any] = {}- model = os.environ.get("REPOWISE_EMBEDDING_MODEL")- if model:- kwargs["model"] = model- if name == "gemini":- dims_raw = os.environ.get("REPOWISE_EMBEDDING_DIMS")- dims = 768- if dims_raw:- try:- parsed = int(dims_raw)- except (ValueError, OverflowError):- parsed = 0- if parsed > 0:- dims = parsed- else:- _log.warning(- "embedding_dims_invalid",- extra={- "var": "REPOWISE_EMBEDDING_DIMS",- "value": dims_raw,- "using": dims,- },- )- print(- f"REPOWISE_EMBEDDING_DIMS={dims_raw!r} is not a positive integer;"- f" using {dims}.",- file=sys.stderr,- )- kwargs["output_dimensionality"] = dims-- env_vars = _EMBEDDER_KEY_ENV.get(name, ())- if env_vars and not any(os.environ.get(var) for var in env_vars):- key = _persisted_embedder_key(name)- if key:- kwargs["api_key"] = key- return kwargs+ """Constructor kwargs for *name*, from the resolver the CLI shares."""+ from repowise.core.providers.embedding.resolve import embedder_kwargs++ return embedder_kwargs(name, _state._repo_path or None)def _resolve_embedder():diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/synthesis.py b/packages/server/src/repowise/server/mcp_server/tool_answer/synthesis.pyindex 182f25465..f806a6b86 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/synthesis.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/synthesis.py@@ -100,158 +100,81 @@ def _synthesis_reasoning_and_budget(return effective, _SYNTHESIS_REASONING_MAX_TOKENS-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, {}-- config_path = repo_path / ".repowise" / "config.yaml"- 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] = {}-- # config.yaml first: it is the user-editable intent. state.json only- # records what the LAST index run used, which goes stale the moment the- # user switches providers (observed: a config saying openai while- # state.json still said gemini from a months-old index build — resolution- # followed state.json into a keyless provider and synthesis went dark).- try:- if config_path.is_file():- import yaml-- data = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}- if isinstance(data, dict):- name = data.get("provider") or None- model = data.get("model") or None- except Exception:- _log.debug("Failed to read %s", config_path, exc_info=True)-- try:- if state_path.is_file():- data = _json.loads(state_path.read_text(encoding="utf-8"))- name = name or data.get("provider") or None- model = model or 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):+ """The provider get_answer synthesises with, or None when none can be built.+ Resolution is the shared one (``repowise.core.providers.llm.resolve``), so+ get_answer uses the same provider and model as ``repowise update`` for the+ repo, reading its ``config.yaml`` and ``.env`` without a separate config.+ ``REPOWISE_DOC_MODEL`` overrides the model for synthesis only.-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, but shares that- function's env-var mapping (``repowise.core.providers.llm.registry``) so- the two cannot drift apart. Returns a BaseProvider or None if no API key /- provider is configured.-- Resolution order: process env vars first, then ``.repowise/config.yaml``- / ``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.+ A configured provider whose key is absent must not end resolution:+ returning None there made get_answer drop silently to retrieval-only mode+ while another provider's key sat in the environment. It falls through to+ auto-detection instead."""try:from repowise.core.providers.llm.registry import (PROVIDER_AUTODETECT_ORDER,get_provider,provider_credentials_present,- provider_is_usable,- provider_kwargs,+ )+ from repowise.core.providers.llm.resolve import (+ llm_provider_kwargs,+ provider_ready,+ repo_getenv,+ resolve_api_key,+ resolve_llm,)except Exception:_log.warning("Provider registry import failed", exc_info=True)return None- persisted_name, persisted_model, env_overlay = _load_repo_provider_config(repo_path)+ doc_model = (os.environ.get("REPOWISE_DOC_MODEL") or "").strip() or None- 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, provider_model: str | None):- kwargs = provider_kwargs(- provider_name,- model=provider_model,- repo_path=repo_path,- getenv=_env,+ def _build(provider_name: str | None = None):+ selection = resolve_llm(+ repo_path,+ provider=provider_name,+ model=doc_model,+ override_source="env:REPOWISE_DOC_MODEL",+ autodetect=False,)+ if selection.provider is None:+ return None, None+ if not provider_ready(selection.provider, repo_path):+ return None, selection.providertry:- return get_provider(provider_name, **kwargs)+ kwargs = llm_provider_kwargs(selection, repo_path)+ return get_provider(selection.provider, **kwargs), selection.providerexcept Exception:- _log.warning("get_provider(%s) failed", provider_name, exc_info=True)- return None-- # Explicit selection wins — when its key is actually available. A- # configured/persisted provider whose key is absent must NOT end- # resolution: returning None here made get_answer silently drop to- # retrieval-only mode even though another provider's key sat in the env- # (the auto-detect below was unreachable). Fall through instead, and- # drop the persisted model on the way down — it belongs to the named- # provider and would break a cross-provider fallback call.+ _log.warning("get_provider(%s) failed", selection.provider, exc_info=True)+ return None, selection.provider++ provider, name = _build()+ if provider is not None:+ return providerif name:- if provider_is_usable(name, _env):- provider = _try(name, model)- if provider is not None:- return provider_log.warning("Configured provider %r has no usable key/setup; falling back to ""auto-detection from available API keys.",name,)- if not (os.environ.get("REPOWISE_DOC_MODEL") or os.environ.get("REPOWISE_MODEL")):- model = None # persisted model was provider-specific- # Auto-detect from whatever credentials the environment carries. Only the- # keyed providers participate: a keyless one is "usable" everywhere, so+ # Auto-detect from whatever credentials are present. Only the keyed+ # providers participate: a keyless one is "usable" everywhere, so# auto-detecting it would hijack every repo that never configured it.+ getenv = repo_getenv(repo_path)for candidate in PROVIDER_AUTODETECT_ORDER:if candidate == name:- # Already attempted above with the same credentials. Retrying it- # here only differs in dropping the model, which cannot fix the- # reasons construction fails (a missing SDK, a rejected key), and- # it costs the next candidate its turn.+ # Already attempted above with the same credentials.continue- if not provider_credentials_present(candidate, _env):+ if not (+ provider_credentials_present(candidate, getenv)+ or resolve_api_key(candidate, repo_path)[0]+ ):continue- provider = _try(candidate, model)+ provider, _ = _build(candidate)if provider is not None:return providerreturn Nonediff --git a/packages/server/src/repowise/server/provider_config.py b/packages/server/src/repowise/server/provider_config.pyindex 35eeb7dbe..ccce3987f 100644--- a/packages/server/src/repowise/server/provider_config.py+++ b/packages/server/src/repowise/server/provider_config.py@@ -1,31 +1,31 @@-"""Provider configuration management — API keys, active provider, model selection.--Stores configuration in a server-side JSON file (``_config_path``). Two-resolution chains run here, both most-specific-first:--**API key** (:func:`_get_key_for_provider`):- 1. process environment (``ANTHROPIC_API_KEY`` etc.)- 2. the target repo's ``.repowise/.env`` (read into a dict, never applied to- ``os.environ``, so one repo's key can't leak into another in workspace- mode)- 3. the server-global stored key set through :func:`set_api_key`--**Active provider/model** (:func:`_resolve_active_for_repo`): per-repo UI-selection > the repo's ``config.yaml`` > server-global active selection >-``REPOWISE_PROVIDER`` / ``REPOWISE_MODEL`` env > auto-detect the first provider-with a usable key. See that function's docstring for the full rationale.--Because the CLI resolves keys from ``.repowise/.env`` (step 2) and never sees-the server store, :func:`set_api_key` mirrors a UI-added key into that file so a-later CLI run in the repo picks it up.+"""Provider configuration for the web UI: catalog, keys, active selection.++Resolution itself lives in :mod:`repowise.core.providers.llm.resolve`, shared+with the CLI and the MCP server, so a repo resolves the same way everywhere:+explicit request override > the repo's ``config.yaml`` > the global default+here > ``REPOWISE_PROVIDER`` / ``REPOWISE_MODEL`` > spec default or+auto-detection. API keys: process env > the repo's ``.repowise/.env`` > keys+stored here.++This module owns the server-side JSON file (``provider_config.json``): API+keys and the global default (``active_provider`` / ``active_model`` /+``active_base_url``). A repo's own choice is written to that repo's+``.repowise/config.yaml`` through the same core writer the CLI uses. Older+servers kept it here under ``repos[repo_id]``; :func:`_migrate_repo_selection`+moves such an entry into the repo's file the first time the repo is resolved.++Because the CLI resolves keys from ``.repowise/.env`` first, :func:`set_api_key`+mirrors a UI-added key into that file too."""from __future__ import annotations-import contextlibimport jsonimport loggingimport os+import threading+from collections.abc import Mapping+from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any@@ -34,14 +34,30 @@ from repowise.core.providers.embedding.registry import (KEYLESS_EMBEDDERS,list_embedders,)+from repowise.core.providers.llm.resolve import (+ UNSET,+ LLMSelection,+ global_config_path,+ read_global_config,+ read_repo_config,+ resolve_api_key,+ resolve_llm,+ save_repo_llm_selection,+ trust_base_url,+ update_global_config,+ validate_base_url,+)from repowise.core.providers.llm.specs import PROVIDER_SPECSlogger = logging.getLogger(__name__)+# One migration at a time: two first requests for the same repo must not both+# write its config.yaml and state.json.+_migration_lock = threading.Lock()+# ---------------------------------------------------------------------------# Provider catalog, derived from the provider specs. Flag-only providers-# (mock) are left out. Order matters: auto-detect below takes the first entry-# that is usable.+# (mock) are left out.# ---------------------------------------------------------------------------PROVIDER_CATALOG: list[dict[str, Any]] = [@@ -65,6 +81,14 @@ _CATALOG_BY_ID = {p["id"]: p for p in PROVIDER_CATALOG}FLAG_ONLY_PROVIDERS = [spec.name for spec in PROVIDER_SPECS.values() if spec.picker_rank is None]+class UnknownProviderError(ValueError):+ """A provider id outside the catalog."""+++class NoProviderConfiguredError(ValueError):+ """Nothing names a provider for this repo and no credentials were found."""++def _embedder_catalog() -> list[dict[str, Any]]:"""Every registered embedder, read at call time so custom ones appear.@@ -88,28 +112,13 @@ def _embedder_catalog() -> list[dict[str, Any]]:def _config_path() -> Path:- """Return the server's provider-config JSON path.-- ``REPOWISE_CONFIG_DIR`` wins when set; otherwise the file lives in the- per-user ``~/.repowise`` config directory (the same home the CLI's global- store and the default database use). The previous CWD-relative fallback- meant a key was saved next to wherever the server happened to be launched- and then invisible from any other working directory.- """- config_dir = os.environ.get("REPOWISE_CONFIG_DIR", "")- if config_dir:- return Path(config_dir) / "provider_config.json"- return Path.home() / ".repowise" / "provider_config.json"+ """The server's ``provider_config.json`` (see ``global_config_path``)."""+ return global_config_path()def _load_config() -> dict[str, Any]:- path = _config_path()- if path.exists():- try:- return json.loads(path.read_text(encoding="utf-8"))- except Exception:- logger.warning("Failed to read provider config, using defaults")- return {}+ """A fresh copy of the stored config. Writes go through ``update_global_config``."""+ return json.loads(json.dumps(dict(read_global_config())))def _redact_key(text: str) -> str:@@ -121,213 +130,196 @@ def _redact_key(text: str) -> str:return re.sub(r"(sk-[A-Za-z0-9\-_]{4,})", "sk-***", text)-def _save_config(config: dict[str, Any]) -> None:- # Write-then-rename so a concurrent reader (or a second writer racing on- # the read-modify-write) never sees a half-written file or a truncated one.- # Keys are sensitive — ensure 0600 permissions (owner read/write only).- import os as _os-- path = _config_path()- path.parent.mkdir(parents=True, exist_ok=True)- tmp = path.with_suffix(f"{path.suffix}.tmp.{os.getpid()}")- tmp.write_text(json.dumps(config, indent=2), encoding="utf-8")- with contextlib.suppress(OSError):- _os.chmod(tmp, 0o600) # best-effort on platforms without chmod (e.g. Windows)- os.replace(tmp, path)- with contextlib.suppress(OSError):- _os.chmod(path, 0o600)--# ----------------------------------------------------------------------------# Public API+# Resolution# ----------------------------------------------------------------------------def _load_repo_context(repo_path: str | Path | None) -> tuple[dict[str, Any], dict[str, str]]:- """Load a repo's ``config.yaml`` dict and ``.env`` dict for resolution.+def _get_key_for_provider(provider_id: str, repo_path: str | Path | None = None) -> str | None:+ """The key chat would use: process env > repo ``.env`` > stored key."""+ if provider_id not in _CATALOG_BY_ID:+ return None+ return resolve_api_key(provider_id, repo_path)[0]- Returns ``({}, {})`` when no path is given so callers can resolve the- server-global configuration unchanged. The ``.env`` is read into a plain- dict (never ``os.environ``) so per-request, per-repo resolution can't leak- one repo's keys into another's in a long-lived workspace server.- """- if repo_path is None:- return {}, {}- from repowise.core.repo_config import RepoConfigError, load_repo_config, load_repo_env- try:- cfg = load_repo_config(repo_path)- except RepoConfigError:- # A broken config.yaml must surface, not silently resolve as defaults:- # the user's provider/model selection would vanish and chat would pick- # an auto-detected provider nobody configured. Name the repo so a- # workspace server points at the right one.- logger.warning("Repo config parse failed for %s; using defaults", repo_path)- cfg = {}- except Exception:- cfg = {}- try:- env = load_repo_env(repo_path)- except RepoConfigError:- logger.warning("Repo .env unreadable for %s; using environment only", repo_path)- env = {}- except Exception:- env = {}- return cfg, env---def _get_key_for_provider(provider_id: str, repo_env: dict[str, str] | None = None) -> str | None:- """Resolve an API key: process env > repo ``.env`` > stored server config.-- ``repo_env`` is the target repo's ``.repowise/.env`` (parsed, not applied- to ``os.environ``). Honouring it is what makes chat use the same key the- user supplied at ``repowise init`` time, even in workspace mode where the- server never loads any single repo's ``.env`` into its own environment.- """+def _provider_configured(provider_id: str, repo_path: str | Path | None = None) -> bool:+ """Whether chat can build ``provider_id``: it needs no key or has one."""catalog = _CATALOG_BY_ID.get(provider_id)- if not catalog:+ if catalog is None:+ return False+ return not catalog["requires_key"] or bool(_get_key_for_provider(provider_id, repo_path))+++def _legacy_selection(repo_id: str | None) -> Mapping[str, Any] | None:+ """The old server's stored ``repos[repo_id]`` choice, if one is left."""+ if not repo_id:return None+ repos = read_global_config().get("repos")+ selection = repos.get(repo_id) if isinstance(repos, Mapping) else None+ return selection if isinstance(selection, Mapping) else None- for env_key in catalog.get("env_keys", []):- val = os.environ.get(env_key)- if val:- return val- if repo_env:- for env_key in catalog.get("env_keys", []):- val = repo_env.get(env_key)- if val:- return val- config = _load_config()- keys = config.get("keys", {})- return keys.get(provider_id)+def _as_repo_layer(selection: Mapping[str, Any]) -> dict[str, Any]:+ """A legacy entry in ``config.yaml``'s shape, for a repo with no checkout."""+ provider = selection.get("provider")+ layer: dict[str, Any] = {"provider": provider, "model": selection.get("model")}+ if selection.get("base_url") and isinstance(provider, str):+ layer[provider] = {"base_url": selection["base_url"]}+ return layer-def _get_base_url_for_provider(- provider_id: str,- repo_env: dict[str, str] | None = None,- repo_cfg: dict[str, Any] | None = None,-) -> str | None:- """Resolve a provider base_url: process env > repo ``.env`` > repo config.-- Mirrors the CLI's resolution (``cli/helpers.resolve_provider``) so a- local LiteLLM/OpenAI-compatible endpoint configured at init is reused by- chat. The repo ``config.yaml`` may carry it under a per-provider section,- e.g. ``openai: {base_url: http://localhost:4000/v1}``.-- The env-var names come from the provider registry, the same table the CLI- and MCP resolvers read, so this cannot drift out of step with them.- """- from repowise.core.providers.llm.registry import PROVIDER_BASE_URL_ENVS-- env_vars = PROVIDER_BASE_URL_ENVS.get(provider_id, ())- for env_var in env_vars:- val = os.environ.get(env_var)- if val:- return val- if repo_env:- for env_var in env_vars:- val = repo_env.get(env_var)- if val:- return val- if repo_cfg:- section = repo_cfg.get(provider_id)- if isinstance(section, dict) and section.get("base_url"):- return str(section["base_url"])- return None---def _provider_configured(provider_id: str, repo_env: dict[str, str] | None = None) -> bool:- """Whether chat can build ``provider_id``: it needs no key or has one."""- catalog = _CATALOG_BY_ID.get(provider_id)- if catalog is None:- return False- return not catalog["requires_key"] or bool(_get_key_for_provider(provider_id, repo_env))+def _migrate_repo_selection(repo_id: str | None, repo_path: str | Path | None) -> None:+ """Move a legacy ``repos[repo_id]`` entry into the repo's ``config.yaml``.+ Written there (base URL included) only when the yaml names no provider;+ otherwise the yaml wins and the entry is dropped. A repo with no checkout+ keeps its entry, which the resolver then reads in place of the yaml. Once+ the entry is gone this is a dict lookup on the cached file.-def _resolve_active_for_repo(- repo_id: str | None,- repo_cfg: dict[str, Any],- repo_env: dict[str, str] | None = None,-) -> tuple[str | None, str | None]:- """Resolve the (provider, model) for a repo's chat, most specific first.-- Precedence:- 1. Per-repo UI selection persisted under ``repos[repo_id]`` — an- explicit override the user made for *this* repo. Stored per-repo so- selecting a model for one repo never shadows another's config (the- original bug behind issue #426).- 2. The repo's own ``config.yaml`` (``provider`` + ``model``) written by- ``repowise init`` — the seamless default.- 3. The server-global ``active_provider`` (legacy single-repo UI state).- 4. ``REPOWISE_PROVIDER`` / ``REPOWISE_MODEL`` env vars.- 5. Auto-detect the first provider with a usable key.+ The entry already chose the model for jobs started from the UI, so moving+ it is not a model change: state.json's fingerprints are carried over and+ the next ``repowise update`` does not regenerate because of it."""- config = _load_config()+ if repo_path is None or _legacy_selection(repo_id) is None:+ return+ with _migration_lock:+ selection = _legacy_selection(repo_id)+ if selection is None:+ return+ provider = selection.get("provider")+ if read_repo_config(repo_path).get("provider"):+ logger.info(+ "Dropped the stored chat selection for repo %s: its config.yaml already "+ "names a provider",+ repo_id,+ )+ elif provider not in _CATALOG_BY_ID:+ logger.warning(+ "Dropped the stored chat selection for repo %s: provider %r is not "+ "available on this server",+ repo_id,+ provider,+ )+ else:+ try:+ _write_migrated_selection(repo_path, selection)+ except (OSError, ValueError):+ logger.warning(+ "Could not move the stored chat selection for repo %s into %s/.repowise/"+ "config.yaml; keeping it for the next try",+ repo_id,+ repo_path,+ )+ return+ logger.info("Moved the stored chat selection for repo %s into config.yaml", repo_id)++ def drop(config: dict[str, Any]) -> None:+ stored = config.get("repos")+ if isinstance(stored, dict):+ stored.pop(repo_id, None)+ if not stored:+ config.pop("repos", None)++ update_global_config(drop)+++def _write_migrated_selection(repo_path: str | Path, selection: Mapping[str, Any]) -> None:+ from repowise.core.repo_config import config_dependency_fingerprints, config_fingerprint++ before = (config_fingerprint(repo_path), config_dependency_fingerprints(repo_path))+ base_url = validate_base_url(selection.get("base_url"))+ save_repo_llm_selection(+ repo_path,+ selection["provider"],+ selection.get("model"),+ base_url if base_url else UNSET,+ )+ if base_url:+ trust_base_url(repo_path, base_url)+ _carry_fingerprints(repo_path, before)- def _with_default(pid: str | None, model: str | None) -> tuple[str | None, str | None]:- if pid and not model:- model = _CATALOG_BY_ID.get(pid, {}).get("default_model")- return pid, model- # 1. Per-repo persisted selection- if repo_id:- repos = config.get("repos") or {}- sel = repos.get(repo_id)- if isinstance(sel, dict) and sel.get("provider") in _CATALOG_BY_ID:- return _with_default(sel["provider"], sel.get("model"))-- # 2. Repo config.yaml- cfg_provider = repo_cfg.get("provider")- if cfg_provider in _CATALOG_BY_ID:- return _with_default(cfg_provider, repo_cfg.get("model"))-- # 3. Server-global active selection- if config.get("active_provider") in _CATALOG_BY_ID:- return _with_default(config["active_provider"], config.get("active_model"))-- # 4. Environment- env_provider = os.environ.get("REPOWISE_PROVIDER")- if env_provider in _CATALOG_BY_ID:- return _with_default(env_provider, os.environ.get("REPOWISE_MODEL"))-- # 5. Auto-detect- for p in PROVIDER_CATALOG:- if _provider_configured(p["id"], repo_env):- return _with_default(p["id"], None)+def _carry_fingerprints(repo_path: str | Path, before: tuple[str, dict[str, str]]) -> None:+ """Move state.json's config fingerprints past the migration's own write.- return None, None+ Only a fingerprint that still matched the pre-migration config moves, so a+ real config change waiting for the next update is still seen.+ """+ from repowise.core.fsutils import atomic_write_text+ from repowise.core.repo_config import config_dependency_fingerprints, config_fingerprint++ state_path = Path(repo_path) / ".repowise" / "state.json"+ try:+ state = json.loads(state_path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return+ if not isinstance(state, dict):+ return+ old_fp, old_deps = before+ changed = False+ if state.get("config_fingerprint") == old_fp:+ state["config_fingerprint"] = config_fingerprint(repo_path)+ changed = True+ stored = state.get("config_dependency_fingerprints")+ if isinstance(stored, dict):+ for bucket, value in config_dependency_fingerprints(repo_path).items():+ if stored.get(bucket) == old_deps.get(bucket) and value != old_deps.get(bucket):+ stored[bucket] = value+ changed = True+ if changed:+ atomic_write_text(state_path, json.dumps(state, indent=2))+++def resolve_for_repo(+ repo_id: str | None = None,+ repo_path: str | Path | None = None,+ *,+ provider_override: str | None = None,+ model_override: str | None = None,+) -> LLMSelection:+ """The selection chat and jobs use for a repo, with provenance."""+ if provider_override and provider_override not in _CATALOG_BY_ID:+ raise UnknownProviderError(f"Unknown provider: {provider_override}")+ _migrate_repo_selection(repo_id, repo_path)+ legacy = _legacy_selection(repo_id) if repo_path is None else None+ return resolve_llm(+ repo_path,+ provider=provider_override,+ model=model_override,+ override_source="request",+ known=_CATALOG_BY_ID,+ repo_layer=_as_repo_layer(legacy) if legacy else None,+ )def list_provider_status(repo_id: str | None = None,repo_path: str | Path | None = None,) -> dict[str, Any]:- """Return provider catalog + the active selection for ``repo_id``.+ """Return provider catalog + the active selection for the repo.- When ``repo_path`` is given the active provider/model reflect that repo's- own configuration (so the UI's model picker shows what chat will actually- use), and a custom configured model not present in the static catalog is- surfaced in that provider's ``models`` list so it's selectable.+ With ``repo_path`` the active provider/model/base URL are what that repo's+ chat will use, each with the layer it came from (``provenance``). A+ configured model missing from the static catalog is added to that+ provider's ``models`` so the picker can show it."""- repo_cfg, repo_env = _load_repo_context(repo_path)- active_id, active_model = _resolve_active_for_repo(repo_id, repo_cfg, repo_env)+ selection = resolve_for_repo(repo_id, repo_path)+ active_id, model = selection.provider, selection.modelproviders = []for p in PROVIDER_CATALOG:- configured = _provider_configured(p["id"], repo_env)models = list(p["models"])# Surface a configured-but-not-cataloged model (e.g. a local LiteLLM# alias like ``gemma4``) so the picker can display the active choice.- if p["id"] == active_id and active_model and active_model not in models:- models.append(active_model)+ if p["id"] == active_id and model and model not in models:+ models.append(model)providers.append({"id": p["id"],"name": p["name"],"models": models,"default_model": p["default_model"],- "configured": configured,+ "configured": _provider_configured(p["id"], repo_path),"requires_key": p["requires_key"],"env_vars": p["env_vars"],"setup_hint": p["setup_hint"],@@ -337,9 +329,6 @@ def list_provider_status(# Deferred: the estimator package pulls in the generation pipeline.from repowise.core.cost_estimator import lookup_cost- model = active_model or (- _CATALOG_BY_ID.get(active_id, {}).get("default_model") if active_id else None- )rates = lookup_cost(model) if model else None# An unpriced model on a local provider costs nothing; anywhere else it# is unknown, and null rates make the dashboard show no estimate.@@ -351,6 +340,8 @@ def list_provider_status("active": {"provider": active_id,"model": model,+ "base_url": selection.display_base_url,+ "provenance": selection.provenance,"input_cost_per_1k": input_rate,"output_cost_per_1k": output_rate,"embedder": os.environ.get("REPOWISE_EMBEDDER", DEFAULT_EMBEDDER).lower(),@@ -366,8 +357,8 @@ def get_active_provider(repo_path: str | Path | None = None,) -> tuple[str | None, str | None]:"""Return (provider_id, model) for the active provider, optionally per-repo."""- repo_cfg, repo_env = _load_repo_context(repo_path)- return _resolve_active_for_repo(repo_id, repo_cfg, repo_env)+ selection = resolve_for_repo(repo_id, repo_path)+ return selection.provider, selection.modeldef get_configured_active_provider(@@ -376,9 +367,8 @@ def get_configured_active_provider() -> tuple[str | None, str | None]:"""Like :func:`get_active_provider`, but ``(None, None)`` when the resolvedprovider still needs a key, so a caller can show setup instead of a 400."""- repo_cfg, repo_env = _load_repo_context(repo_path)- provider_id, model = _resolve_active_for_repo(repo_id, repo_cfg, repo_env)- if provider_id is None or not _provider_configured(provider_id, repo_env):+ provider_id, model = get_active_provider(repo_id, repo_path)+ if provider_id is None or not _provider_configured(provider_id, repo_path):return None, Nonereturn provider_id, model@@ -387,24 +377,61 @@ def set_active_provider(provider_id: str,model: str | None = None,repo_id: str | None = None,+ *,+ repo_path: str | Path | None = None,+ base_url: Any = UNSET,) -> None:- """Persist the active provider/model selection.+ """Persist the active provider/model (and optionally base URL).- With ``repo_id`` the selection is scoped to that repo (under ``repos``),- so it overrides only that repo's chat and never shadows other repos in a- workspace. Without it, the legacy server-global selection is set.+ With ``repo_id`` the choice goes to that repo's ``.repowise/config.yaml``+ (``repo_path`` is required), the file the CLI reads too. Without it the+ global default in ``provider_config.json`` is set. ``model`` is any+ string, not only a catalog model. ``base_url`` left out keeps the current+ one; ``None`` or ``""`` clears it."""if provider_id not in _CATALOG_BY_ID:- raise ValueError(f"Unknown provider: {provider_id}")- resolved_model = model or _CATALOG_BY_ID[provider_id]["default_model"]- config = _load_config()+ raise UnknownProviderError(f"Unknown provider: {provider_id}")+ choice = _Choice(+ provider_id,+ (model or "").strip() or None,+ base_url if base_url is UNSET else validate_base_url(base_url),+ )if repo_id:- repos = config.setdefault("repos", {})- repos[repo_id] = {"provider": provider_id, "model": resolved_model}+ _save_repo_choice(choice, repo_id, repo_path)+ else:+ update_global_config(choice.apply_global)+++@dataclass(frozen=True, slots=True)+class _Choice:+ """A validated provider/model/base URL; ``base_url`` may be ``UNSET`` (keep)."""++ provider: str+ model: str | None+ base_url: Any++ def apply_global(self, config: dict[str, Any]) -> None:+ config["active_provider"] = self.provider+ _set_or_pop(config, "active_model", self.model)+ if self.base_url is not UNSET:+ _set_or_pop(config, "active_base_url", self.base_url)+++def _set_or_pop(config: dict[str, Any], key: str, value: Any) -> None:+ if value:+ config[key] = valueelse:- config["active_provider"] = provider_id- config["active_model"] = resolved_model- _save_config(config)+ config.pop(key, None)+++def _save_repo_choice(choice: _Choice, repo_id: str, repo_path: str | Path | None) -> None:+ if repo_path is None:+ raise ValueError(f"Repository {repo_id} has no local checkout to save the provider in.")+ _migrate_repo_selection(repo_id, repo_path)+ save_repo_llm_selection(repo_path, choice.provider, choice.model, choice.base_url)+ if choice.base_url not in (UNSET, None):+ # Chosen here by the user, so stored keys may be sent to it.+ trust_base_url(repo_path, choice.base_url)def set_api_key(@@ -427,18 +454,19 @@ def set_api_key(the decision to mirror a key to disk lives here in the server layer."""if provider_id not in _CATALOG_BY_ID:- raise ValueError(f"Unknown provider: {provider_id}")+ raise UnknownProviderError(f"Unknown provider: {provider_id}")if key is not None and ("\n" in key or "\r" in key):# Reject before writing anything so a bad value can't inject extra env# lines nor leave a partial store update. A real key has no newline.raise ValueError("API key must not contain a newline")- config = _load_config()- keys = config.setdefault("keys", {})- if key:- keys[provider_id] = key- else:- keys.pop(provider_id, None)- _save_config(config)+ def change(config: dict[str, Any]) -> None:+ keys = config.setdefault("keys", {})+ if key:+ keys[provider_id] = key+ else:+ keys.pop(provider_id, None)++ update_global_config(change)if repo_path is not None:_mirror_key_to_repo_env(provider_id, key, repo_path)@@ -475,47 +503,23 @@ def get_chat_provider_instance():"""Create a chat provider instance, resolved for a specific repo.- Resolution draws on the target repo's ``.repowise/config.yaml`` and- ``.repowise/.env`` (provider, model, API key, base_url) so chat uses the- exact configuration set at ``repowise init`` — without the server having- to load any repo's ``.env`` into its own process environment. An explicit+ Uses the shared resolver, so chat builds what ``repowise update`` would:+ the repo's ``config.yaml`` and ``.env`` without the server loading any+ repo's ``.env`` into its own environment. An explicit``provider_override``/``model_override`` (a per-request UI choice) wins.Returns a provider that implements both BaseProvider and ChatProvider."""- from repowise.core.providers.llm.registry import get_provider, provider_kwargs-- repo_cfg, repo_env = _load_repo_context(repo_path)-- if provider_override:- if provider_override not in _CATALOG_BY_ID:- raise ValueError(f"Unknown provider: {provider_override}")- provider_id = provider_override- model = model_override- # Inherit the repo's configured model when overriding only the- # provider and that provider matches what init configured.- if not model and repo_cfg.get("provider") == provider_id:- model = repo_cfg.get("model")- if not model:- model = _CATALOG_BY_ID[provider_id]["default_model"]- else:- provider_id, model = _resolve_active_for_repo(repo_id, repo_cfg, repo_env)-- if not provider_id:- raise ValueError("No active provider configured. Set an API key first.")-- api_key = _get_key_for_provider(provider_id, repo_env)- base_url = _get_base_url_for_provider(provider_id, repo_env, repo_cfg)- catalog = _CATALOG_BY_ID[provider_id]-- kwargs = provider_kwargs(- provider_id,- model=model or catalog["default_model"],- repo_path=repo_path,+ from repowise.core.providers.llm.registry import get_provider+ from repowise.core.providers.llm.resolve import llm_provider_kwargs++ selection = resolve_for_repo(+ repo_id,+ repo_path,+ provider_override=provider_override,+ model_override=model_override,)- if api_key:- kwargs["api_key"] = api_key- if base_url:- kwargs["base_url"] = base_url-- return get_provider(provider_id, with_rate_limiter=False, **kwargs)+ if not selection.provider:+ raise NoProviderConfiguredError("No active provider configured. Set an API key first.")+ kwargs = llm_provider_kwargs(selection, repo_path)+ return get_provider(selection.provider, with_rate_limiter=False, **kwargs)diff --git a/packages/server/src/repowise/server/routers/chat.py b/packages/server/src/repowise/server/routers/chat.pyindex 95e966d88..8aa3cff52 100644--- a/packages/server/src/repowise/server/routers/chat.py+++ b/packages/server/src/repowise/server/routers/chat.py@@ -21,6 +21,7 @@ from starlette.responses import StreamingResponsefrom repowise.core.persistence import crudfrom repowise.core.persistence.database import get_sessionfrom repowise.core.providers.llm.base import ChatProvider+from repowise.core.providers.llm.resolve import UntrustedBaseUrlErrorfrom repowise.core.redaction import redact_secretsfrom repowise.server.auth import PER_CALL_TOOL_SCOPE, Principal, get_authorizerfrom repowise.server.chat_artifacts import find_artifact, set_artifact_pinned@@ -53,7 +54,11 @@ from repowise.server.deps import (resolve_session_factory,verify_api_key,)-from repowise.server.provider_config import get_chat_provider_instance+from repowise.server.provider_config import (+ NoProviderConfiguredError,+ UnknownProviderError,+ get_chat_provider_instance,+)from repowise.server.schemas import (ArtifactUpdateRequest,ChatArtifactEnvelope,@@ -139,16 +144,18 @@ def _chat_provider()except ValueError as exc:# Every detail here is shown to the person, so none echoes the config.- # The two texts matched are get_chat_provider_instance's own; another- # ValueError (a bad base URL, say) is an invalid configuration.+ # Another ValueError (a bad base URL, say) is an invalid configuration.reason = str(exc)logger.warning("chat_provider_unavailable: %s", redact_secrets(reason))- if reason.startswith("No active provider configured"):+ if isinstance(exc, NoProviderConfiguredError):raise HTTPException(400, NO_PROVIDER_MESSAGE) from exc- if provider and reason.startswith("Unknown provider"):+ if isinstance(exc, UnknownProviderError):raise HTTPException(400, f"Unknown provider {provider!r}. Pick a provider in Settings.") from exc+ if isinstance(exc, UntrustedBaseUrlError):+ # Names only the URL, already stripped of any credentials.+ raise HTTPException(400, str(exc)) from excraise HTTPException(400, INVALID_PROVIDER_MESSAGE) from excexcept Exception as exc:logger.warning(diff --git a/packages/server/src/repowise/server/routers/providers.py b/packages/server/src/repowise/server/routers/providers.pyindex f3460dc2e..1537ac663 100644--- a/packages/server/src/repowise/server/routers/providers.py+++ b/packages/server/src/repowise/server/routers/providers.py@@ -65,12 +65,23 @@ async def get_providers(request: Request, repo_id: str | None = None):@router.patch("/active", response_model=ProviderStatusResponse)async def set_active(body: SetActiveProviderRequest, request: Request):- """Set the active provider and model (per-repo when ``repo_id`` is given)."""+ """Set the active provider, model and base URL.++ With ``repo_id`` the choice is written to that repo's+ ``.repowise/config.yaml``, which the CLI reads too; without it, the+ server-wide default is set. ``base_url`` left out of the body keeps the+ current endpoint; ``""`` or ``null`` clears it.+ """+ repo_path = await _repo_path_for(request, body.repo_id)+ if body.repo_id and repo_path is None:+ raise HTTPException(404, f"Repository {body.repo_id} has no local checkout.")+ extra = {"base_url": body.base_url} if "base_url" in body.model_fields_set else {}try:- set_active_provider(body.provider, body.model, repo_id=body.repo_id)+ set_active_provider(+ body.provider, body.model, repo_id=body.repo_id, repo_path=repo_path, **extra+ )except ValueError as exc:raise HTTPException(400, str(exc)) from exc- repo_path = await _repo_path_for(request, body.repo_id)return list_provider_status(repo_id=body.repo_id, repo_path=repo_path)diff --git a/packages/server/src/repowise/server/schemas/ui_helpers.py b/packages/server/src/repowise/server/schemas/ui_helpers.pyindex 0ef2eb2bc..dd63c12d2 100644--- a/packages/server/src/repowise/server/schemas/ui_helpers.py+++ b/packages/server/src/repowise/server/schemas/ui_helpers.py@@ -18,9 +18,14 @@ class OkResponse(BaseModel):class SetActiveProviderRequest(BaseModel):provider: str+ #: Any model id the provider accepts, not only a catalog model.model: str | None = None- # When set, the selection is scoped to this repo (so picking a model for- # one repo never shadows another in a workspace). Omit for the global default.+ #: An ``http(s)://`` endpoint (an OpenAI-compatible server such as LM+ #: Studio). Omit to keep the current one; ``""`` or ``null`` clears it.+ base_url: str | None = None+ # When set, the selection is written to this repo's .repowise/config.yaml+ # (so picking a model for one repo never shadows another in a workspace).+ # Omit for the global default.repo_id: str | None = None@@ -60,11 +65,22 @@ class EmbedderEntry(BaseModel):semantic: bool = True+class SelectionProvenance(BaseModel):+ provider: str | None = None+ model: str | None = None+ base_url: str | None = None++class ActiveProviderSelection(BaseModel):"""The provider/model this scope resolves to; ``None`` when unset."""provider: str | None = Nonemodel: str | None = None+ #: The endpoint requests go to; ``None`` means the provider's own default.+ base_url: str | None = None+ #: Where each value came from, per field: ``request``, ``config.yaml``,+ #: ``global``, ``env:<VAR>``, ``default`` or ``autodetect``; ``None`` if unset.+ provenance: SelectionProvenance = SelectionProvenance()#: USD per 1K tokens for ``model``; ``None`` when no model resolves.input_cost_per_1k: float | None = Noneoutput_cost_per_1k: float | None = Nonediff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 5c463f49c..c1e3be772 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -95,6 +95,8 @@ export interface ActionsResponse {export interface ActiveProviderSelection {provider?: string | null;model?: string | null;+ base_url?: string | null;+ provenance?: SelectionProvenance;input_cost_per_1k?: number | null;output_cost_per_1k?: number | null;embedder?: string | null;@@ -3589,9 +3591,16 @@ export interface SecuritySummaryResponse {scanned_at?: string | null;}+export interface SelectionProvenance {+ provider?: string | null;+ model?: string | null;+ base_url?: string | null;+}+export interface SetActiveProviderRequest {provider: string;model?: string | null;+ base_url?: string | null;repo_id?: string | null;}diff --git a/tests/conftest.py b/tests/conftest.pyindex 6d78969e6..3dc068d5e 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -117,6 +117,32 @@ def _isolate_tokens_file(monkeypatch: pytest.MonkeyPatch, tmp_path_factory: pytemonkeypatch.setenv("REPOWISE_TOKENS_FILE", str(missing))+_REAL_HOME = Path.home()++[email protected](autouse=True)+def _isolate_provider_config(+ monkeypatch: pytest.MonkeyPatch, tmp_path_factory: pytest.TempPathFactory+):+ """Keep a developer's ``~/.repowise`` provider and embedder settings out.++ Every LLM resolver reads ``provider_config.json`` (global default, stored+ keys) and the embedder resolver reads ``~/.repowise/config.yaml``, so real+ ones on the machine would decide what a test resolves. A test that moves+ ``Path.home`` on purpose still gets its own home.+ """+ scratch = tmp_path_factory.mktemp("provider-config")+ monkeypatch.setenv("REPOWISE_CONFIG_DIR", str(scratch))+ from repowise.core.providers.embedding import resolve as embedding_resolve++ def _global_embedder_config() -> Path:+ home = Path.home()+ return (scratch if home == _REAL_HOME else home / ".repowise") / "config.yaml"++ monkeypatch.setattr(embedding_resolve, "global_config_path", _global_embedder_config)+ sys.modules["repowise.core.providers.llm.resolve"].clear_cache()++@pytest.fixture(autouse=True)def _fresh_per_index_caches():"""Drop the MCP server's per-index caches before every test.diff --git a/tests/unit/cli/test_doctor_provider_status.py b/tests/unit/cli/test_doctor_provider_status.pyindex 3756c45c8..795f1284c 100644--- a/tests/unit/cli/test_doctor_provider_status.py+++ b/tests/unit/cli/test_doctor_provider_status.py@@ -31,7 +31,7 @@ def _patch_provider_state()monkeypatch.setattr("repowise.cli.helpers.validate_provider_config",- lambda: warnings or [],+ lambda **_kw: warnings or [],)diff --git a/tests/unit/cli/test_embedder_resolution.py b/tests/unit/cli/test_embedder_resolution.pyindex 0cb7f4b5a..0d282c04b 100644--- a/tests/unit/cli/test_embedder_resolution.py+++ b/tests/unit/cli/test_embedder_resolution.py@@ -180,6 +180,24 @@ def test_serve_seeds_a_mock_pin_into_the_environment(assert os.environ.get("REPOWISE_EMBEDDER") == "mock"+def test_serve_leaves_the_chat_provider_to_the_shared_resolver(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Chat reads config.yaml per repo, so serve no longer copies it into env vars."""+ from repowise.cli.commands import serve_cmd++ _write_config(tmp_path, provider="openai", model="qwen3", embedder="mock")+ monkeypatch.chdir(tmp_path)+ monkeypatch.delenv("REPOWISE_PROVIDER", raising=False)+ monkeypatch.delenv("REPOWISE_MODEL", raising=False)+ monkeypatch.setenv("REPOWISE_EMBEDDER", "mock")++ serve_cmd._load_local_provider_config()++ assert "REPOWISE_PROVIDER" not in os.environ+ assert "REPOWISE_MODEL" not in os.environ++def test_reader_falls_back_to_the_environment_when_nothing_is_pinned(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/tests/unit/cli/test_helpers.py b/tests/unit/cli/test_helpers.pyindex 23e760a94..ce0ecab03 100644--- a/tests/unit/cli/test_helpers.py+++ b/tests/unit/cli/test_helpers.py@@ -7,6 +7,7 @@ import osfrom pathlib import Pathfrom typing import Any+import clickimport pytestfrom repowise.cli.helpers import (@@ -21,6 +22,7 @@ from repowise.cli.helpers import (resolve_reasoning,resolve_repo_path,run_async,+ save_config,save_state,validate_provider_config,warn,@@ -813,13 +815,73 @@ class TestResolveProviderConfigModel:assert resolve_provider(None, None, repo_path=tmp_path) == "provider"assert captured["kwargs"].get("model") == "anthropic/claude-sonnet-5"- def test_env_model_overrides_config_model(self, monkeypatch, tmp_path):+ def test_config_model_overrides_env_model(self, monkeypatch, tmp_path):+ """config.yaml outranks REPOWISE_MODEL, the order every entry point shares."""captured = self._capture(monkeypatch, tmp_path, {"model": "google/gemini-3.1"})monkeypatch.setenv("REPOWISE_PROVIDER", "openrouter")monkeypatch.setenv("REPOWISE_MODEL", "anthropic/claude-opus-5")assert resolve_provider(None, None, repo_path=tmp_path) == "provider"- assert captured["kwargs"].get("model") == "anthropic/claude-opus-5"+ assert captured["kwargs"].get("model") == "google/gemini-3.1"++ def test_config_provider_overrides_env_provider(self, monkeypatch, tmp_path):+ captured = self._capture(+ monkeypatch, tmp_path, {"provider": "openrouter", "model": "google/gemini-3.1"}+ )+ monkeypatch.setenv("REPOWISE_PROVIDER", "anthropic")+ monkeypatch.setenv("REPOWISE_MODEL", "claude-opus-4-6")++ assert resolve_provider(None, None, repo_path=tmp_path) == "provider"+ assert captured["name"] == "openrouter"+ assert captured["kwargs"].get("model") == "google/gemini-3.1"++ def test_flag_provider_does_not_inherit_another_providers_model(+ self, monkeypatch, tmp_path+ ):+ captured = self._capture(+ monkeypatch, tmp_path, {"provider": "gemini", "model": "gemini-3.1-pro-preview"}+ )++ assert resolve_provider("openrouter", None, repo_path=tmp_path) == "provider"+ from repowise.core.providers.llm.specs import PROVIDER_SPECS++ assert captured["kwargs"].get("model") == PROVIDER_SPECS["openrouter"].default_model++ def test_config_base_url_beats_env_base_url(self, monkeypatch, tmp_path):+ captured = self._capture(+ monkeypatch,+ tmp_path,+ {"provider": "openai", "model": "qwen", "openai": {"base_url": "http://localhost:1234/v1"}},+ )+ monkeypatch.setenv("OPENAI_API_KEY", "lm-studio")+ monkeypatch.setenv("OPENAI_BASE_URL", "http://other:4000/v1")++ assert resolve_provider(None, None, repo_path=tmp_path) == "provider"+ assert captured["kwargs"]["base_url"] == "http://localhost:1234/v1"++ def test_unconfirmed_remote_base_url_is_refused_with_its_url(self, monkeypatch, tmp_path):+ self._capture(+ monkeypatch,+ tmp_path,+ {"provider": "openai", "openai": {"base_url": "https://collector.example/v1"}},+ )+ monkeypatch.setenv("OPENAI_API_KEY", "sk-shell")++ with pytest.raises(click.ClickException, match=r"collector\.example") as info:+ resolve_provider(None, None, repo_path=tmp_path)+ assert "repowise init" in info.value.message++ def test_init_confirms_the_base_url_it_saves(self, monkeypatch, tmp_path):+ captured = self._capture(+ monkeypatch,+ tmp_path,+ {"provider": "openai", "openai": {"base_url": "https://gateway.example/v1"}},+ )+ monkeypatch.setenv("OPENAI_API_KEY", "sk-shell")+ save_config(tmp_path, "openai", "gpt-x", "mock", save_key=False)++ assert resolve_provider(None, None, repo_path=tmp_path) == "provider"+ assert captured["kwargs"]["base_url"] == "https://gateway.example/v1"def test_explicit_model_flag_overrides_env_model(self, monkeypatch, tmp_path):captured = self._capture(monkeypatch, tmp_path, {"model": "google/gemini-3.1"})diff --git a/tests/unit/server/mcp/test_provider_resolution.py b/tests/unit/server/mcp/test_provider_resolution.pyindex d8bc5cbca..c109111a7 100644--- a/tests/unit/server/mcp/test_provider_resolution.py+++ b/tests/unit/server/mcp/test_provider_resolution.py@@ -14,10 +14,7 @@ import json as _jsonimport pytestfrom repowise.server.mcp_server.tool_answer import synthesis as synthesis_module-from repowise.server.mcp_server.tool_answer.synthesis import (- _load_repo_provider_config,- _resolve_provider_for_answer,-)+from repowise.server.mcp_server.tool_answer.synthesis import _resolve_provider_for_answer@pytest.fixture(autouse=True)@@ -51,27 +48,43 @@ def _write_repo(tmp_path, *, config=None, state=None):return tmp_path-def test_config_yaml_outranks_state_json(tmp_path):- """config.yaml is user intent; state.json only records the last run."""- repo = _write_repo(- tmp_path,- config={"provider": "openai", "model": "gpt-5.4-nano"},- state={"provider": "gemini", "model": "gemini-3.1-flash-lite-preview"},- )- name, model, _ = _load_repo_provider_config(repo)- assert name == "openai"- assert model == "gpt-5.4-nano"+def test_config_yaml_outranks_the_env_provider(tmp_path, monkeypatch):+ """config.yaml is the repo's choice; REPOWISE_PROVIDER is a lower default."""+ repo = _write_repo(tmp_path, config={"provider": "openai", "model": "gpt-5.4-nano"})+ monkeypatch.setenv("REPOWISE_PROVIDER", "anthropic")+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test")+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-test")+ seen = _record_get_provider(monkeypatch)++ assert _resolve_provider_for_answer(repo) is not None+ assert seen["name"] == "openai"+ assert seen["kwargs"]["model"] == "gpt-5.4-nano"+++def test_doc_model_overrides_the_configured_model(tmp_path, monkeypatch):+ repo = _write_repo(tmp_path, config={"provider": "openai", "model": "gpt-5.4-nano"})+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test")+ monkeypatch.setenv("REPOWISE_DOC_MODEL", "gpt-5.4")+ seen = _record_get_provider(monkeypatch)++ assert _resolve_provider_for_answer(repo) is not None+ assert seen["kwargs"]["model"] == "gpt-5.4"-def test_state_json_still_used_when_config_lacks_provider(tmp_path):- repo = _write_repo(- tmp_path,- config={"commit_limit": 200},- state={"provider": "openai", "model": "gpt-5.4-nano"},+def test_config_base_url_reaches_the_provider(tmp_path, monkeypatch):+ """An OpenAI-compatible server (LM Studio) set once in config.yaml."""+ d = tmp_path / ".repowise"+ d.mkdir()+ (d / "config.yaml").write_text(+ "provider: openai\nmodel: qwen3\nopenai:\n base_url: http://localhost:1234/v1\n",+ encoding="utf-8",)- name, model, _ = _load_repo_provider_config(repo)- assert name == "openai"- assert model == "gpt-5.4-nano"+ monkeypatch.setenv("OPENAI_API_KEY", "lm-studio")+ seen = _record_get_provider(monkeypatch)++ assert _resolve_provider_for_answer(tmp_path) is not None+ assert seen["kwargs"]["base_url"] == "http://localhost:1234/v1"+ assert seen["kwargs"]["model"] == "qwen3"def test_reasoning_is_loaded_from_repo_config(tmp_path):@@ -81,8 +94,8 @@ def test_reasoning_is_loaded_from_repo_config(tmp_path):def test_keyless_persisted_provider_falls_back_to_available_key(tmp_path, monkeypatch):- """gemini persisted, only OPENAI_API_KEY present -> openai provider, not None."""- repo = _write_repo(tmp_path, state={"provider": "gemini", "model": "gemini-3.1-flash"})+ """gemini configured, only OPENAI_API_KEY present -> openai provider, not None."""+ repo = _write_repo(tmp_path, config={"provider": "gemini", "model": "gemini-3.1-flash"})monkeypatch.setenv("OPENAI_API_KEY", "sk-test")provider = _resolve_provider_for_answer(repo)assert provider is not None@@ -92,12 +105,12 @@ def test_keyless_persisted_provider_falls_back_to_available_key(tmp_path, monkeydef test_no_keys_at_all_resolves_to_none(tmp_path):- repo = _write_repo(tmp_path, state={"provider": "gemini"})+ repo = _write_repo(tmp_path, config={"provider": "gemini"})assert _resolve_provider_for_answer(repo) is Nonedef test_explicit_env_provider_still_wins(tmp_path, monkeypatch):- repo = _write_repo(tmp_path, state={"provider": "gemini"})+ repo = _write_repo(tmp_path)monkeypatch.setenv("REPOWISE_PROVIDER", "openai")monkeypatch.setenv("OPENAI_API_KEY", "sk-test")provider = _resolve_provider_for_answer(repo)diff --git a/tests/unit/server/test_app_lifespan.py b/tests/unit/server/test_app_lifespan.pyindex 0bc6149f4..749fde06a 100644--- a/tests/unit/server/test_app_lifespan.py+++ b/tests/unit/server/test_app_lifespan.py@@ -563,37 +563,35 @@ async def test_shutdown_closes_the_registry_and_member_engines(env, stubs):@pytest.fixture-def embedder_env(monkeypatch):- for key in ("REPOWISE_EMBEDDER", "REPOWISE_EMBEDDING_MODEL", "REPOWISE_EMBEDDING_DIMS"):+def embedder_env(monkeypatch, tmp_path):+ for key in (+ "REPOWISE_EMBEDDER",+ "REPOWISE_EMBEDDING_MODEL",+ "REPOWISE_EMBEDDING_DIMS",+ "OPENAI_API_KEY",+ "GEMINI_API_KEY",+ "GOOGLE_API_KEY",+ "OPENROUTER_API_KEY",+ "EDENAI_API_KEY",+ ):monkeypatch.delenv(key, raising=False)+ # No developer ~/.repowise/config.yaml key leaks into the kwargs.+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))return monkeypatch+# Only configured values are passed; each embedder's default model and width+# live in its own constructor.@pytest.mark.parametrize(("backend", "target", "model_env", "expected_kwargs"),[("ollama", "ollama.OllamaEmbedder", None, {}),- ("OpenAI", "openai.OpenAIEmbedder", None, {"model": "text-embedding-3-small"}),+ ("OpenAI", "openai.OpenAIEmbedder", None, {}),("openai", "openai.OpenAIEmbedder", "text-embedding-3-large", {"model": "text-embedding-3-large"}),- (- "openrouter",- "openrouter.OpenRouterEmbedder",- None,- {"model": "google/gemini-embedding-001"},- ),- (- "edenai",- "edenai.EdenAIEmbedder",- None,- {"model": "amazon/amazon.titan-embed-text-v2:0"},- ),- ("gemini", "gemini.GeminiEmbedder", None, {"output_dimensionality": 768}),- (- "gemini",- "gemini.GeminiEmbedder",- "text-embedding-004",- {"model": "text-embedding-004", "output_dimensionality": 768},- ),+ ("openrouter", "openrouter.OpenRouterEmbedder", None, {}),+ ("edenai", "edenai.EdenAIEmbedder", None, {}),+ ("gemini", "gemini.GeminiEmbedder", None, {}),+ ("gemini", "gemini.GeminiEmbedder", "text-embedding-004", {"model": "text-embedding-004"}),],)def test_build_embedder_backends(embedder_env, backend, target, model_env, expected_kwargs):@@ -607,21 +605,37 @@ def test_build_embedder_backends(embedder_env, backend, target, model_env, expeccls.assert_called_once_with(**expected_kwargs)+def test_build_embedder_passes_the_resolved_key(embedder_env):+ from repowise.server.app import _build_embedder++ embedder_env.setenv("REPOWISE_EMBEDDER", "openai")+ embedder_env.setenv("OPENAI_API_KEY", "sk-test")+ with patch("repowise.core.providers.embedding.openai.OpenAIEmbedder") as cls:+ _build_embedder()+ cls.assert_called_once_with(api_key="sk-test")++@pytest.mark.parametrize(- ("raw", "dims", "warned"),- [("1536", 1536, False), ("0", 768, True), ("-3", 768, True), ("wide", 768, True), ("", 768, False)],+ ("raw", "expected", "warned"),+ [+ ("1536", {"output_dimensionality": 1536}, False),+ ("0", {}, True),+ ("-3", {}, True),+ ("wide", {}, True),+ ("", {}, False),+ ],)-def test_build_embedder_gemini_dims(embedder_env, capsys, raw, dims, warned):+def test_build_embedder_gemini_dims(embedder_env, capsys, raw, expected, warned):from repowise.server.app import _build_embedderembedder_env.setenv("REPOWISE_EMBEDDER", "gemini")embedder_env.setenv("REPOWISE_EMBEDDING_DIMS", raw)with patch("repowise.core.providers.embedding.gemini.GeminiEmbedder") as cls:_build_embedder()- cls.assert_called_once_with(output_dimensionality=dims)+ cls.assert_called_once_with(**expected)err = capsys.readouterr().errif warned:- assert err == f"REPOWISE_EMBEDDING_DIMS={raw!r} is not a positive integer; using 768.\n"+ assert f"REPOWISE_EMBEDDING_DIMS={raw!r} is not a positive integer" in errelse:assert err == ""diff --git a/tests/unit/server/test_chat_router.py b/tests/unit/server/test_chat_router.pyindex 0f325afc2..c18486c8b 100644--- a/tests/unit/server/test_chat_router.py+++ b/tests/unit/server/test_chat_router.py@@ -13,6 +13,7 @@ from repowise.core.providers.llm.base import ChatStreamEvent, ChatToolCall, Provfrom repowise.server.chat_prompt import _build_system_promptfrom repowise.server.chat_session import WEB_POLICYfrom repowise.server.chat_tools import get_tool_catalog+from repowise.server.provider_config import NoProviderConfiguredError, UnknownProviderErrorfrom repowise.server.schemas.chat import ChatPageContextfrom tests.unit.server.test_chat_stream_terminal_event import (_REPO_ID,@@ -577,7 +578,7 @@ async def test_no_configured_provider_is_a_chat_error_event_not_an_http_error():from repowise.server.chat_errors import NO_PROVIDER_MESSAGEapp = await _make_app()- failure = ValueError("No active provider configured. Set an API key first.")+ failure = NoProviderConfiguredError("No active provider configured. Set an API key first.")with patch(_PROVIDER, side_effect=failure):events = _data_events(await _post(app, {"message": "hi"}))assert events == [{"type": "error", "message": NO_PROVIDER_MESSAGE}]@@ -587,8 +588,10 @@ async def test_no_configured_provider_is_a_chat_error_event_not_an_http_error():@pytest.mark.parametrize(("override", "failure", "expected"),[- (None, ValueError("No active provider configured. Set an API key first."), "No LLM provider"),- ("nope", ValueError("Unknown provider: nope"), "Unknown provider 'nope'"),+ (None, NoProviderConfiguredError("No active provider configured."), "No LLM provider"),+ ("nope", UnknownProviderError("Unknown provider: nope"), "Unknown provider 'nope'"),+ # Matched by type, not text: a plain ValueError with the same words is generic.+ (None, ValueError("No active provider configured."), "configuration is invalid"),(None, ValueError("base_url http://10.0.0.5:9/x?key=AIzaSecret1234 is invalid"), "configuration is invalid"),("openai", RuntimeError("client init failed for sk-proj-abcdef1234567890"), "Could not start the chat provider"),],diff --git a/tests/unit/server/test_embedding_dims_validation.py b/tests/unit/server/test_embedding_dims_validation.pyindex 607ed1b91..357d3fe0e 100644--- a/tests/unit/server/test_embedding_dims_validation.py+++ b/tests/unit/server/test_embedding_dims_validation.py@@ -28,21 +28,22 @@ def test_valid_dims_are_passed_through(monkeypatch: pytest.MonkeyPatch) -> None:assert kwargs["output_dimensionality"] == 256-def test_missing_dims_default_to_768(monkeypatch: pytest.MonkeyPatch) -> None:+def test_missing_dims_leave_the_constructor_default(monkeypatch: pytest.MonkeyPatch) -> None:_clear_dims(monkeypatch)kwargs = _embedder_kwargs("gemini")- assert kwargs["output_dimensionality"] == 768+ # GeminiEmbedder's own default (768) applies; it is declared only there.+ assert "output_dimensionality" not in kwargs@pytest.mark.parametrize("bad", ["-5", "0", "-1", "abc", "3.14", "inf", "nan", ""])-def test_bad_dims_fall_back_to_768(+def test_bad_dims_fall_back_to_the_default(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture, bad: str) -> None:_clear_dims(monkeypatch)if bad:monkeypatch.setenv("REPOWISE_EMBEDDING_DIMS", bad)kwargs = _embedder_kwargs("gemini")- assert kwargs["output_dimensionality"] == 768+ assert "output_dimensionality" not in kwargsif bad:assert "not a positive integer" in capsys.readouterr().errdiff --git a/tests/unit/server/test_provider_config.py b/tests/unit/server/test_provider_config.pyindex cd7878b7b..5aaed02b3 100644--- a/tests/unit/server/test_provider_config.py+++ b/tests/unit/server/test_provider_config.py@@ -157,7 +157,7 @@ def test_per_repo_selection_does_not_shadow_other_repo(clean_env, tmp_path):)# User picks a different model for repo A via the UI.- pc.set_active_provider("openai", "gpt-5.4", repo_id="ra")+ pc.set_active_provider("openai", "gpt-5.4", repo_id="ra", repo_path=str(repo_a))a_provider, a_model = pc.get_active_provider(repo_id="ra", repo_path=str(repo_a))b_provider, b_model = pc.get_active_provider(repo_id="rb", repo_path=str(repo_b))@@ -382,3 +382,227 @@ def test_configured_active_provider_needs_the_key_chat_needs(clean_env, tmp_path_make_repo(repo, env="ANTHROPIC_API_KEY=sk-ant-test\n")assert pc.get_configured_active_provider(repo_path=repo) == ("anthropic", "claude-x")+++# ---------------------------------------------------------------------------+# config.yaml is the repo's single source; legacy JSON entries migrate once.+# ---------------------------------------------------------------------------+++def _write_store(tmp_path: Path, data: dict) -> None:+ import json++ from repowise.core.providers.llm.resolve import forget_cached++ path = tmp_path / "server" / "provider_config.json"+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(data), encoding="utf-8")+ forget_cached(path)+++def test_repo_selection_is_written_to_config_yaml(clean_env, tmp_path):+ from repowise.core.repo_config import load_repo_config++ repo = _make_repo(tmp_path / "repo", config="provider: gemini\nembedder: gemini\n")++ pc.set_active_provider(+ "openai", "qwen3-coder", repo_id="r1", repo_path=repo, base_url="http://localhost:1234/v1"+ )++ cfg = load_repo_config(repo)+ assert (cfg["provider"], cfg["model"], cfg["embedder"]) == ("openai", "qwen3-coder", "gemini")+ assert cfg["openai"] == {"base_url": "http://localhost:1234/v1"}+ assert "repos" not in pc._load_config()+ active = pc.list_provider_status(repo_id="r1", repo_path=repo)["active"]+ assert active["base_url"] == "http://localhost:1234/v1"+ assert active["provenance"] == {+ "provider": "config.yaml",+ "model": "config.yaml",+ "base_url": "config.yaml",+ }+++def test_repo_selection_needs_a_checkout(clean_env):+ with pytest.raises(ValueError, match="no local checkout"):+ pc.set_active_provider("openai", "m", repo_id="r1")+++def test_bad_base_url_is_rejected_before_writing(clean_env, tmp_path):+ repo = _make_repo(tmp_path / "repo", config="provider: gemini\n")+ with pytest.raises(ValueError, match="http"):+ pc.set_active_provider("openai", "m", repo_id="r1", repo_path=repo, base_url="localhost")+ assert "openai" not in (repo / ".repowise" / "config.yaml").read_text(encoding="utf-8")+++def test_global_default_keeps_base_url_and_any_model(clean_env, tmp_path):+ pc.set_active_provider("openai", "my-custom-model", base_url="http://lm:1234/v1")+ stored = pc._load_config()+ assert stored["active_model"] == "my-custom-model"+ assert stored["active_base_url"] == "http://lm:1234/v1"++ pc.set_active_provider("openai", "my-custom-model", base_url="")+ assert "active_base_url" not in pc._load_config()+++def test_legacy_json_selection_moves_into_an_empty_config_yaml(clean_env, tmp_path):+ from repowise.core.repo_config import load_repo_config++ repo = _make_repo(tmp_path / "repo", config="embedder: mock\n")+ _write_store(tmp_path, {"repos": {"r1": {"provider": "openai", "model": "gpt-5.4"}}})++ assert pc.get_active_provider(repo_id="r1", repo_path=repo) == ("openai", "gpt-5.4")+ cfg = load_repo_config(repo)+ assert (cfg["provider"], cfg["model"], cfg["embedder"]) == ("openai", "gpt-5.4", "mock")+ assert "repos" not in pc._load_config()+++def test_legacy_json_selection_is_dropped_when_yaml_has_a_provider(clean_env, tmp_path):+ from repowise.core.repo_config import load_repo_config++ repo = _make_repo(tmp_path / "repo", config="provider: gemini\nmodel: g\n")+ _write_store(+ tmp_path,+ {+ "repos": {"r1": {"provider": "openai", "model": "gpt-5.4"}, "r2": {"provider": "kimi"}},+ "keys": {"openai": "sk-keep"},+ },+ )++ assert pc.get_active_provider(repo_id="r1", repo_path=repo) == ("gemini", "g")+ assert load_repo_config(repo)["provider"] == "gemini"+ stored = pc._load_config()+ assert stored["repos"] == {"r2": {"provider": "kimi"}}+ assert stored["keys"] == {"openai": "sk-keep"}+++def test_config_yaml_beats_the_env_provider_for_chat(clean_env, tmp_path):+ repo = _make_repo(tmp_path / "repo", config="provider: openai\nmodel: gemma4\n")+ clean_env["REPOWISE_PROVIDER"] = "anthropic"+ clean_env["REPOWISE_MODEL"] = "claude-x"+ assert pc.get_active_provider(repo_path=repo) == ("openai", "gemma4")+++def test_legacy_base_url_moves_with_the_selection_and_is_trusted(clean_env, tmp_path):+ from repowise.core.repo_config import load_repo_config++ repo = _make_repo(tmp_path / "repo", config="embedder: mock\n", env="")+ _write_store(+ tmp_path,+ {"repos": {"r1": {"provider": "openai", "model": "m", "base_url": "https://gw.example/v1"}}},+ )+ clean_env["OPENAI_API_KEY"] = "sk-shell"++ status = pc.list_provider_status(repo_id="r1", repo_path=repo)+ assert status["active"]["base_url"] == "https://gw.example/v1"+ assert load_repo_config(repo)["openai"] == {"base_url": "https://gw.example/v1"}+ # Chosen in the UI before, so the stored key may still go there.+ from repowise.core.providers.llm.resolve import llm_provider_kwargs, resolve_llm++ assert llm_provider_kwargs(resolve_llm(repo), repo)["api_key"] == "sk-shell"+++def test_a_repo_without_a_checkout_keeps_its_stored_selection(clean_env, tmp_path):+ _write_store(tmp_path, {"repos": {"r1": {"provider": "anthropic", "model": "claude-x"}}})++ assert pc.get_active_provider(repo_id="r1") == ("anthropic", "claude-x")+ assert pc._load_config()["repos"]["r1"]["provider"] == "anthropic"+ active = pc.list_provider_status(repo_id="r1")["active"]+ assert active["provenance"]["provider"] == "provider_config.json"+++def test_unknown_legacy_provider_is_dropped_with_a_warning(clean_env, tmp_path, caplog):+ repo = _make_repo(tmp_path / "repo", config="embedder: mock\n")+ _write_store(tmp_path, {"repos": {"r1": {"provider": "retired-thing"}}})++ with caplog.at_level("WARNING"):+ pc.get_active_provider(repo_id="r1", repo_path=repo)+ assert "retired-thing" in caplog.text+ assert "repos" not in pc._load_config()+++def test_migration_does_not_look_like_a_config_change_to_update(clean_env, tmp_path):+ import json++ from repowise.core.repo_config import (+ changed_config_dependencies,+ config_dependency_fingerprints,+ config_fingerprint,+ )++ repo = _make_repo(tmp_path / "repo", config="embedder: mock\ncommit_limit: 50\n")+ state_path = repo / ".repowise" / "state.json"+ state_path.write_text(+ json.dumps(+ {+ "config_fingerprint": config_fingerprint(repo),+ "config_dependency_fingerprints": config_dependency_fingerprints(repo),+ }+ ),+ encoding="utf-8",+ )+ _write_store(tmp_path, {"repos": {"r1": {"provider": "openai", "model": "gpt-5.4"}}})++ pc.get_active_provider(repo_id="r1", repo_path=repo)++ state = json.loads(state_path.read_text(encoding="utf-8"))+ assert state["config_fingerprint"] == config_fingerprint(repo)+ assert not changed_config_dependencies(+ state["config_dependency_fingerprints"], config_dependency_fingerprints(repo)+ )+++def test_a_pending_config_change_survives_the_migration(clean_env, tmp_path):+ import json++ from repowise.core.repo_config import config_dependency_fingerprints, config_fingerprint++ repo = _make_repo(tmp_path / "repo", config="embedder: mock\n")+ stale = {"config_fingerprint": "old", "config_dependency_fingerprints": {"traversal": "old"}}+ (repo / ".repowise" / "state.json").write_text(json.dumps(stale), encoding="utf-8")+ _write_store(tmp_path, {"repos": {"r1": {"provider": "openai"}}})++ pc.get_active_provider(repo_id="r1", repo_path=repo)++ state = json.loads((repo / ".repowise" / "state.json").read_text(encoding="utf-8"))+ assert state["config_fingerprint"] == "old"+ assert state["config_dependency_fingerprints"]["traversal"] == "old"+ assert config_fingerprint(repo) and config_dependency_fingerprints(repo)+++def test_ui_patch_is_a_real_change_for_update(clean_env, tmp_path):+ import json++ from repowise.core.repo_config import config_fingerprint++ repo = _make_repo(tmp_path / "repo", config="provider: gemini\nmodel: g\n")+ before = config_fingerprint(repo)+ (repo / ".repowise" / "state.json").write_text(+ json.dumps({"config_fingerprint": before}), encoding="utf-8"+ )++ pc.set_active_provider("openai", "gpt-5.4", repo_id="r1", repo_path=repo)++ state = json.loads((repo / ".repowise" / "state.json").read_text(encoding="utf-8"))+ assert state["config_fingerprint"] == before != config_fingerprint(repo)+++def test_concurrent_migration_and_key_writes_lose_nothing(clean_env, tmp_path):+ from concurrent.futures import ThreadPoolExecutor++ repos = {+ f"r{i}": _make_repo(tmp_path / f"repo{i}", config="embedder: mock\n") for i in range(8)+ }+ _write_store(tmp_path, {"repos": {rid: {"provider": "openai"} for rid in repos}})+ providers = ["anthropic", "gemini", "deepseek", "kimi", "openrouter", "edenai"]++ def work(i: int) -> None:+ rid = f"r{i % 8}"+ pc.get_active_provider(repo_id=rid, repo_path=repos[rid])+ pc.set_api_key(providers[i % len(providers)], f"k{i % len(providers)}")++ with ThreadPoolExecutor(max_workers=8) as pool:+ list(pool.map(work, range(24)))++ stored = pc._load_config()+ assert "repos" not in stored+ assert set(stored["keys"]) == set(providers)diff --git a/tests/unit/server/test_provider_key_endpoint.py b/tests/unit/server/test_provider_key_endpoint.pyindex d30bd2c37..802ede41f 100644--- a/tests/unit/server/test_provider_key_endpoint.py+++ b/tests/unit/server/test_provider_key_endpoint.py@@ -19,8 +19,10 @@ def isolate_server_store(monkeypatch, tmp_path):from repowise.server import provider_config as pcmonkeypatch.setenv("REPOWISE_CONFIG_DIR", str(tmp_path / "server-store"))- # Don't let a real ANTHROPIC_API_KEY on the dev box mask the stored one.+ # Don't let a real ANTHROPIC_API_KEY on the dev box mask the stored one,+ # nor an OPENAI_BASE_URL another test exported stand in for a cleared one.monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)+ monkeypatch.delenv("OPENAI_BASE_URL", raising=False)return pc@@ -185,3 +187,51 @@ async def test_get_providers_returns_no_key_material(client: AsyncClient) -> Nonfor provider in resp.json()["providers"]:assert "key" not in providerassert "api_key" not in provider+++async def test_patch_active_with_repo_id_writes_config_yaml(client: AsyncClient) -> None:+ from pathlib import Path++ from repowise.core.repo_config import load_repo_config++ repo = await create_test_repo(client)++ resp = await client.patch(+ "/api/providers/active",+ json={+ "provider": "openai",+ "model": "qwen/qwen3-coder-30b",+ "base_url": "http://localhost:1234/v1",+ "repo_id": repo["id"],+ },+ )+ assert resp.status_code == 200+ active = resp.json()["active"]+ assert (active["provider"], active["model"]) == ("openai", "qwen/qwen3-coder-30b")+ assert active["base_url"] == "http://localhost:1234/v1"+ assert active["provenance"]["base_url"] == "config.yaml"+ cfg = load_repo_config(Path(repo["local_path"]))+ assert cfg["openai"] == {"base_url": "http://localhost:1234/v1"}++ # Leaving base_url out keeps it; the existing request shape still works.+ resp = await client.patch(+ "/api/providers/active",+ json={"provider": "openai", "model": "other", "repo_id": repo["id"]},+ )+ assert resp.json()["active"]["base_url"] == "http://localhost:1234/v1"++ resp = await client.patch(+ "/api/providers/active",+ json={"provider": "openai", "base_url": "", "repo_id": repo["id"]},+ )+ assert resp.json()["active"]["base_url"] is None+++async def test_patch_active_rejects_a_non_http_base_url(client: AsyncClient) -> None:+ resp = await client.patch(+ "/api/providers/active", json={"provider": "openai", "base_url": "localhost:1234"}+ )+ assert resp.status_code == 400+ assert "http" in resp.json()["detail"]diff --git a/tests/unit/test_providers/test_embedding_resolve.py b/tests/unit/test_providers/test_embedding_resolve.pynew file mode 100644index 000000000..75626cafb--- /dev/null+++ b/tests/unit/test_providers/test_embedding_resolve.py@@ -0,0 +1,107 @@+"""The shared embedder resolver, and that the CLI, HTTP and MCP servers use it."""++from __future__ import annotations++from pathlib import Path++import pytest++from repowise.core.providers.embedding import resolve+from repowise.core.providers.llm.specs import PROVIDER_SPECS++_VARS = (+ "REPOWISE_EMBEDDER",+ "REPOWISE_EMBEDDING_MODEL",+ "OPENAI_API_KEY",+ "GEMINI_API_KEY",+ "GOOGLE_API_KEY",+ "OPENROUTER_API_KEY",+ "EDENAI_API_KEY",+ "OLLAMA_EMBEDDING_MODEL",+)++[email protected](autouse=True)+def _clean(monkeypatch, tmp_path):+ for var in _VARS:+ monkeypatch.delenv(var, raising=False)+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path / "home"))+++def _repo(tmp_path: Path, config: str = "", env: str = "") -> Path:+ rw = tmp_path / "repo" / ".repowise"+ rw.mkdir(parents=True, exist_ok=True)+ if config:+ (rw / "config.yaml").write_text(config, encoding="utf-8")+ if env:+ (rw / ".env").write_text(env, encoding="utf-8")+ return rw.parent+++def test_key_env_map_comes_from_the_provider_specs():+ expected = {+ name: PROVIDER_SPECS[name].api_key_envs+ for name in ("openai", "gemini", "openrouter", "edenai")+ }+ assert dict(resolve.EMBEDDER_KEY_ENVS) == expected+++def test_precedence_flag_env_pin_detection_default(tmp_path, monkeypatch):+ repo = _repo(tmp_path, "embedder: gemini\n")+ monkeypatch.setenv("OPENAI_API_KEY", "sk")++ assert resolve.resolve_embedder_name("ollama", repo_path=repo) == ("ollama", "flag")+ monkeypatch.setenv("REPOWISE_EMBEDDER", "OpenRouter")+ assert resolve.resolve_embedder_name(repo_path=repo) == ("openrouter", "env:REPOWISE_EMBEDDER")+ monkeypatch.delenv("REPOWISE_EMBEDDER")+ assert resolve.resolve_embedder_name(repo_path=repo) == ("gemini", "config.yaml")+ assert resolve.resolve_embedder_name(repo_path=repo, use_pin=False) == ("openai", "autodetect")+ assert resolve.resolve_embedder_name(detect=False) == ("mock", "default")+++def test_key_chain_env_repo_env_global(tmp_path, monkeypatch):+ repo = _repo(tmp_path, env="OPENAI_API_KEY=from-file\n")+ home = tmp_path / "home" / ".repowise"+ home.mkdir(parents=True)+ (home / "config.yaml").write_text(+ "embedder: openai\nembedder_api_key: from-global\n", encoding="utf-8"+ )++ assert resolve.resolve_embedder_key("openai", repo).key == "from-file"+ assert resolve.resolve_embedder_key("openai").key == "from-global"+ assert resolve.resolve_embedder_key("gemini").key is None # global key names openai+ monkeypatch.setenv("OPENAI_API_KEY", "from-shell")+ assert resolve.resolve_embedder_key("openai", repo).key == "from-shell"+ assert resolve.resolve_embedder_key("ollama") == resolve.KeyLookup(None, ())+++def test_kwargs_pass_the_resolved_key_and_model(tmp_path, monkeypatch):+ repo = _repo(tmp_path, env="GEMINI_API_KEY=g-key\n")+ monkeypatch.setenv("REPOWISE_EMBEDDING_MODEL", "gemini-embedding-002")+ assert resolve.embedder_kwargs("gemini", repo) == {+ "model": "gemini-embedding-002",+ "api_key": "g-key",+ }+++def test_every_entry_point_resolves_the_same_embedder(tmp_path, monkeypatch):+ from repowise.cli.providers.embedders import resolve_embedder_for_repo+ from repowise.server.mcp_server import _server, _state++ repo = _repo(tmp_path, "embedder: openrouter\n", env="OPENROUTER_API_KEY=or-key\n")+ monkeypatch.setattr(_state, "_repo_path", str(repo))++ assert resolve_embedder_for_repo(repo) == "openrouter"+ assert _server._configured_embedder_name() == "openrouter"+ assert _server._embedder_kwargs("openrouter")["api_key"] == "or-key"+++def test_http_server_builds_from_the_shared_resolver(monkeypatch):+ from repowise.core.providers.embedding.base import KeylessEmbedder+ from repowise.core.providers.embedding.openai import OpenAIEmbedder+ from repowise.server.app import _build_embedder++ assert isinstance(_build_embedder(), KeylessEmbedder)+ monkeypatch.setenv("REPOWISE_EMBEDDER", "openai")+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test")+ assert isinstance(_build_embedder(), OpenAIEmbedder)diff --git a/tests/unit/test_providers/test_llm_resolve.py b/tests/unit/test_providers/test_llm_resolve.pynew file mode 100644index 000000000..ffff5dda0--- /dev/null+++ b/tests/unit/test_providers/test_llm_resolve.py@@ -0,0 +1,359 @@+"""The one LLM resolver: precedence, provenance, keys, cache, and the yaml writer."""++from __future__ import annotations++import json+import os+from pathlib import Path++import pytest++from repowise.core.providers.llm import resolve+from repowise.core.providers.llm.resolve import (+ UNSET,+ apply_llm_selection,+ llm_provider_kwargs,+ resolve_api_key,+ resolve_llm,+ save_repo_llm_selection,+ validate_base_url,+)+from repowise.core.providers.llm.specs import PROVIDER_SPECS+from repowise.core.repo_config import RepoConfigError, load_repo_config++_ENV_VARS = (+ "REPOWISE_PROVIDER",+ "REPOWISE_MODEL",+ "OPENAI_API_KEY",+ "OPENAI_BASE_URL",+ "ANTHROPIC_API_KEY",+ "GEMINI_API_KEY",+ "GOOGLE_API_KEY",+ "OPENROUTER_API_KEY",+ "OLLAMA_BASE_URL",+ "DEEPSEEK_API_KEY",+ "KIMI_API_KEY",+ "EDENAI_API_KEY",+)++[email protected](autouse=True)+def _clean(monkeypatch, tmp_path):+ for var in _ENV_VARS:+ monkeypatch.delenv(var, raising=False)+ monkeypatch.setenv("REPOWISE_CONFIG_DIR", str(tmp_path / "global"))+ resolve.clear_cache()+++def _repo(tmp_path: Path, config: str = "", env: str = "") -> Path:+ rw = tmp_path / "repo" / ".repowise"+ rw.mkdir(parents=True, exist_ok=True)+ if config:+ (rw / "config.yaml").write_text(config, encoding="utf-8")+ if env:+ (rw / ".env").write_text(env, encoding="utf-8")+ return rw.parent+++def _global(tmp_path: Path, **data) -> None:+ path = tmp_path / "global" / "provider_config.json"+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(data), encoding="utf-8")+ resolve.forget_cached(path)+++# -- precedence --------------------------------------------------------------+++def test_flag_beats_config_global_and_env(tmp_path, monkeypatch):+ repo = _repo(tmp_path, "provider: openai\nmodel: gpt-a\n")+ _global(tmp_path, active_provider="gemini", active_model="g")+ monkeypatch.setenv("REPOWISE_PROVIDER", "kimi")++ sel = resolve_llm(repo, provider="anthropic", model="claude-x")+ assert (sel.provider, sel.model) == ("anthropic", "claude-x")+ assert sel.provenance == {"provider": "flag", "model": "flag", "base_url": None}+++def test_config_beats_global_and_env(tmp_path, monkeypatch):+ repo = _repo(tmp_path, "provider: openai\nmodel: gpt-a\n")+ _global(tmp_path, active_provider="gemini", active_model="g")+ monkeypatch.setenv("REPOWISE_PROVIDER", "kimi")+ monkeypatch.setenv("REPOWISE_MODEL", "k")++ sel = resolve_llm(repo)+ assert (sel.provider, sel.model) == ("openai", "gpt-a")+ assert sel.provider_source == sel.model_source == "config.yaml"+++def test_global_beats_env(tmp_path, monkeypatch):+ repo = _repo(tmp_path, "embedder: mock\n")+ _global(tmp_path, active_provider="gemini", active_model="g")+ monkeypatch.setenv("REPOWISE_PROVIDER", "kimi")++ sel = resolve_llm(repo)+ assert (sel.provider, sel.model, sel.provider_source) == ("gemini", "g", "global")+++def test_env_then_spec_default(tmp_path, monkeypatch):+ repo = _repo(tmp_path)+ monkeypatch.setenv("REPOWISE_PROVIDER", "kimi")++ sel = resolve_llm(repo)+ assert sel.provider == "kimi"+ assert sel.provider_source == "env:REPOWISE_PROVIDER"+ assert (sel.model, sel.model_source) == (PROVIDER_SPECS["kimi"].default_model, "default")+++def test_env_reads_the_repo_env_file(tmp_path):+ repo = _repo(tmp_path, env="REPOWISE_PROVIDER=deepseek\n")+ assert resolve_llm(repo).provider == "deepseek"+++def test_autodetect_from_keys_including_stored_ones(tmp_path):+ repo = _repo(tmp_path)+ assert resolve_llm(repo).provider is None++ _global(tmp_path, keys={"openrouter": "sk-or"})+ sel = resolve_llm(repo)+ assert (sel.provider, sel.provider_source) == ("openrouter", "autodetect")+ assert resolve_llm(repo, autodetect=False).provider is None+++def test_a_model_only_follows_its_own_provider(tmp_path):+ repo = _repo(tmp_path, "provider: gemini\nmodel: gemini-3.1-pro-preview\n")+ sel = resolve_llm(repo, provider="openai")+ assert sel.model == PROVIDER_SPECS["openai"].default_model+++def test_a_model_without_a_provider_applies_to_the_resolved_one(tmp_path, monkeypatch):+ repo = _repo(tmp_path, "model: my-local-model\n")+ monkeypatch.setenv("REPOWISE_PROVIDER", "openai")+ sel = resolve_llm(repo)+ assert (sel.provider, sel.model, sel.model_source) == (+ "openai",+ "my-local-model",+ "config.yaml",+ )+++def test_known_filters_out_providers_the_caller_cannot_build(tmp_path):+ repo = _repo(tmp_path, "provider: mock\nmodel: m\n")+ _global(tmp_path, active_provider="anthropic")+ sel = resolve_llm(repo, known={"anthropic", "openai"})+ assert (sel.provider, sel.provider_source) == ("anthropic", "global")+ assert sel.model == PROVIDER_SPECS["anthropic"].default_model+++# -- base URL ----------------------------------------------------------------+++def test_base_url_precedence(tmp_path, monkeypatch):+ repo = _repo(tmp_path, "provider: openai\nopenai:\n base_url: http://yaml:1/v1\n")+ _global(tmp_path, active_provider="openai", active_base_url="http://global:1/v1")+ monkeypatch.setenv("OPENAI_BASE_URL", "http://env:1/v1")++ assert resolve_llm(repo, base_url="http://flag:1/v1").base_url == "http://flag:1/v1"+ sel = resolve_llm(repo)+ assert (sel.base_url, sel.base_url_source) == ("http://yaml:1/v1", "config.yaml")++ save_repo_llm_selection(repo, "openai", None, base_url=None)+ sel = resolve_llm(repo)+ assert (sel.base_url, sel.base_url_source) == ("http://global:1/v1", "global")++ _global(tmp_path, active_provider="openai")+ sel = resolve_llm(repo)+ assert (sel.base_url, sel.base_url_source) == ("http://env:1/v1", "env:OPENAI_BASE_URL")+++def test_global_base_url_only_applies_to_its_provider(tmp_path):+ repo = _repo(tmp_path, "provider: kimi\n")+ _global(tmp_path, active_provider="openai", active_base_url="http://lm:1234/v1")+ assert resolve_llm(repo).base_url is None+++# -- keys and kwargs ---------------------------------------------------------+++def test_key_chain_env_then_repo_env_then_stored(tmp_path, monkeypatch):+ repo = _repo(tmp_path, env="OPENAI_API_KEY=from-file\n")+ _global(tmp_path, keys={"openai": "from-store"})++ monkeypatch.setenv("OPENAI_API_KEY", "from-shell")+ assert resolve_api_key("openai", repo) == ("from-shell", "env:OPENAI_API_KEY")+ monkeypatch.delenv("OPENAI_API_KEY")+ assert resolve_api_key("openai", repo) == ("from-file", ".repowise/.env")+ assert resolve_api_key("openai", None) == ("from-store", "provider_config.json")+++def test_kwargs_carry_key_url_and_repo_path(tmp_path):+ repo = _repo(+ tmp_path,+ "provider: openai\nmodel: qwen3\nopenai:\n base_url: http://localhost:1234/v1\n",+ env="OPENAI_API_KEY=lm-studio\n",+ )+ kwargs = llm_provider_kwargs(resolve_llm(repo), repo)+ assert kwargs == {+ "model": "qwen3",+ "api_key": "lm-studio",+ "base_url": "http://localhost:1234/v1",+ }+ assert llm_provider_kwargs(resolve_llm(repo, provider="codex_cli"), repo)["repo_path"] == repo+++# -- cache -------------------------------------------------------------------+++def test_files_are_parsed_once_per_version(tmp_path, monkeypatch):+ repo = _repo(tmp_path, "provider: openai\n")+ calls = []+ real = resolve._parse_repo_config+ monkeypatch.setattr(resolve, "_parse_repo_config", lambda p: calls.append(p) or real(p))++ for _ in range(5):+ resolve_llm(repo)+ assert len(calls) == 1++ save_repo_llm_selection(repo, "anthropic", "claude-x")+ assert resolve_llm(repo).provider == "anthropic"+ assert len(calls) == 2+++# -- writer ------------------------------------------------------------------+++def test_writer_keeps_other_keys_and_sets_or_clears_base_url(tmp_path):+ repo = _repo(tmp_path, "provider: gemini\nmodel: g\nembedder: gemini\ncommit_limit: 50\n")++ save_repo_llm_selection(repo, "openai", "qwen3", base_url="http://localhost:1234/v1")+ cfg = load_repo_config(repo)+ assert cfg["provider"] == "openai" and cfg["model"] == "qwen3"+ assert cfg["openai"] == {"base_url": "http://localhost:1234/v1"}+ assert cfg["embedder"] == "gemini" and cfg["commit_limit"] == 50++ save_repo_llm_selection(repo, "openai", "other") # base_url left as is+ assert load_repo_config(repo)["openai"]["base_url"] == "http://localhost:1234/v1"++ save_repo_llm_selection(repo, "openai", None, base_url="")+ cfg = load_repo_config(repo)+ assert "openai" not in cfg and "model" not in cfg+++def test_writer_keeps_unrelated_keys_in_the_provider_section():+ cfg = {"openai": {"base_url": "http://x/v1", "timeout": 5}}+ apply_llm_selection(cfg, "openai", "m", base_url=None)+ assert cfg["openai"] == {"timeout": 5}+ assert apply_llm_selection({}, "openai", "m", UNSET) == {"provider": "openai", "model": "m"}+++def test_writer_refuses_to_overwrite_a_broken_file(tmp_path):+ repo = _repo(tmp_path, "provider: [unclosed\n")+ with pytest.raises(RepoConfigError):+ save_repo_llm_selection(repo, "openai", "m")+ assert (repo / ".repowise" / "config.yaml").read_text(encoding="utf-8") == "provider: [unclosed\n"+++ ("value", "expected"),+ [("", None), (None, None), (" http://localhost:1234/v1 ", "http://localhost:1234/v1")],+)+def test_validate_base_url_accepts(value, expected):+ assert validate_base_url(value) == expected++[email protected]("value", ["localhost:1234", "ftp://x", "http://", "file:///etc"])+def test_validate_base_url_rejects(value):+ with pytest.raises(ValueError, match="http"):+ validate_base_url(value)+++def test_a_same_size_rewrite_is_seen(tmp_path):+ """Two writes of equal length inside one timestamp tick, as another process would."""+ repo = _repo(tmp_path, "provider: openai\n")+ path = repo / ".repowise" / "config.yaml"+ assert resolve_llm(repo).provider == "openai"+ stat = path.stat()+ path.write_text("provider: gemini\n", encoding="utf-8")+ os.utime(path, ns=(stat.st_atime_ns, stat.st_mtime_ns))+ assert resolve_llm(repo).provider == "gemini"+++# -- base URL trust ------------------------------------------------------------++_REMOTE = "provider: openai\nopenai:\n base_url: https://collector.example/v1\n"+++def test_untrusted_yaml_base_url_does_not_get_an_outside_key(tmp_path, monkeypatch):+ repo = _repo(tmp_path, _REMOTE)+ monkeypatch.setenv("OPENAI_API_KEY", "sk-shell")+ with pytest.raises(resolve.UntrustedBaseUrlError, match=r"collector\.example") as info:+ llm_provider_kwargs(resolve_llm(repo), repo)+ assert "sk-shell" not in str(info.value)++ _global(tmp_path, keys={"openai": "sk-stored"})+ monkeypatch.delenv("OPENAI_API_KEY")+ with pytest.raises(resolve.UntrustedBaseUrlError):+ llm_provider_kwargs(resolve_llm(repo), repo)+++def test_trusted_yaml_base_url_gets_the_key(tmp_path, monkeypatch):+ repo = _repo(tmp_path, _REMOTE)+ monkeypatch.setenv("OPENAI_API_KEY", "sk-shell")+ resolve.trust_base_url(repo, "https://collector.example/v1")+ assert llm_provider_kwargs(resolve_llm(repo), repo)["api_key"] == "sk-shell"+++def test_repo_env_key_and_loopback_urls_need_no_confirmation(tmp_path, monkeypatch):+ repo = _repo(tmp_path, _REMOTE, env="OPENAI_API_KEY=sk-repo\n")+ assert llm_provider_kwargs(resolve_llm(repo), repo)["api_key"] == "sk-repo"++ monkeypatch.setenv("OPENAI_API_KEY", "sk-shell")+ for url in ("http://localhost:1234/v1", "http://127.0.0.1:8000/v1", "http://[::1]:9/v1"):+ save_repo_llm_selection(repo, "openai", None, base_url=url)+ assert llm_provider_kwargs(resolve_llm(repo), repo)["base_url"] == url+++def test_keyless_request_to_an_unconfirmed_url_is_allowed(tmp_path):+ repo = _repo(tmp_path, _REMOTE)+ assert "api_key" not in llm_provider_kwargs(resolve_llm(repo), repo)+++def test_credentials_in_a_base_url_are_refused_and_never_shown(tmp_path):+ with pytest.raises(ValueError, match="user name or password") as info:+ validate_base_url("https://me:[email protected]/v1")+ assert "hunter2" not in str(info.value)++ repo = _repo(tmp_path, "provider: openai\nopenai:\n base_url: https://me:[email protected]/v1\n")+ sel = resolve_llm(repo)+ assert sel.display_base_url == "https://gw.example/v1"+ assert "hunter2" not in sel.describe()+ with pytest.raises(ValueError, match=r"config\.yaml") as info:+ llm_provider_kwargs(sel, repo)+ assert "hunter2" not in str(info.value)++[email protected]("writer", ["config.yaml", "provider_config.json"])+def test_writers_retry_while_a_reader_holds_the_file(tmp_path, monkeypatch, writer):+ """Windows refuses a replace while another thread has the file open."""+ from repowise.core import fsutils+ from repowise.core.repo_config import save_repo_config++ real_replace = os.replace+ refusals = []++ def busy_then_free(src, dst):+ if len(refusals) < 3:+ refusals.append(dst)+ raise PermissionError(13, "Access is denied")+ real_replace(src, dst)++ monkeypatch.setattr(fsutils.os, "replace", busy_then_free)+ monkeypatch.setattr(fsutils.time, "sleep", lambda _s: None)+ repo = _repo(tmp_path)+ if writer == "config.yaml":+ save_repo_config(repo, {"provider": "openai"})+ assert load_repo_config(repo) == {"provider": "openai"}+ else:+ resolve.update_global_config(lambda config: config.update(active_provider="kimi"))+ assert resolve.read_global_config()["active_provider"] == "kimi"+ assert len(refusals) == 3diff --git a/tests/unit/test_providers/test_provider_specs.py b/tests/unit/test_providers/test_provider_specs.pyindex e43a4e035..1fab7a39c 100644--- a/tests/unit/test_providers/test_provider_specs.py+++ b/tests/unit/test_providers/test_provider_specs.py@@ -100,14 +100,13 @@ _ALLOWED: dict[str, frozenset[str]] = {"server/src/repowise/server/mcp_server/tool_answer/synthesis.py": frozenset({"openai"}),# Embedder surfaces: these literals name embedders, which share spellings."core/src/repowise/core/providers/embedding/registry.py": _EMBEDDERS,+ "core/src/repowise/core/providers/embedding/resolve.py": _EMBEDDERS,"cli/src/repowise/cli/commands/init_cmd/command.py": _EMBEDDERS,"cli/src/repowise/cli/commands/reindex_cmd.py": _EMBEDDERS,"cli/src/repowise/cli/commands/serve_cmd.py": _EMBEDDERS,"cli/src/repowise/cli/commands/update_cmd/deterministic.py": _EMBEDDERS,"cli/src/repowise/cli/providers/embedders.py": _EMBEDDERS,- "cli/src/repowise/cli/providers/keys.py": _EMBEDDERS,"cli/src/repowise/cli/ui/mode_selection.py": _EMBEDDERS,- "server/src/repowise/server/app.py": _EMBEDDERS,"server/src/repowise/server/mcp_server/_server.py": _EMBEDDERS,}