Skip to content

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

26.0 KB
Raw Blame
"""Per-repo chat provider resolution (issue #426).

The web-UI chat must use the provider/model/API-key/base-url that
``repowise init`` wrote to each repo's ``.repowise/config.yaml`` +
``.repowise/.env`` — the same configuration ``repowise update`` already
honours — instead of falling back to a hardcoded catalog default. Selecting a
model for one repo must not shadow another repo in a workspace.
"""

from __future__ import annotations

import textwrap
from pathlib import Path

import pytest

from repowise.server import provider_config as pc


@pytest.fixture
def clean_env(monkeypatch, tmp_path):
    """Replace ``os.environ`` with a minimal dict and isolate the config file.

    The dev machine often has real ``*_API_KEY`` vars exported, which would
    otherwise leak into auto-detection and make these assertions flaky.
    """
    env: dict[str, str] = {"REPOWISE_CONFIG_DIR": str(tmp_path / "server")}
    monkeypatch.setattr(pc.os, "environ", env)
    return env


def _make_repo(root: Path, *, config: str = "", env: str = "") -> Path:
    """Create a repo dir with ``.repowise/config.yaml`` and ``.repowise/.env``."""
    rw = root / ".repowise"
    rw.mkdir(parents=True, exist_ok=True)
    if config:
        (rw / "config.yaml").write_text(textwrap.dedent(config), encoding="utf-8")
    if env:
        (rw / ".env").write_text(textwrap.dedent(env), encoding="utf-8")
    return root


# ---------------------------------------------------------------------------
# The reported bug: repo config.yaml model is ignored, default is used.
# ---------------------------------------------------------------------------


def test_repo_config_model_used_without_ui_selection(clean_env, tmp_path):
    repo = _make_repo(
        tmp_path / "repo",
        config="""
            provider: openai
            model: gemma4
            embedder: openai
        """,
        env="OPENAI_API_KEY=admin\nOPENAI_BASE_URL=http://localhost:4000/v1\n",
    )

    provider, model = pc.get_active_provider(repo_id="r1", repo_path=str(repo))
    assert provider == "openai"
    assert model == "gemma4"  # not the catalog default gpt-5.4-nano


def test_get_chat_provider_passes_repo_key_model_and_base_url(clean_env, tmp_path, monkeypatch):
    repo = _make_repo(
        tmp_path / "repo",
        config="""
            provider: openai
            model: gemma4
            embedder: openai
        """,
        env="OPENAI_API_KEY=admin\nOPENAI_BASE_URL=http://localhost:4000/v1\n",
    )

    captured: dict = {}

    def fake_get_provider(provider_id, **kwargs):
        captured["provider_id"] = provider_id
        captured.update(kwargs)
        return object()

    monkeypatch.setattr("repowise.core.providers.llm.registry.get_provider", fake_get_provider)

    pc.get_chat_provider_instance(repo_path=str(repo), repo_id="r1")

    assert captured["provider_id"] == "openai"
    assert captured["model"] == "gemma4"
    assert captured["api_key"] == "admin"  # from .repowise/.env
    assert captured["base_url"] == "http://localhost:4000/v1"


@pytest.mark.parametrize("provider_id", ["codex_cli", "opencode"])
def test_get_chat_provider_passes_path_to_repo_aware_provider(
    clean_env, tmp_path, monkeypatch, provider_id
):
    repo = _make_repo(tmp_path / "repo")
    captured: dict = {}

    monkeypatch.setattr(
        "repowise.core.providers.llm.registry.get_provider",
        lambda selected, **kwargs: captured.update({"id": selected, **kwargs}) or object(),
    )

    pc.get_chat_provider_instance(
        repo_path=repo,
        provider_override=provider_id,
        model_override="",
    )

    assert captured["id"] == provider_id
    assert captured["repo_path"] == repo


def test_kimi_repo_config_passes_key_model_and_base_url(clean_env, tmp_path, monkeypatch):
    repo = _make_repo(
        tmp_path / "repo",
        config="""
            provider: kimi
            model: kimi-k2.6
            embedder: mock
        """,
        env="KIMI_API_KEY=sk-kimi-test\nKIMI_BASE_URL=https://kimi.example/v1\n",
    )

    captured: dict = {}

    def fake_get_provider(provider_id, **kwargs):
        captured["provider_id"] = provider_id
        captured.update(kwargs)
        return object()

    monkeypatch.setattr("repowise.core.providers.llm.registry.get_provider", fake_get_provider)

    pc.get_chat_provider_instance(repo_path=str(repo), repo_id="kimi-repo")

    assert captured["provider_id"] == "kimi"
    assert captured["model"] == "kimi-k2.6"
    assert captured["api_key"] == "sk-kimi-test"
    assert captured["base_url"] == "https://kimi.example/v1"


# ---------------------------------------------------------------------------
# Precedence + no cross-repo shadowing.
# ---------------------------------------------------------------------------


def test_per_repo_selection_does_not_shadow_other_repo(clean_env, tmp_path):
    repo_a = _make_repo(
        tmp_path / "a",
        config="provider: openai\nmodel: gemma4\nembedder: openai\n",
        env="OPENAI_API_KEY=admin\n",
    )
    repo_b = _make_repo(
        tmp_path / "b",
        config="provider: openai\nmodel: codellama\nembedder: openai\n",
        env="OPENAI_API_KEY=admin\n",
    )

    # User picks a different model for repo A via the UI.
    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))

    assert (a_provider, a_model) == ("openai", "gpt-5.4")  # A's override
    assert (b_provider, b_model) == ("openai", "codellama")  # B untouched


def test_request_override_beats_repo_config(clean_env, tmp_path, monkeypatch):
    repo = _make_repo(
        tmp_path / "repo",
        config="provider: openai\nmodel: gemma4\nembedder: openai\n",
        env="OPENAI_API_KEY=admin\nANTHROPIC_API_KEY=sk-ant\n",
    )

    captured: dict = {}
    monkeypatch.setattr(
        "repowise.core.providers.llm.registry.get_provider",
        lambda provider_id, **kw: captured.update({"id": provider_id, **kw}) or object(),
    )

    pc.get_chat_provider_instance(
        repo_path=str(repo),
        repo_id="r1",
        provider_override="anthropic",
        model_override="claude-opus-4-6",
    )

    assert captured["id"] == "anthropic"
    assert captured["model"] == "claude-opus-4-6"


# ---------------------------------------------------------------------------
# Status surfaces the configured (possibly custom) model for the picker.
# ---------------------------------------------------------------------------


def test_list_provider_status_surfaces_custom_model(clean_env, tmp_path):
    repo = _make_repo(
        tmp_path / "repo",
        config="provider: openai\nmodel: gemma4\nembedder: openai\n",
        env="OPENAI_API_KEY=admin\n",
    )

    status = pc.list_provider_status(repo_id="r1", repo_path=str(repo))

    assert (status["active"]["provider"], status["active"]["model"]) == ("openai", "gemma4")
    openai = next(p for p in status["providers"] if p["id"] == "openai")
    assert "gemma4" in openai["models"]  # custom model is selectable
    assert openai["configured"] is True  # key seen via repo .env


def test_repo_env_key_enables_autodetect(clean_env, tmp_path):
    # No provider in config — only a key in the repo .env. Auto-detect should
    # still find it (without the server holding the key in its own environ).
    repo = _make_repo(
        tmp_path / "repo",
        config="embedder: openai\n",
        env="OPENAI_API_KEY=admin\n",
    )

    provider, _ = pc.get_active_provider(repo_id="r1", repo_path=str(repo))
    assert provider == "openai"


def test_unknown_provider_override_raises(clean_env, tmp_path):
    repo = _make_repo(
        tmp_path / "repo",
        config="provider: openai\nmodel: gemma4\nembedder: openai\n",
        env="OPENAI_API_KEY=admin\n",
    )
    with pytest.raises(ValueError, match="Unknown provider"):
        pc.get_chat_provider_instance(repo_path=str(repo), repo_id="r1", provider_override="bogus")


def test_global_selection_used_when_repo_has_no_config(clean_env, tmp_path):
    repo = _make_repo(tmp_path / "repo", config="embedder: mock\n")
    pc.set_active_provider("anthropic", "claude-sonnet-4-6")  # global default

    provider, model = pc.get_active_provider(repo_id="r1", repo_path=str(repo))
    assert (provider, model) == ("anthropic", "claude-sonnet-4-6")


# ---------------------------------------------------------------------------
# D6: set_api_key mirrors into the repo's .repowise/.env so the CLI sees it.
# ---------------------------------------------------------------------------


def test_set_api_key_mirrors_into_repo_env(clean_env, tmp_path):
    repo = _make_repo(tmp_path / "repo", config="embedder: mock\n")

    pc.set_api_key("anthropic", "sk-ant-xyz", repo_path=str(repo))

    # Server store updated...
    assert pc._get_key_for_provider("anthropic") == "sk-ant-xyz"
    # ...and mirrored under the provider's canonical env var so a later CLI run
    # (which reads .env, not the server store) picks it up.
    from repowise.core.repo_config import load_repo_env

    assert load_repo_env(repo)["ANTHROPIC_API_KEY"] == "sk-ant-xyz"


def test_set_api_key_removal_clears_repo_env(clean_env, tmp_path):
    repo = _make_repo(tmp_path / "repo", config="embedder: mock\n")
    pc.set_api_key("anthropic", "sk-ant-xyz", repo_path=str(repo))

    pc.set_api_key("anthropic", None, repo_path=str(repo))

    from repowise.core.repo_config import load_repo_env

    assert "ANTHROPIC_API_KEY" not in load_repo_env(repo)


def test_set_api_key_without_repo_path_is_global_only(clean_env, tmp_path):
    repo = _make_repo(tmp_path / "repo", config="embedder: mock\n")

    pc.set_api_key("anthropic", "sk-ant-xyz")  # no repo_path

    assert pc._get_key_for_provider("anthropic") == "sk-ant-xyz"
    assert not (repo / ".repowise" / ".env").exists()


def test_set_api_key_keyless_provider_writes_no_env(clean_env, tmp_path):
    # Ollama takes no key (empty env_keys); there is nothing to mirror.
    repo = _make_repo(tmp_path / "repo", config="embedder: mock\n")

    pc.set_api_key("ollama", "irrelevant", repo_path=str(repo))

    assert not (repo / ".repowise" / ".env").exists()


def test_set_api_key_rejects_newline_in_value(clean_env, tmp_path):
    # A value with a newline would inject extra env lines a later CLI run parses.
    repo = _make_repo(tmp_path / "repo", config="embedder: mock\n")
    with pytest.raises(ValueError, match="newline"):
        pc.set_api_key("anthropic", "sk-ant\nEVIL=1", repo_path=str(repo))


def test_config_path_defaults_to_home(monkeypatch, tmp_path):
    # No REPOWISE_CONFIG_DIR: the store lives in ~/.repowise, not the CWD.
    monkeypatch.setattr(pc.os, "environ", {})
    monkeypatch.setattr(pc.Path, "home", classmethod(lambda cls: tmp_path))
    assert pc._config_path() == tmp_path / ".repowise" / "provider_config.json"


def test_list_provider_status_carries_setup_facts_from_the_specs(clean_env, tmp_path):
    """The settings UIs render these instead of keeping provider tables."""
    status = pc.list_provider_status()
    by_id = {p["id"]: p for p in status["providers"]}

    assert by_id["gemini"]["requires_key"] is True
    assert by_id["gemini"]["env_vars"] == ["GEMINI_API_KEY", "GOOGLE_API_KEY"]
    assert by_id["ollama"]["requires_key"] is False
    assert by_id["ollama"]["env_vars"] == ["OLLAMA_BASE_URL"]
    assert by_id["codex_cli"]["requires_key"] is False
    assert "codex login" in by_id["codex_cli"]["setup_hint"]
    assert "mock" not in by_id
    assert status["flag_only_providers"] == ["mock"]


def test_list_provider_status_names_where_a_key_was_found(clean_env, tmp_path):
    repo = _make_repo(tmp_path / "repo", env="OPENAI_API_KEY=sk-from-repo-env\n")
    clean_env["GEMINI_API_KEY"] = "from-process-env"
    pc.set_api_key("anthropic", "sk-ant-stored")

    by_id = {p["id"]: p for p in pc.list_provider_status(repo_path=str(repo))["providers"]}

    assert by_id["openai"]["detected"] == "env"
    assert by_id["gemini"]["detected"] == "env"
    assert by_id["anthropic"]["detected"] == "saved"
    assert by_id["deepseek"]["detected"] is None
    # Keyless providers name nothing; agent CLIs only when asked to detect.
    assert by_id["ollama"]["detected"] is None
    assert by_id["claude_cli"]["detected"] is None


def test_detect_names_signed_in_agent_clis(clean_env, monkeypatch):
    from repowise.core.agents.identity import AgentIdentity

    calls: list[str] = []

    def is_logged_in(self):
        calls.append(self.slug)
        return self.slug == "claude_code"

    monkeypatch.setattr(AgentIdentity, "is_logged_in", is_logged_in)

    assert {p["detected"] for p in pc.list_provider_status()["providers"]} == {None}
    assert calls == []

    by_id = {p["id"]: p for p in pc.list_provider_status(detect=True)["providers"]}
    assert by_id["claude_cli"]["detected"] == "signed_in"
    assert by_id["codex_cli"]["detected"] is None
    assert "codex" in calls


def test_detect_never_reports_signed_in_for_an_agent_without_a_login_check(clean_env, monkeypatch):
    import shutil

    monkeypatch.setattr(shutil, "which", lambda name: f"/bin/{name}")
    by_id = {p["id"]: p for p in pc.list_provider_status(detect=True)["providers"]}
    assert by_id["opencode"]["detected"] == "installed"
    assert by_id["copilot_cli"]["detected"] == "installed"


def test_detect_does_not_run_login_checks_when_the_network_is_off(clean_env, monkeypatch):
    import shutil
    import subprocess

    clean_env["DO_NOT_TRACK"] = "1"
    monkeypatch.setattr(shutil, "which", lambda name: f"/bin/{name}")

    def fail(*args, **kwargs):
        raise AssertionError("a login check was spawned with DO_NOT_TRACK set")

    monkeypatch.setattr(subprocess, "run", fail)
    by_id = {p["id"]: p for p in pc.list_provider_status(detect=True)["providers"]}
    assert by_id["claude_cli"]["detected"] == "installed"
    assert by_id["codex_cli"]["detected"] == "installed"


def test_a_broken_login_check_counts_as_not_signed_in(clean_env, monkeypatch):
    from repowise.core.agents.identity import AgentIdentity

    def is_logged_in(self):
        raise RuntimeError("boom")

    monkeypatch.setattr(AgentIdentity, "is_logged_in", is_logged_in)
    by_id = {p["id"]: p for p in pc.list_provider_status(detect=True)["providers"]}
    assert by_id["claude_cli"]["detected"] is None


def test_list_provider_status_carries_the_embedder_registry(clean_env, tmp_path, monkeypatch):
    from repowise.core.providers.embedding import registry

    monkeypatch.setitem(registry._custom_embedders, "voyage", lambda **_kw: None)
    clean_env["REPOWISE_EMBEDDER"] = "Gemini"
    status = pc.list_provider_status()
    by_id = {e["id"]: e for e in status["embedders"]}

    assert set(by_id) == set(registry.list_embedders())
    assert status["embedders"][0]["id"] == registry.DEFAULT_EMBEDDER
    assert by_id["gemini"]["env_vars"] == ["GEMINI_API_KEY", "GOOGLE_API_KEY"]
    assert by_id["mock"] == {"id": "mock", "env_vars": [], "semantic": False}
    assert by_id["voyage"] == {"id": "voyage", "env_vars": [], "semantic": True}
    assert status["active"]["embedder"] == "gemini"


def test_list_provider_status_prices_the_active_model(clean_env, tmp_path):
    from repowise.core.cost_estimator import lookup_cost

    def rates(provider, model):
        pc.set_active_provider(provider, model)
        active = pc.list_provider_status()["active"]
        return active["input_cost_per_1k"], active["output_cost_per_1k"]

    assert rates("openai", "gpt-5.4-mini") == lookup_cost("gpt-5.4-mini")
    # Unpriced is unknown, not free; a local model is free.
    assert rates("openai", "gpt-4o") == (None, None)
    assert rates("ollama", "qwen3.5:4b") == (0.0, 0.0)


def test_list_provider_status_never_returns_key_material(clean_env, tmp_path):
    repo = _make_repo(
        tmp_path / "repo",
        config="provider: openai\nmodel: gpt-5.4-nano\nembedder: openai\n",
        env="OPENAI_API_KEY=super-secret-key\n",
    )

    status = pc.list_provider_status(repo_id="r1", repo_path=str(repo))

    serialized = repr(status)
    assert "super-secret-key" not in serialized
    for provider in status["providers"]:
        assert set(provider) == {
            "id",
            "name",
            "models",
            "default_model",
            "configured",
            "requires_key",
            "accepts_base_url",
            "local_server",
            "local_model",
            "env_vars",
            "setup_hint",
            "detected",
        }
        assert "key" not in provider
        assert "api_key" not in provider


def test_configured_active_provider_needs_the_key_chat_needs(clean_env, tmp_path):
    """A configured provider without its key is reported as none, not as usable."""
    repo = _make_repo(tmp_path / "repo", config="provider: anthropic\nmodel: claude-x\n")
    assert pc.get_active_provider(repo_path=repo) == ("anthropic", "claude-x")
    assert pc.get_configured_active_provider(repo_path=repo) == (None, None)

    _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)