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
feat(update): onboard a provider when a docs update needs one (#917)
Raghav Chamadiya9b38f07539a9
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.pyindex 199cfe03b..8911cbaa5 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py@@ -28,7 +28,7 @@ from repowise.cli.helpers import (read_update_pending,release_update_lock,resolve_command_target,- resolve_provider,+ resolve_provider_or_prompt,resolve_reasoning,rotate_update_log_if_needed,run_async,@@ -64,6 +64,18 @@ from .workspace import _workspace_updatelog = structlog.get_logger(__name__)+def _docs_provider_prompt_allowed(emitter: Any) -> bool:+ """Whether a docs run may block on an interactive provider prompt.++ Requires a real terminal on *both* ends: a terminal stdout (so the table+ renders) and a tty stdin (so the answer can actually be read). The stdin+ check is what keeps a background post-commit hook or CI run from hanging+ even when it inherits a ``FORCE_COLOR`` that makes ``console.is_terminal``+ report True. ``--progress json`` (emitter set) is always non-interactive.+ """+ return console.is_terminal and sys.stdin.isatty() and emitter is None++def _record_update_outcome(*,index_only: bool,@@ -830,7 +842,20 @@ def run_update(tier2_tail_dirs=tuple(tail_dirs_cfg) if tail_dirs_cfg else None,)- provider = resolve_provider(provider_name, model, repo_path=repo_path)+ # Resolve the generation provider. If the repo wants docs but was never+ # given a provider/key (e.g. it started --index-only and later flipped+ # docs_enabled on, or `repowise update --docs`), onboard the same way init+ # does: prompt for provider + key and persist, but only in an interactive+ # terminal. Hooks / CI / --progress json keep the clean non-blocking error.+ # In the workspace docs flow each member reaches this per-repo run; the+ # first prompt sets the key in-process, so later members auto-resolve.+ provider = resolve_provider_or_prompt(+ provider_name,+ model,+ repo_path,+ reasoning=reasoning,+ interactive=_docs_provider_prompt_allowed(emitter),+ )# Attach a DB-backed CostTracker so every LLM call made during this update# (decision rescan + page regeneration) is persisted to the `llm_costs`diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.pyindex d73653725..d898579bd 100644--- a/packages/cli/src/repowise/cli/helpers.py+++ b/packages/cli/src/repowise/cli/helpers.py@@ -722,6 +722,51 @@ def resolve_provider()+def resolve_provider_or_prompt(+ provider_name: str | None,+ model: str | None,+ repo_path: Path,+ *,+ reasoning: str | None = None,+ interactive: bool,+) -> Any:+ """Resolve a provider, falling back to init's interactive setup on a miss.++ Ordinary resolution is :func:`resolve_provider`. When that fails because no+ provider/key is configured and ``interactive`` is set (an interactive+ terminal, not a hook / CI / ``--progress json`` run), reuse init's exact+ provider + API-key prompt, persist the choice, and retry — so a docs run+ that only just gained ``docs_enabled`` onboards the same way ``init`` does+ instead of dying with "No provider configured".++ When ``interactive`` is False the original error propagates unchanged, so+ background runs (post-commit hook, CI, machine-driven ``--progress json``)+ keep their clean, non-blocking failure.++ Persistence reuses init's helpers: the key lands in ``.repowise/.env`` (from+ the prompt) and provider/model in ``.repowise/config.yaml`` here, so the+ prompt only ever appears once per repo.+ """+ try:+ return resolve_provider(provider_name, model, repo_path=repo_path)+ except Exception:+ if not interactive:+ raise+ from repowise.cli.ui import interactive_provider_config_select++ selection = interactive_provider_config_select(+ console, model, reasoning, repo_path=repo_path+ )+ # Persist provider/model so future runs resolve without re-prompting.+ # The API key was already persisted to .repowise/.env by the prompt.+ save_config_partial(+ repo_path,+ provider=selection.provider_name,+ model=selection.model,+ )+ return resolve_provider(selection.provider_name, selection.model, repo_path=repo_path)++# ---------------------------------------------------------------------------# Provider validation# ---------------------------------------------------------------------------diff --git a/tests/unit/cli/test_update_provider_prompt.py b/tests/unit/cli/test_update_provider_prompt.pynew file mode 100644index 000000000..03720115b--- /dev/null+++ b/tests/unit/cli/test_update_provider_prompt.py@@ -0,0 +1,183 @@+"""``repowise update`` onboards a provider when a docs run needs one.++A repo can start life ``--index-only`` and later flip ``docs_enabled`` on (via+config or ``repowise update --docs``) without a provider/key ever being+configured. In an interactive terminal the docs run should prompt for the+provider + key exactly like ``init`` does, persist the choice, and continue,+rather than dying with "No provider configured". In a non-interactive run+(hook / CI / ``--progress json``) it must stay a clean, non-blocking failure.+"""++from __future__ import annotations++import asyncio+import json+import subprocess+from pathlib import Path++import yaml+from click.testing import CliRunner++from repowise.cli.main import cli+from repowise.cli.ui.provider_selection import ProviderSelection++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _git(repo: Path, *args: str) -> str:+ result = subprocess.run(["git", *args], cwd=str(repo), capture_output=True, text=True)+ return result.stdout.strip()+++def _make_git_repo(tmp_path: Path) -> Path:+ repo = tmp_path / "repo"+ repo.mkdir(parents=True)+ _git(repo, "init")+ _git(repo, "config", "user.email", "[email protected]")+ _git(repo, "config", "user.name", "Test")+ # Ignore the index dir so `git add .` never commits repowise's own+ # artifacts — commit hashes then track only the source changes below.+ (repo / ".gitignore").write_text(".repowise/\n")+ (repo / "a.py").write_text("def alpha():\n return 1\n")+ (repo / "b.py").write_text("from a import alpha\n\n\ndef beta():\n return alpha() + 1\n")+ _git(repo, "add", ".")+ _git(repo, "commit", "-m", "initial")+ return repo+++def _index_full(repo: Path) -> None:+ """Real index-only init: full pipeline + persistence, no provider/key."""+ from repowise.core.pipeline.full_index import index_repo_full++ asyncio.run(index_repo_full(repo))+++def _commit_change(repo: Path, name: str, body: str) -> str:+ (repo / name).write_text(body)+ _git(repo, "add", ".")+ _git(repo, "commit", "-m", f"add {name}")+ return _git(repo, "rev-parse", "HEAD")+++def _config(repo: Path) -> dict:+ text = (repo / ".repowise" / "config.yaml").read_text(encoding="utf-8")+ return yaml.safe_load(text) or {}+++def _prep_docs_repo_without_provider(tmp_path: Path) -> tuple[Path, str]:+ """Index-only repo that now wants docs, with no provider/key configured."""+ repo = _make_git_repo(tmp_path)+ _index_full(repo)+ base = _git(repo, "rev-parse", "HEAD")++ from repowise.cli.helpers import save_state++ # docs_enabled flipped on after an index-only start; the docs pointer sits+ # at the indexed commit so the changed file below is docs work.+ save_state(repo, {"last_sync_commit": base, "last_docs_commit": base, "docs_enabled": True})+ new_head = _commit_change(+ repo, "c.py", "from b import beta\n\n\ndef gamma():\n return beta() * 2\n"+ )+ return repo, new_head+++class _StubPrompt:+ """Stand-in for init's interactive provider prompt.++ Records call count and mimics the real prompt's persistence side effect:+ it sets the key in the environment and writes it to ``.repowise/.env``,+ exactly as ``interactive_provider_config_select`` does for a real provider,+ then returns a selection for the (unselectable-in-table) ``mock`` provider.+ """++ def __init__(self) -> None:+ self.calls = 0++ def __call__(self, console, model, reasoning=None, *, repo_path=None):+ self.calls += 1+ import os++ from repowise.cli.ui.env_persistence import _save_key_to_dotenv++ os.environ["MOCK_API_KEY"] = "sk-mock-test-key"+ if repo_path is not None:+ _save_key_to_dotenv(repo_path, "MOCK_API_KEY", "sk-mock-test-key")+ return ProviderSelection("mock", "mock-model-1", "auto")+++def _force_interactive(monkeypatch) -> None:+ """Open the docs-prompt gate as if a real interactive terminal were present.++ The gate requires both a terminal stdout and a tty stdin; ``CliRunner``+ provides neither, so patch the named gate helper directly rather than+ faking two low-level tty signals.+ """+ monkeypatch.setattr(+ "repowise.cli.commands.update_cmd.command._docs_provider_prompt_allowed",+ lambda emitter: True,+ )+++# ---------------------------------------------------------------------------+# Tests+# ---------------------------------------------------------------------------+++def test_update_prompts_and_persists_when_docs_needs_a_provider(tmp_path, monkeypatch) -> None:+ repo, new_head = _prep_docs_repo_without_provider(tmp_path)++ stub = _StubPrompt()+ monkeypatch.setattr("repowise.cli.ui.interactive_provider_config_select", stub, raising=False)+ _force_interactive(monkeypatch)++ result = CliRunner().invoke(cli, ["update", str(repo), "--no-workspace"])+ assert result.exit_code == 0, result.output++ # The prompt fired exactly once to onboard the provider.+ assert stub.calls == 1++ # provider/model persisted to config, key persisted to .repowise/.env.+ cfg = _config(repo)+ assert cfg.get("provider") == "mock"+ assert cfg.get("model") == "mock-model-1"+ env_text = (repo / ".repowise" / ".env").read_text(encoding="utf-8")+ assert "MOCK_API_KEY=sk-mock-test-key" in env_text++ # Docs were actually generated: the docs pointer advanced to HEAD.+ state = json.loads((repo / ".repowise" / "state.json").read_text(encoding="utf-8"))+ assert state["last_docs_commit"] == new_head++ # A second docs run reuses the persisted provider without re-prompting.+ # run_update releases its single-flight lock via atexit, which fires at+ # process exit — but back-to-back CliRunner invokes share one process, so+ # release it here to mimic the real per-process boundary (otherwise run2+ # would bail as "another update already running").+ from repowise.cli.helpers import release_update_lock++ release_update_lock(repo)+ second_head = _commit_change(+ repo, "d.py", "from c import gamma\n\n\ndef delta():\n return gamma() + 1\n"+ )+ result2 = CliRunner().invoke(cli, ["update", str(repo), "--no-workspace"])+ assert result2.exit_code == 0, result2.output+ assert stub.calls == 1, "provider already persisted; must not prompt again"+ state2 = json.loads((repo / ".repowise" / "state.json").read_text(encoding="utf-8"))+ assert state2["last_docs_commit"] == second_head+++def test_update_non_interactive_stays_a_clean_failure(tmp_path, monkeypatch) -> None:+ repo, _ = _prep_docs_repo_without_provider(tmp_path)++ stub = _StubPrompt()+ monkeypatch.setattr("repowise.cli.ui.interactive_provider_config_select", stub, raising=False)+ # No _force_interactive: under CliRunner stdin is not a tty and the console+ # is not a terminal, so the prompt gate is closed (the hook / CI case).++ result = CliRunner().invoke(cli, ["update", str(repo), "--no-workspace"])++ # Clean, non-blocking failure — never prompted, never hung.+ assert result.exit_code != 0+ assert stub.calls == 0+ assert "No provider configured" in result.output