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(cli): add advisory update check to doctor (#346)
joptimusb0c8954031ec
diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.mdindex 451aa247f..6977930e8 100644--- a/docs/CLI_REFERENCE.md+++ b/docs/CLI_REFERENCE.md@@ -527,6 +527,17 @@ repowise doctor --workspace # every workspace reporepowise doctor --workspace --repair # also drop dead entries / sync drift```+**CLI update check.** `doctor` also prints a best-effort `CLI version` row that+compares your installed CLI against the latest release on PyPI and, when an+update is available, shows the suggested upgrade command (e.g. `uv tool upgrade+repowise`, `pipx upgrade repowise`, or `python -m pip install -U repowise`). It+shows both the `repowise` resolved on your `PATH` and the command that launched+the current process, since these can differ. This check is advisory: it never+updates anything automatically and does not fail `doctor` when PyPI is+unreachable. After upgrading, **restart Claude/Codex/Cursor or any MCP client**+so it picks up the new executable. (A standalone `repowise version --check` may+be added later.)+---### `repowise delete [REPO_ID]`diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.mdindex d8f2f001f..54d7c9734 100644--- a/docs/USER_GUIDE.md+++ b/docs/USER_GUIDE.md@@ -584,6 +584,14 @@ Checks:- `state.json` valid- Providers installed and importable- Stale page count+- **CLI version** — best-effort check of your installed CLI against the latest+ PyPI release++The CLI version row is advisory: when a newer release exists it prints the+right upgrade command for your install method (`uv tool upgrade repowise`,+`pipx upgrade repowise`, or `python -m pip install -U repowise`) plus a reminder+to **restart Claude/Codex/Cursor or any MCP client** afterwards. It never+upgrades automatically and never fails `doctor` when PyPI is unavailable.---diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd.py b/packages/cli/src/repowise/cli/commands/doctor_cmd.pyindex a4819e6da..940844013 100644--- a/packages/cli/src/repowise/cli/commands/doctor_cmd.py+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd.py@@ -23,6 +23,59 @@ def _check(name: str, ok: bool, detail: str = "") -> tuple[str, str, str]:return (name, status, detail)+def _print_cli_version_status() -> None:+ """Print a best-effort CLI update-check line.++ Advisory only: an outdated CLI is informational, not a broken repo, so this+ never affects doctor's pass/fail outcome and never fails on network errors.+ Runs once per invocation (the CLI version is global, not per-repo).+ """+ try:+ from repowise.cli.update_check import get_cli_update_check++ check = get_cli_update_check()+ except Exception:+ return # never let the update check break doctor++ # Show the full running command and resolved path verbatim — they can+ # differ (e.g. a stale shim on PATH vs the venv that launched this process),+ # and surfacing that mismatch is the point of this row.+ path_detail = check.resolved_executable or "not on PATH"+ running = check.running_executable or "?"++ if check.latest_version is None:+ status = "[green]OK[/green]"+ detail = (+ f"current {check.current_version}, could not check latest version, "+ f"path {path_detail}, running {running}"+ )+ elif check.update_available:+ status = "[yellow]WARN[/yellow]"+ detail = (+ f"current {check.current_version}, latest {check.latest_version}, "+ f"path {path_detail}, running {running}"+ )+ else:+ status = "[green]OK[/green]"+ detail = (+ f"current {check.current_version} (latest), "+ f"path {path_detail}, running {running}"+ )++ table = Table(show_header=False, box=None, pad_edge=False)+ table.add_column(style="cyan")+ table.add_column()+ table.add_column()+ table.add_row("CLI version", status, detail)+ console.print(table)++ if check.update_available:+ console.print(f" [yellow]Update available:[/yellow] {check.suggested_command}")+ console.print(+ " [dim]Restart Claude/Codex/Cursor or any MCP client after updating.[/dim]"+ )++def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:"""Run the standard health checks against one repo. Returns ``True`` ifall checks passed.@@ -443,6 +496,9 @@ def doctor_command()target.notice(console, command="doctor")+ # Advisory CLI update check — printed once, above the repo check table(s).+ _print_cli_version_status()+if not target.is_workspace:assert target.repo_path is not None_run_repo_checks(target.repo_path, repair)diff --git a/packages/cli/src/repowise/cli/update_check.py b/packages/cli/src/repowise/cli/update_check.pynew file mode 100644index 000000000..af149eb68--- /dev/null+++ b/packages/cli/src/repowise/cli/update_check.py@@ -0,0 +1,173 @@+"""Best-effort check for whether the installed ``repowise`` CLI is stale.++This is intentionally conservative:++* Current version comes from :data:`repowise.cli.__version__`.+* Latest version is fetched from the PyPI JSON endpoint via the already-bundled+ ``httpx`` with a short timeout.+* An install-method-appropriate upgrade *command* is suggested, but never run.++Network failures are swallowed — callers (e.g. ``repowise doctor``) must keep+working when PyPI is unreachable. This module never raises and never invokes a+package manager.+"""++from __future__ import annotations++import shutil+import sys+from dataclasses import dataclass+from pathlib import Path++PYPI_URL = "https://pypi.org/pypi/repowise/json"+++@dataclass(frozen=True)+class UpdateCheck:+ """Result of a CLI update check.++ ``update_available`` is ``None`` when the latest version could not be+ determined (network error, parse failure) so callers can distinguish+ "up to date" from "unknown".+ """++ current_version: str+ latest_version: str | None+ resolved_executable: str | None+ running_executable: str+ python: str+ update_available: bool | None+ suggested_command: str+ install_hint: str+ error: str | None = None+++def _parse_release(version: str) -> tuple[int, ...] | None:+ """Parse the leading numeric release parts of a version string.++ Returns a tuple of ints for the dotted numeric prefix (so ``0.15.2`` ->+ ``(0, 15, 2)``). Pre-release/local suffixes such as ``-rc1`` or ``+local``+ are ignored. Returns ``None`` when no numeric component can be parsed.+ """+ parts: list[int] = []+ for chunk in version.strip().split("."):+ digits = ""+ for ch in chunk:+ if ch.isdigit():+ digits += ch+ else:+ break+ if not digits:+ break+ parts.append(int(digits))+ return tuple(parts) or None+++def is_newer_version(latest: str, current: str) -> bool:+ """Return ``True`` if ``latest`` is a strictly newer release than ``current``.++ Uses a simple numeric-release comparison. If either version cannot be+ parsed, returns ``False`` (no update decision) rather than raising.+ """+ lat = _parse_release(latest)+ cur = _parse_release(current)+ if lat is None or cur is None:+ return False+ # Pad to equal length so 0.15 compares correctly against 0.15.2.+ length = max(len(lat), len(cur))+ lat = lat + (0,) * (length - len(lat))+ cur = cur + (0,) * (length - len(cur))+ return lat > cur+++def suggest_update_command(executable: str | None, python: str) -> tuple[str, str]:+ """Suggest an upgrade command and human-readable install hint.++ Heuristic, based on the resolved executable path. Returns+ ``(command, hint)``. When the install method is unknown, falls back to a+ safe ``<python> -m pip install -U repowise``.+ """+ path = (executable or "").replace("\\", "/").lower()++ if "pipx" in path:+ return ("pipx upgrade repowise", "pipx")+ # uv tool installs live under a uv data dir, e.g.+ # ~/.local/share/uv/tools/... or a uv-managed bin shim.+ if "/uv/" in path or "uv/tools" in path or "/uv/tools/" in path:+ return ("uv tool upgrade repowise", "uv tool")+ return (f"{python} -m pip install -U repowise", "pip")+++def _editable_checkout() -> Path | None:+ """Return the repo root when ``repowise`` is running from a source checkout.++ Detected by the package not living under ``site-packages``/``dist-packages``+ while a parent directory carries both ``pyproject.toml`` and ``.git``.+ """+ try:+ from repowise.cli import __file__ as cli_file+ except Exception:+ return None+ pkg = Path(cli_file).resolve()+ if "site-packages" in pkg.parts or "dist-packages" in pkg.parts:+ return None+ for parent in pkg.parents:+ if (parent / "pyproject.toml").exists() and (parent / ".git").exists():+ return parent+ return None+++def get_cli_update_check(timeout: float = 2.0) -> UpdateCheck:+ """Check whether the installed ``repowise`` CLI is out of date.++ Always returns an :class:`UpdateCheck`; never raises. On network/parse+ failure, ``latest_version`` is ``None``, ``update_available`` is ``None``,+ and ``error`` carries a short description.+ """+ from repowise.cli import __version__++ current = __version__+ resolved = shutil.which("repowise")+ running = sys.argv[0] if sys.argv else ""+ python = sys.executable or "python"++ checkout = _editable_checkout()+ if checkout is not None:+ suggested = f"cd {checkout} && git pull && {python} -m pip install -e ."+ hint = "editable"+ else:+ suggested, hint = suggest_update_command(resolved or running, python)++ latest: str | None = None+ error: str | None = None+ try:+ import httpx++ resp = httpx.get(PYPI_URL, timeout=timeout)+ resp.raise_for_status()+ fetched = resp.json()["info"]["version"]+ # Only accept a version we can actually compare; otherwise leave+ # latest=None so callers report "unknown" rather than a false "latest".+ if _parse_release(fetched) is None:+ error = f"unparsable latest version: {fetched!r}"+ else:+ latest = fetched+ except Exception as exc: # network, JSON, missing key — all advisory+ error = str(exc) or exc.__class__.__name__++ if latest is None:+ update_available: bool | None = None+ else:+ update_available = is_newer_version(latest, current)++ return UpdateCheck(+ current_version=current,+ latest_version=latest,+ resolved_executable=resolved,+ running_executable=running,+ python=python,+ update_available=update_available,+ suggested_command=suggested,+ install_hint=hint,+ error=error,+ )diff --git a/tests/unit/cli/test_doctor_cli_version.py b/tests/unit/cli/test_doctor_cli_version.pynew file mode 100644index 000000000..e8a4a6f09--- /dev/null+++ b/tests/unit/cli/test_doctor_cli_version.py@@ -0,0 +1,84 @@+"""Tests for the advisory CLI version row in ``repowise doctor``."""++from __future__ import annotations++import io++import pytest+from rich.console import Console++from repowise.cli.commands import doctor_cmd+from repowise.cli.update_check import UpdateCheck+++def _capture(monkeypatch: pytest.MonkeyPatch, check: UpdateCheck) -> str:+ buf = io.StringIO()+ monkeypatch.setattr(doctor_cmd, "console", Console(file=buf, width=200))+ monkeypatch.setattr("repowise.cli.update_check.get_cli_update_check", lambda *a, **k: check)+ doctor_cmd._print_cli_version_status()+ return buf.getvalue()+++def _make(**overrides) -> UpdateCheck:+ base = dict(+ current_version="0.13.0",+ latest_version="0.15.2",+ resolved_executable="/usr/local/bin/repowise",+ running_executable="/tmp/venv/bin/repowise",+ python="/usr/bin/python",+ update_available=True,+ suggested_command="/usr/bin/python -m pip install -U repowise",+ install_hint="pip",+ error=None,+ )+ base.update(overrides)+ return UpdateCheck(**base)+++def test_update_available_shows_warn_and_command(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ out = _capture(monkeypatch, _make())+ assert "CLI version" in out+ assert "WARN" in out+ assert "current 0.13.0" in out+ assert "latest 0.15.2" in out+ assert "/usr/local/bin/repowise" in out # resolved path+ assert "/tmp/venv/bin/repowise" in out # full running command (may differ)+ assert "pip install -U repowise" in out+ assert "Restart" in out+++def test_up_to_date_shows_ok_no_command(monkeypatch: pytest.MonkeyPatch) -> None:+ out = _capture(+ monkeypatch,+ _make(current_version="0.15.2", latest_version="0.15.2", update_available=False),+ )+ assert "OK" in out+ assert "WARN" not in out+ assert "(latest)" in out+ assert "Restart" not in out+++def test_latest_unknown_stays_neutral(monkeypatch: pytest.MonkeyPatch) -> None:+ out = _capture(+ monkeypatch,+ _make(latest_version=None, update_available=None, error="no network"),+ )+ assert "OK" in out+ assert "WARN" not in out+ assert "could not check latest version" in out+ assert "Restart" not in out+++def test_never_raises_when_check_errors(monkeypatch: pytest.MonkeyPatch) -> None:+ buf = io.StringIO()+ monkeypatch.setattr(doctor_cmd, "console", Console(file=buf, width=200))++ def _boom(*a, **k):+ raise RuntimeError("unexpected")++ monkeypatch.setattr("repowise.cli.update_check.get_cli_update_check", _boom)+ # Should swallow the error and print nothing rather than crash doctor.+ doctor_cmd._print_cli_version_status()+ assert buf.getvalue() == ""diff --git a/tests/unit/cli/test_update_check.py b/tests/unit/cli/test_update_check.pynew file mode 100644index 000000000..578b77de0--- /dev/null+++ b/tests/unit/cli/test_update_check.py@@ -0,0 +1,170 @@+"""Tests for the CLI update-check helper (``repowise.cli.update_check``)."""++from __future__ import annotations++import httpx+import pytest++from repowise.cli import update_check as uc++# --- version comparison ----------------------------------------------------+++ ("latest", "current", "expected"),+ [+ ("0.15.2", "0.13.0", True),+ ("0.15.2", "0.15.2", False),+ ("0.15.10", "0.15.2", True),+ ("0.13.0", "0.15.2", False),+ ("0.15", "0.15.2", False), # 0.15.0 < 0.15.2+ ("0.16", "0.15.2", True),+ ],+)+def test_is_newer_version(latest: str, current: str, expected: bool) -> None:+ assert uc.is_newer_version(latest, current) is expected++[email protected]("latest", ["", "not-a-version", "abc"])+def test_is_newer_version_unparseable_returns_false(latest: str) -> None:+ # Invalid/missing latest yields no update decision instead of crashing.+ assert uc.is_newer_version(latest, "0.15.2") is False+++# --- install-method suggestion ---------------------------------------------+++def test_suggest_uv_tool_path() -> None:+ cmd, hint = uc.suggest_update_command(+ "/home/user/.local/share/uv/tools/repowise/bin/repowise", "/usr/bin/python"+ )+ assert cmd == "uv tool upgrade repowise"+ assert hint == "uv tool"+++def test_suggest_pipx_path() -> None:+ cmd, hint = uc.suggest_update_command(+ "/home/user/.local/pipx/venvs/repowise/bin/repowise", "/usr/bin/python"+ )+ assert cmd == "pipx upgrade repowise"+ assert hint == "pipx"+++def test_suggest_pip_fallback() -> None:+ cmd, hint = uc.suggest_update_command("/usr/local/bin/repowise", "/opt/py/bin/python")+ assert cmd == "/opt/py/bin/python -m pip install -U repowise"+ assert hint == "pip"+++def test_suggest_pip_fallback_when_executable_unknown() -> None:+ cmd, hint = uc.suggest_update_command(None, "/opt/py/bin/python")+ assert cmd == "/opt/py/bin/python -m pip install -U repowise"+ assert hint == "pip"+++# --- get_cli_update_check --------------------------------------------------+++class _FakeResponse:+ def __init__(self, payload: dict) -> None:+ self._payload = payload++ def raise_for_status(self) -> None:+ return None++ def json(self) -> dict:+ return self._payload+++def _patch_no_editable(monkeypatch: pytest.MonkeyPatch) -> None:+ # Force the non-editable path so the suggested command is deterministic.+ monkeypatch.setattr(uc, "_editable_checkout", lambda: None)+++def test_detects_update_available(monkeypatch: pytest.MonkeyPatch) -> None:+ _patch_no_editable(monkeypatch)+ monkeypatch.setattr("repowise.cli.__version__", "0.13.0", raising=False)+ monkeypatch.setattr(+ httpx, "get", lambda *a, **k: _FakeResponse({"info": {"version": "0.15.2"}})+ )++ result = uc.get_cli_update_check(timeout=0.1)++ assert result.current_version == "0.13.0"+ assert result.latest_version == "0.15.2"+ assert result.update_available is True+ assert result.error is None+++def test_no_update_when_current_is_latest(monkeypatch: pytest.MonkeyPatch) -> None:+ _patch_no_editable(monkeypatch)+ monkeypatch.setattr("repowise.cli.__version__", "0.15.2", raising=False)+ monkeypatch.setattr(+ httpx, "get", lambda *a, **k: _FakeResponse({"info": {"version": "0.15.2"}})+ )++ result = uc.get_cli_update_check(timeout=0.1)++ assert result.update_available is False+++def test_network_error_does_not_raise(monkeypatch: pytest.MonkeyPatch) -> None:+ _patch_no_editable(monkeypatch)++ def _boom(*a, **k):+ raise httpx.ConnectError("no network")++ monkeypatch.setattr(httpx, "get", _boom)++ result = uc.get_cli_update_check(timeout=0.1)++ assert result.latest_version is None+ assert result.update_available is None+ assert result.error is not None+++def test_unparsable_latest_is_treated_as_unknown(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _patch_no_editable(monkeypatch)+ monkeypatch.setattr("repowise.cli.__version__", "0.15.2", raising=False)+ monkeypatch.setattr(+ httpx, "get", lambda *a, **k: _FakeResponse({"info": {"version": "garbage"}})+ )++ result = uc.get_cli_update_check(timeout=0.1)++ # An uncomparable PyPI version must not masquerade as "up to date".+ assert result.latest_version is None+ assert result.update_available is None+ assert result.error is not None+++def test_records_resolved_and_running_executables(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _patch_no_editable(monkeypatch)+ monkeypatch.setattr(uc.shutil, "which", lambda name: "/usr/local/bin/repowise")+ monkeypatch.setattr(uc.sys, "argv", ["/tmp/venv/bin/repowise", "doctor"])+ monkeypatch.setattr(+ httpx, "get", lambda *a, **k: _FakeResponse({"info": {"version": "0.15.2"}})+ )++ result = uc.get_cli_update_check(timeout=0.1)++ assert result.resolved_executable == "/usr/local/bin/repowise"+ assert result.running_executable == "/tmp/venv/bin/repowise"+++def test_editable_checkout_suggests_pip_editable(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:+ monkeypatch.setattr(uc, "_editable_checkout", lambda: tmp_path)+ monkeypatch.setattr(uc.sys, "executable", "/opt/py/bin/python")+ monkeypatch.setattr(+ httpx, "get", lambda *a, **k: _FakeResponse({"info": {"version": "0.15.2"}})+ )++ result = uc.get_cli_update_check(timeout=0.1)++ assert result.install_hint == "editable"+ assert "git pull" in result.suggested_command+ assert "pip install -e ." in result.suggested_command