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.

test(cli): pin serve, doctor and update behaviour (#3974)

Raghav Chamadiyab0d7ba2373d2
diff --git a/tests/unit/cli/_real_call_guard.py b/tests/unit/cli/_real_call_guard.py
new file mode 100644
index 000000000..34ea30279
--- /dev/null
+++ b/tests/unit/cli/_real_call_guard.py
@@ -0,0 +1,70 @@
+"""Make a real subprocess, network or socket call fail loudly in a test.
+
+A patch on a name that stops intercepting (a module turned into a package,
+a re-export moved) would otherwise run the real thing: bind a port, spawn
+node, or hit GitHub. A test that patches one of these entries replaces the
+guard, since its monkeypatch runs after this one.
+"""
+
+from __future__ import annotations
+
+import os
+import socket
+import subprocess
+import urllib.request
+
+import httpx
+import pytest
+
+
+class UnexpectedRealCall(AssertionError):
+ pass
+
+
+def _refuse(what: str):
+ def _raise(*args, **kwargs):
+ raise UnexpectedRealCall(f"unexpected real call: {what} args={args!r}")
+
+ return _raise
+
+
+def _is_git(cmd) -> bool:
+ argv0 = cmd if isinstance(cmd, str) else (cmd[0] if cmd else "")
+ name = os.path.basename(str(argv0).split(" ", 1)[0]).lower()
+ return name in ("git", "git.exe")
+
+
+def guard_real_calls(monkeypatch: pytest.MonkeyPatch, *, allow_git: bool = False) -> None:
+ """Refuse subprocesses, HTTP and non-ephemeral binds.
+
+ ``allow_git`` lets git through for tests that build a real repository.
+ Port-0 binds stay allowed: they are what ``socket.socketpair`` (the
+ Windows asyncio loop) and the OS-assigned port fallback use, and they
+ never claim a real port.
+ """
+ real_popen_init = subprocess.Popen.__init__
+
+ def _popen_init(self, args, *a, **kw):
+ if allow_git and _is_git(args):
+ return real_popen_init(self, args, *a, **kw)
+ raise UnexpectedRealCall(f"unexpected real call: subprocess.Popen {args!r}")
+
+ # Popen.__init__ also covers subprocess.run / check_output, which build one.
+ monkeypatch.setattr(subprocess.Popen, "__init__", _popen_init)
+ if not allow_git:
+ monkeypatch.setattr(subprocess, "run", _refuse("subprocess.run"))
+ monkeypatch.setattr(subprocess, "Popen", _refuse("subprocess.Popen"))
+
+ monkeypatch.setattr(httpx, "stream", _refuse("httpx.stream"))
+ monkeypatch.setattr(httpx.Client, "send", _refuse("httpx.Client.send"))
+ monkeypatch.setattr(httpx.AsyncClient, "send", _refuse("httpx.AsyncClient.send"))
+ monkeypatch.setattr(urllib.request, "urlopen", _refuse("urllib.request.urlopen"))
+
+ real_bind = socket.socket.bind
+
+ def _bind(self, address):
+ if isinstance(address, tuple) and len(address) >= 2 and address[1] == 0:
+ return real_bind(self, address)
+ raise UnexpectedRealCall(f"unexpected real call: socket.bind {address!r}")
+
+ monkeypatch.setattr(socket.socket, "bind", _bind)
diff --git a/tests/unit/cli/test_doctor_check_order.py b/tests/unit/cli/test_doctor_check_order.py
new file mode 100644
index 000000000..e1db1dd21
--- /dev/null
+++ b/tests/unit/cli/test_doctor_check_order.py
@@ -0,0 +1,476 @@
+"""Safety net for ``_run_repo_checks`` before it is split.
+
+Pins the row list (names, order, statuses) for a healthy store and a few
+broken ones, the table/advisory output order, and every ``--repair`` branch:
+FTS and vector repair, the "nothing to repair" paths, agent refresh and the
+Claude Code re-registration. Rows that depend on the machine (providers,
+distill, editor registration, agents, hosted account) are stubbed with
+marker rows so only their position is pinned.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+
+import pytest
+
+from repowise.cli.commands.doctor_cmd import repo_checks
+from repowise.cli.commands.doctor_cmd._types import _check
+
+from ._real_call_guard import guard_real_calls
+
+
[email protected](autouse=True)
+def _no_real_calls(monkeypatch) -> None:
+ # git stays real: the fixtures build actual repositories.
+ guard_real_calls(monkeypatch, allow_git=True)
+
+KEPT = "file_page:kept.py"
+ALSO = "file_page:also.py"
+GHOST = "file_page:ghost.py"
+
+
+async def _build(
+ tmp_path: Path,
+ *,
+ pages: tuple[tuple[str, str, str], ...] = ((KEPT, "kept.py", "File: kept.py"),),
+ fts: tuple[str, ...] = (KEPT,),
+ vectors: tuple[str, ...] = (KEPT,),
+) -> Path:
+ """A git repo with SQL pages and chosen FTS / vector contents."""
+ import git as gitpython
+
+ from repowise.core.persistence import (
+ FullTextSearch,
+ create_engine,
+ create_session_factory,
+ get_session,
+ )
+ from repowise.core.persistence.crud import upsert_page, upsert_repository
+ from repowise.core.persistence.database import init_db
+ from repowise.core.persistence.vector_store import LanceDBVectorStore
+ from repowise.core.providers.embedding.base import MockEmbedder
+
+ repo_path = (tmp_path / "repo").resolve()
+ repo_path.mkdir()
+ gitpython.Repo.init(repo_path)
+ rw = repo_path / ".repowise"
+ rw.mkdir()
+ (rw / "state.json").write_text(json.dumps({"last_sync_commit": "abcdef0123456789"}))
+
+ engine = create_engine(f"sqlite+aiosqlite:///{rw / 'wiki.db'}")
+ await init_db(engine)
+ sf = create_session_factory(engine)
+ async with get_session(sf) as session:
+ repo = await upsert_repository(
+ session, name="repo", local_path=str(repo_path), url="https://example.test/repo"
+ )
+ for page_id, path, title in pages:
+ await upsert_page(
+ session,
+ page_id=page_id,
+ repository_id=repo.id,
+ page_type="file_page",
+ title=title,
+ content="Body.",
+ summary="",
+ target_path=path,
+ source_hash="",
+ model_name="mock",
+ provider_name="mock",
+ )
+ await session.commit()
+
+ index = FullTextSearch(engine)
+ await index.ensure_index()
+ for page_id in fts:
+ await index.index(page_id, "File", "Body.", summary="", target_path="x.py")
+ await engine.dispose()
+
+ store = LanceDBVectorStore(str(rw / "lancedb"), embedder=MockEmbedder())
+ for page_id in vectors:
+ await store.embed_and_upsert(page_id, "Body.", {"title": "File"})
+ await store.close()
+ return repo_path
+
+
+def env(monkeypatch) -> dict:
+ """Stub machine-dependent rows and record console output in order."""
+ st: dict = {"printed": [], "wedged": False, "refresh": False}
+ monkeypatch.setattr(repo_checks, "_autosync_hook_check", lambda _p: _check("<hook>", True, ""))
+ monkeypatch.setattr(repo_checks, "_attribution_notes_check", lambda _p: None)
+ monkeypatch.setattr(repo_checks, "_events_config_check", lambda _p: None)
+ monkeypatch.setattr(repo_checks, "_provider_checks", lambda _p: [_check("<provider>", True, "")])
+ monkeypatch.setattr(repo_checks, "_distill_checks", lambda _p: [_check("<distill>", True, "")])
+ monkeypatch.setattr(
+ repo_checks,
+ "_claude_registration_check",
+ lambda _p: (_check("<registration>", not st["wedged"], ""), st["wedged"]),
+ )
+ monkeypatch.setattr(repo_checks, "_mcp_responds_check", lambda: _check("<mcp>", True, ""))
+ monkeypatch.setattr(
+ repo_checks,
+ "_agent_target_checks",
+ lambda _p: ([_check("<agent>", not st["refresh"], "")], st["refresh"]),
+ )
+ monkeypatch.setattr(repo_checks, "_advise_claude_md_stamp", lambda *_a: st["printed"].append("<stamp>"))
+ monkeypatch.setattr("repowise.cli.platform.credentials.load", lambda: None)
+ monkeypatch.setattr(
+ repo_checks.console, "print", lambda *a, **_k: st["printed"].append(" ".join(map(str, a)))
+ )
+ return st
+
+
+def _rows(repo_path: Path, fmt: str = "json") -> list[tuple[str, bool, str]]:
+ _ok, checks = repo_checks._run_repo_checks(repo_path, repair=False, fmt=fmt)
+ return [(c.name, c.ok, c.detail) for c in checks]
+
+
+HEALTHY_ORDER = [
+ "Git repository",
+ ".repowise/ directory",
+ "<hook>",
+ "Database",
+ "state.json",
+ "Store format",
+ "<provider>",
+ "Hosted account",
+ "Stale pages",
+ "SQL ↔ Vector Store",
+ "SQL ↔ FTS Index",
+ "Coordinator drift",
+ "<distill>",
+ "<registration>",
+ "<mcp>",
+ "<agent>",
+]
+
+
+def _by_name(rows: list[tuple[str, bool, str]]) -> dict[str, tuple[bool, str]]:
+ return {n: (ok, d) for n, ok, d in rows}
+
+
+def test_healthy_store_rows_and_order(env, tmp_path) -> None:
+ repo = asyncio.run(_build(tmp_path))
+ rows = _rows(repo)
+ assert [r[0] for r in rows] == HEALTHY_ORDER
+ assert all(ok for _n, ok, _d in rows)
+ got = _by_name(rows)
+ assert got["Git repository"][1] == str(repo)
+ assert got["Database"] == (True, "1 pages")
+ assert got["state.json"] == (True, "last_sync: abcdef01")
+ assert got["Stale pages"] == (True, "0 stale")
+ assert got["SQL ↔ Vector Store"] == (True, "in sync")
+ assert got["SQL ↔ FTS Index"] == (True, "in sync")
+ assert got["Coordinator drift"] == (True, "SQL=1, Vector=1, Drift=0.0%")
+ assert got["Hosted account"][1].startswith("Not signed in")
+ # JSON format prints nothing; the table and advisories are table-only.
+ assert env["printed"] == []
+
+
+def test_optional_rows_slot_in_after_the_hook(env, monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr(
+ repo_checks, "_attribution_notes_check", lambda _p: _check("<notes>", True, "")
+ )
+ monkeypatch.setattr(
+ repo_checks, "_events_config_check", lambda _p: _check("<events>", False, "")
+ )
+ repo = asyncio.run(_build(tmp_path))
+ names = [r[0] for r in _rows(repo)]
+ assert names[2:5] == ["<hook>", "<notes>", "<events>"]
+
+
+def test_unindexed_repo_rows(env, monkeypatch, tmp_path) -> None:
+ import git as gitpython
+
+ monkeypatch.setattr(repo_checks, "db_configured", lambda: False)
+ repo = tmp_path / "bare"
+ repo.mkdir()
+ gitpython.Repo.init(repo)
+ rows = _rows(repo)
+ assert [r[0] for r in rows] == [
+ "Git repository",
+ ".repowise/ directory",
+ "<hook>",
+ "Database",
+ "state.json",
+ "<provider>",
+ "Hosted account",
+ "<distill>",
+ "<registration>",
+ "<mcp>",
+ "<agent>",
+ ]
+ got = _by_name(rows)
+ assert got[".repowise/ directory"][0] is False
+ assert got["Database"] == (False, "wiki.db not found")
+ assert got["state.json"] == (False, "Not found or empty")
+
+
+def test_missing_state_drops_store_format_row(env, tmp_path) -> None:
+ repo = asyncio.run(_build(tmp_path))
+ (repo / ".repowise" / "state.json").unlink()
+ rows = _rows(repo)
+ assert "Store format" not in [r[0] for r in rows]
+ assert _by_name(rows)["state.json"] == (False, "Not found or empty")
+
+
+def test_drift_rows_and_coordinator(env, tmp_path) -> None:
+ repo = asyncio.run(
+ _build(
+ tmp_path,
+ pages=((KEPT, "kept.py", "File: kept.py"), (ALSO, "also.py", "File: also.py")),
+ fts=(KEPT, GHOST),
+ vectors=(KEPT, GHOST),
+ )
+ )
+ rows = _rows(repo)
+ assert [r[0] for r in rows] == HEALTHY_ORDER
+ got = _by_name(rows)
+ assert got["Database"] == (True, "2 pages")
+ assert got["SQL ↔ Vector Store"] == (False, "1 missing, 1 orphaned")
+ assert got["SQL ↔ FTS Index"] == (False, "1 missing, 1 orphaned")
+ # Same count on both sides: the coordinator reads 0% drift.
+ assert got["Coordinator drift"] == (True, "SQL=2, Vector=2, Drift=0.0%")
+
+
+def test_stale_pages_row(env, monkeypatch, tmp_path) -> None:
+ async def _stale(_s, _r):
+ return {"file_page": 2}
+
+ monkeypatch.setattr(repo_checks, "_stale_page_counts", _stale)
+ repo = asyncio.run(_build(tmp_path))
+ ok, detail = _by_name(_rows(repo))["Stale pages"]
+ assert ok is False
+ assert detail.startswith("2 stale")
+
+
+def test_expired_and_cached_hosted_identity(env, monkeypatch, tmp_path) -> None:
+ repo = asyncio.run(_build(tmp_path))
+ monkeypatch.setattr("repowise.cli.platform.credentials.load", lambda: {"stale": True})
+ assert _by_name(_rows(repo))["Hosted account"] == (
+ False,
+ "Session expired or revoked; run repowise login",
+ )
+ monkeypatch.setattr(
+ "repowise.cli.platform.credentials.load",
+ lambda: {"account": {"email": "[email protected]", "tier": "pro"}},
+ )
+ monkeypatch.setattr("repowise.cli.platform.auth.fetch_account", lambda: None)
+ assert _by_name(_rows(repo))["Hosted account"] == (
+ True,
+ "[email protected] (pro) (offline, using cached identity)",
+ )
+
+
+# ---------------------------------------------------------------------------
+# Table output and --repair
+# ---------------------------------------------------------------------------
+
+
+def _repair(repo: Path) -> bool:
+ ok, _checks = repo_checks._run_repo_checks(repo, repair=True)
+ return ok
+
+
+def _texts(env: dict) -> list[str]:
+ """Printed strings, with the rich Table collapsed to a marker."""
+ return ["<table>" if p.startswith("<rich.table") else p for p in env["printed"]]
+
+
+def mock_embedder(monkeypatch) -> None:
+ from repowise.core.providers.embedding.base import MockEmbedder
+
+ monkeypatch.setattr("repowise.cli.providers.resolve_embedder_for_repo", lambda _p: "mock")
+ monkeypatch.setattr(
+ "repowise.cli.providers.build_embedder", lambda _n, _p=None: MockEmbedder()
+ )
+
+
+def test_table_healthy_prints_table_stamp_then_pass(env, tmp_path) -> None:
+ repo = asyncio.run(_build(tmp_path))
+ ok, _ = repo_checks._run_repo_checks(repo, repair=False)
+ assert ok is True
+ assert _texts(env) == ["<table>", "<stamp>", "[bold green]All checks passed![/bold green]"]
+
+
+def test_repair_with_nothing_to_do(env, tmp_path) -> None:
+ repo = asyncio.run(_build(tmp_path))
+ _repair(repo)
+ assert _texts(env)[-1] == "[green]Nothing to repair.[/green]"
+
+
+def test_repair_without_drift_names_stale_pages(env, monkeypatch, tmp_path) -> None:
+ async def _stale(_s, _r):
+ return {"file_page": 1}
+
+ monkeypatch.setattr(repo_checks, "_stale_page_counts", _stale)
+ repo = asyncio.run(_build(tmp_path))
+ _repair(repo)
+ assert _texts(env)[-1].startswith("[yellow]No store drift to repair. 1 stale")
+
+
+def test_repair_fixes_fts_and_vector_drift(env, mock_embedder, tmp_path) -> None:
+ repo = asyncio.run(
+ _build(
+ tmp_path,
+ pages=((KEPT, "kept.py", "File: kept.py"), (ALSO, "also.py", "File: also.py")),
+ fts=(KEPT, GHOST),
+ vectors=(KEPT, GHOST),
+ )
+ )
+ assert _repair(repo) is False
+ assert _texts(env) == [
+ "<table>",
+ "<stamp>",
+ "[bold yellow]Some checks failed.[/bold yellow]",
+ "\n[bold]Repairing store mismatches...[/bold]",
+ # FTS: 1 orphan + 1 missing; vector: 1 missing + 1 orphan.
+ "[bold green]Repaired 4 entries.[/bold green]",
+ ]
+ got = _by_name(_rows(repo))
+ assert got["SQL ↔ Vector Store"] == (True, "in sync")
+ assert got["SQL ↔ FTS Index"] == (True, "in sync")
+
+
+def test_repair_reports_stale_after_store_repair(env, monkeypatch, tmp_path) -> None:
+ async def _stale(_s, _r):
+ return {"file_page": 1}
+
+ monkeypatch.setattr(repo_checks, "_stale_page_counts", _stale)
+ repo = asyncio.run(_build(tmp_path, fts=(KEPT, GHOST)))
+ _repair(repo)
+ out = _texts(env)
+ assert out[-2] == "[bold green]Repaired 1 entries.[/bold green]"
+ assert out[-1].startswith("[yellow]1 stale")
+
+
+def test_fts_upgrade_failure_does_not_stop_repair(env, monkeypatch, tmp_path) -> None:
+ from repowise.core.persistence import FullTextSearch
+
+ repo = asyncio.run(_build(tmp_path, fts=(KEPT, GHOST)))
+
+ async def _refuse(self):
+ raise RuntimeError("drifted columns")
+
+ monkeypatch.setattr(FullTextSearch, "ensure_index", _refuse)
+ _repair(repo)
+ out = _texts(env)
+ assert " [yellow]Full-text index upgrade skipped: drifted columns[/yellow]" in out
+ assert out[-1] == "[bold green]Repaired 1 entries.[/bold green]"
+
+
+def test_vector_repair_skips_untitled_page(env, mock_embedder, tmp_path) -> None:
+ repo = asyncio.run(
+ _build(
+ tmp_path,
+ pages=((KEPT, "kept.py", "File: kept.py"), (ALSO, "also.py", "")),
+ fts=(KEPT, ALSO),
+ )
+ )
+ _repair(repo)
+ out = _texts(env)
+ assert f" [yellow]Skipped {ALSO}: no title to index it by.[/yellow]" in out
+ assert out[-1] == "[bold green]Repaired 0 entries.[/bold green]"
+
+
+def test_vector_repair_on_paid_embedder_announces_cost(env, monkeypatch, tmp_path) -> None:
+ from repowise.core.persistence.vector_store import LanceDBVectorStore
+ from repowise.core.providers.embedding.base import MockEmbedder
+
+ repo = asyncio.run(
+ _build(
+ tmp_path,
+ pages=((KEPT, "kept.py", "File: kept.py"), (ALSO, "also.py", "File: also.py")),
+ fts=(KEPT, ALSO),
+ )
+ )
+ embedded: list[str] = []
+
+ async def _record(self, page_id, *_a, **_k):
+ embedded.append(page_id)
+
+ monkeypatch.setattr(LanceDBVectorStore, "embed_and_upsert", _record)
+ monkeypatch.setattr("repowise.cli.providers.resolve_embedder_for_repo", lambda _p: "openai")
+ monkeypatch.setattr(
+ "repowise.cli.providers.build_embedder", lambda _n, _p=None: MockEmbedder()
+ )
+ _repair(repo)
+ assert embedded == [ALSO]
+ assert " [dim]Embedding 1 missing page(s) with openai.[/dim]" in _texts(env)
+
+
+def test_vector_repair_without_usable_embedder(env, mock_embedder, monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr("repowise.cli.providers.build_vector_store", lambda _p, _e: None)
+ repo = asyncio.run(_build(tmp_path, vectors=(KEPT, GHOST)))
+ _repair(repo)
+ out = _texts(env)
+ assert any(o.startswith("[yellow]Vector repair skipped: no embedder available") for o in out)
+ assert out[-1] == "[bold green]Repaired 0 entries.[/bold green]"
+
+
+def test_repair_refreshes_agents_then_reregisters(env, monkeypatch, tmp_path) -> None:
+ env["refresh"] = True
+ env["wedged"] = True
+ payload = {
+ "changed": False,
+ "agents": [
+ {"id": "claude", "writes": {"repo": {"files": [{"action": "kept", "path": "a.json"}]}}}
+ ],
+ }
+ monkeypatch.setattr(
+ "repowise.cli.commands.agents_cmd.refresh_wired_agents", lambda _p: payload
+ )
+ monkeypatch.setattr(
+ "repowise.cli.editor_integrations.claude_config.register_with_claude_code",
+ lambda _p: "~/.claude.json",
+ )
+ repo = asyncio.run(_build(tmp_path))
+ assert _repair(repo) is False
+ out = _texts(env)
+ start = out.index("\n[bold]Refreshing agent integrations...[/bold]")
+ assert out[start + 1] == " claude [repo]: kept a.json"
+ assert out[start + 2].startswith("[yellow]Nothing moved.")
+ assert out[start + 3:] == [
+ "[bold green]Re-registered the Claude Code MCP entry (~/.claude.json).[/bold green]"
+ ]
+ # The "Nothing to repair" lines are skipped when agents or registration need work.
+ assert not any("Nothing to repair" in o for o in out)
+
+
+def test_failed_reregistration_points_at_init(env, monkeypatch, tmp_path) -> None:
+ env["wedged"] = True
+ monkeypatch.setattr(
+ "repowise.cli.editor_integrations.claude_config.register_with_claude_code",
+ lambda _p: None,
+ )
+ repo = asyncio.run(_build(tmp_path))
+ _repair(repo)
+ assert _texts(env)[-1].startswith("[yellow]Could not re-register the Claude Code MCP entry")
+
+
+def test_coordinator_drift_is_colored_in_table(env, monkeypatch, tmp_path) -> None:
+ from rich.table import Table
+
+ rows: list[tuple] = []
+ real_add_row = Table.add_row
+
+ def _add_row(self, *cells, **kw):
+ rows.append(cells)
+ return real_add_row(self, *cells, **kw)
+
+ monkeypatch.setattr(Table, "add_row", _add_row)
+ repo = asyncio.run(
+ _build(
+ tmp_path,
+ pages=((KEPT, "kept.py", "File: kept.py"), (ALSO, "also.py", "File: also.py")),
+ fts=(KEPT, ALSO),
+ )
+ )
+ repo_checks._run_repo_checks(repo, repair=False)
+ coord = next(r for r in rows if r[0] == "Coordinator drift")
+ assert coord[2] == "SQL=2, Vector=1, Drift=[red]50.0%[/red]"
diff --git a/tests/unit/cli/test_serve_paths.py b/tests/unit/cli/test_serve_paths.py
new file mode 100644
index 000000000..9ded4a7cf
--- /dev/null
+++ b/tests/unit/cli/test_serve_paths.py
@@ -0,0 +1,795 @@
+"""Safety net for `repowise serve` before the module is split.
+
+Pins the embedder prompt, port fallback, web asset resolution (download,
+local build, staleness), frontend launch and the command's branch order.
+No real server, socket listener, subprocess or network call is made.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import os
+import subprocess
+import sys
+import tarfile
+import tempfile
+from contextlib import contextmanager
+from pathlib import Path
+
+import httpx
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.commands import serve_cmd
+
+from ._real_call_guard import guard_real_calls
+
+
[email protected](autouse=True)
+def _no_real_calls(monkeypatch) -> None:
+ guard_real_calls(monkeypatch)
+
+
+def _own_env(monkeypatch: pytest.MonkeyPatch, *names: str) -> None:
+ """Clear *names* so monkeypatch restores them even after raw assignment."""
+ for name in names:
+ monkeypatch.setenv(name, "x")
+ monkeypatch.delenv(name)
+
+
+_EMBED_ENV = (
+ "REPOWISE_EMBEDDER",
+ "REPOWISE_EMBEDDING_MODEL",
+ "GEMINI_API_KEY",
+ "GOOGLE_API_KEY",
+ "OPENAI_API_KEY",
+ "OPENROUTER_API_KEY",
+)
+
+
+# ---------------------------------------------------------------------------
+# _setup_embedder
+# ---------------------------------------------------------------------------
+
+
+def embed_env(monkeypatch, tmp_path) -> dict:
+ """Clean embedder env, a tmp global config dir and a scripted prompt."""
+ _own_env(monkeypatch, *_EMBED_ENV)
+ monkeypatch.setattr(serve_cmd, "_GLOBAL_CONFIG_DIR", tmp_path / "global")
+ state: dict = {"config": {}, "answers": [], "prompts": []}
+ monkeypatch.setattr(serve_cmd, "load_config", lambda _p: state["config"])
+
+ def fake_prompt(text, default=None, **_kw):
+ state["prompts"].append((text.strip(), default))
+ return state["answers"].pop(0)
+
+ monkeypatch.setattr(serve_cmd.click, "prompt", fake_prompt)
+ return state
+
+
+def _saved_global(tmp_path: Path) -> dict:
+ import yaml
+
+ return yaml.safe_load((tmp_path / "global" / "config.yaml").read_text(encoding="utf-8"))
+
+
+def test_embedder_env_already_set_skips_everything(embed_env, monkeypatch) -> None:
+ monkeypatch.setenv("REPOWISE_EMBEDDER", "openai")
+ embed_env["config"] = {"embedder": "gemini"}
+ serve_cmd._setup_embedder()
+ assert os.environ["REPOWISE_EMBEDDER"] == "openai"
+ assert embed_env["prompts"] == []
+
+
+def test_saved_embedder_restores_env_and_key(embed_env) -> None:
+ embed_env["config"] = {"embedder": "openrouter", "embedder_api_key": "sk-or"}
+ serve_cmd._setup_embedder()
+ assert os.environ["REPOWISE_EMBEDDER"] == "openrouter"
+ assert os.environ["OPENROUTER_API_KEY"] == "sk-or"
+ assert embed_env["prompts"] == []
+
+
+def test_saved_key_never_overwrites_exported_key(embed_env, monkeypatch) -> None:
+ monkeypatch.setenv("OPENAI_API_KEY", "from-env")
+ embed_env["config"] = {"embedder": "openai", "embedder_api_key": "from-config"}
+ serve_cmd._setup_embedder()
+ assert os.environ["OPENAI_API_KEY"] == "from-env"
+
+
+def test_saved_mock_embedder_falls_through_to_prompt(embed_env, tmp_path) -> None:
+ embed_env["config"] = {"embedder": "mock"}
+ embed_env["answers"] = ["skip"]
+ serve_cmd._setup_embedder()
+ assert "REPOWISE_EMBEDDER" not in os.environ
+ assert embed_env["prompts"] == [("Select", "3")]
+ assert not (tmp_path / "global").exists()
+
+
+ ("key_var", "default"),
+ [(None, "3"), ("GEMINI_API_KEY", "1"), ("GOOGLE_API_KEY", "1"), ("OPENAI_API_KEY", "1")],
+)
+def test_prompt_default_follows_exported_keys(embed_env, monkeypatch, key_var, default) -> None:
+ if key_var:
+ monkeypatch.setenv(key_var, "k")
+ embed_env["answers"] = ["4"]
+ serve_cmd._setup_embedder()
+ assert embed_env["prompts"][0] == ("Select", default)
+ assert "REPOWISE_EMBEDDER" not in os.environ
+
+
[email protected]("answer", ["9", "0", "nonsense", "skip", "4"])
+def test_unknown_or_skip_answer_skips(embed_env, answer) -> None:
+ embed_env["answers"] = [answer]
+ serve_cmd._setup_embedder()
+ assert "REPOWISE_EMBEDDER" not in os.environ
+ assert len(embed_env["prompts"]) == 1
+
+
+def test_numbered_choice_with_exported_key_saves_without_reprompt(
+ embed_env, monkeypatch, tmp_path
+) -> None:
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-env")
+ embed_env["answers"] = ["2"]
+ serve_cmd._setup_embedder()
+ assert os.environ["REPOWISE_EMBEDDER"] == "openai"
+ assert len(embed_env["prompts"]) == 1
+ # The exported key is persisted alongside the choice.
+ assert _saved_global(tmp_path) == {"embedder": "openai", "embedder_api_key": "sk-env"}
+
+
+def test_named_choice_prompts_for_missing_key(embed_env, tmp_path) -> None:
+ embed_env["answers"] = ["gemini", " sk-typed "]
+ serve_cmd._setup_embedder()
+ assert os.environ["REPOWISE_EMBEDDER"] == "gemini"
+ assert os.environ["GEMINI_API_KEY"] == "sk-typed"
+ assert [p[0] for p in embed_env["prompts"]] == ["Select", "GEMINI_API_KEY"]
+ assert _saved_global(tmp_path) == {"embedder": "gemini", "embedder_api_key": "sk-typed"}
+
+
+def test_blank_key_saves_choice_only_and_merges_existing(embed_env, tmp_path) -> None:
+ (tmp_path / "global").mkdir()
+ (tmp_path / "global" / "config.yaml").write_text("other: 1\n", encoding="utf-8")
+ embed_env["answers"] = ["3", ""]
+ serve_cmd._setup_embedder()
+ assert os.environ["REPOWISE_EMBEDDER"] == "openrouter"
+ assert "OPENROUTER_API_KEY" not in os.environ
+ assert _saved_global(tmp_path) == {"other": 1, "embedder": "openrouter"}
+
+
+def test_get_or_prompt_api_key_unknown_embedder_is_blank() -> None:
+ assert serve_cmd._get_or_prompt_api_key("ollama") == ""
+
+
+def test_set_api_key_env_ignores_blank_and_unknown(monkeypatch) -> None:
+ _own_env(monkeypatch, *_EMBED_ENV)
+ serve_cmd._set_api_key_env("openai", "")
+ serve_cmd._set_api_key_env("ollama", "k")
+ assert not any(n in os.environ for n in _EMBED_ENV)
+
+
+# ---------------------------------------------------------------------------
+# _load_local_provider_config
+# ---------------------------------------------------------------------------
+
+
+def _write_local_repowise(root: Path, *, env: str = "", config: str = "") -> None:
+ (root / ".repowise").mkdir()
+ if env:
+ (root / ".repowise" / ".env").write_text(env, encoding="utf-8")
+ if config:
+ (root / ".repowise" / "config.yaml").write_text(config, encoding="utf-8")
+
+
+def test_local_provider_config_noop_without_repowise_dir(monkeypatch, tmp_path) -> None:
+ _own_env(monkeypatch, *_EMBED_ENV)
+ monkeypatch.chdir(tmp_path)
+ serve_cmd._load_local_provider_config()
+ assert "REPOWISE_EMBEDDER" not in os.environ
+
+
+def test_local_provider_config_loads_env_and_seeds_embedder(monkeypatch, tmp_path) -> None:
+ _own_env(monkeypatch, *_EMBED_ENV)
+ _write_local_repowise(
+ tmp_path,
+ env="OPENAI_API_KEY=sk-local\n",
+ config="embedder: mock\nembedding_model: tiny-8\n",
+ )
+ monkeypatch.chdir(tmp_path)
+ serve_cmd._load_local_provider_config()
+ assert os.environ["OPENAI_API_KEY"] == "sk-local"
+ # "mock" is seeded too: it pins the on-disk vector width.
+ assert os.environ["REPOWISE_EMBEDDER"] == "mock"
+ assert os.environ["REPOWISE_EMBEDDING_MODEL"] == "tiny-8"
+
+
+def test_local_provider_config_never_overrides_env(monkeypatch, tmp_path) -> None:
+ _own_env(monkeypatch, *_EMBED_ENV)
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-env")
+ monkeypatch.setenv("REPOWISE_EMBEDDER", "gemini")
+ monkeypatch.setenv("REPOWISE_EMBEDDING_MODEL", "m-env")
+ _write_local_repowise(
+ tmp_path,
+ env="OPENAI_API_KEY=sk-local\n",
+ config="embedder: openai\nembedding_model: m-cfg\n",
+ )
+ monkeypatch.chdir(tmp_path)
+ serve_cmd._load_local_provider_config()
+ assert os.environ["OPENAI_API_KEY"] == "sk-env"
+ assert os.environ["REPOWISE_EMBEDDER"] == "gemini"
+ assert os.environ["REPOWISE_EMBEDDING_MODEL"] == "m-env"
+
+
+# ---------------------------------------------------------------------------
+# Port probing
+# ---------------------------------------------------------------------------
+
+
+def test_find_free_port_scans_upward(monkeypatch) -> None:
+ probed: list[int] = []
+
+ def fake_free(_host, port):
+ probed.append(port)
+ return port == 3002
+
+ monkeypatch.setattr(serve_cmd, "_is_port_free", fake_free)
+ assert serve_cmd._find_free_port("127.0.0.1", 3000, "web UI") == 3002
+ assert probed == [3000, 3001, 3002]
+
+
+def test_find_free_port_respects_max_attempts(monkeypatch) -> None:
+ probed: list[int] = []
+
+ def fake_free(_host, port):
+ probed.append(port)
+ return False
+
+ monkeypatch.setattr(serve_cmd, "_is_port_free", fake_free)
+ serve_cmd._find_free_port("127.0.0.1", 4000, "API server", max_attempts=3)
+ assert probed == [4000, 4001, 4002, 4003]
+
+
+def test_find_free_port_stops_scanning_at_65535(monkeypatch) -> None:
+ probed: list[int] = []
+
+ def fake_free(_host, port):
+ probed.append(port)
+ return False
+
+ monkeypatch.setattr(serve_cmd, "_is_port_free", fake_free)
+ chosen = serve_cmd._find_free_port("127.0.0.1", 65534, "API server")
+ assert probed == [65534, 65535]
+ assert isinstance(chosen, int) and chosen > 0
+
+
+# ---------------------------------------------------------------------------
+# Web asset resolution
+# ---------------------------------------------------------------------------
+
+
+def web_cache(monkeypatch, tmp_path) -> Path:
+ cache = tmp_path / "web-cache"
+ monkeypatch.setattr(serve_cmd, "_WEB_CACHE_DIR", cache)
+ monkeypatch.setattr(serve_cmd, "_MARKER_FILE", cache / ".version")
+ return cache
+
+
+def test_web_is_cached_requires_server_js_and_matching_marker(web_cache) -> None:
+ assert serve_cmd._web_is_cached("1.0.0") is False
+ web_cache.mkdir()
+ (web_cache / "server.js").write_text("")
+ assert serve_cmd._web_is_cached("1.0.0") is False # no marker
+ (web_cache / ".version").write_text("0.9.0\n")
+ assert serve_cmd._web_is_cached("1.0.0") is False
+ (web_cache / ".version").write_text("1.0.0\n")
+ assert serve_cmd._web_is_cached("1.0.0") is True
+
+
+def test_find_local_web_walks_up_from_cwd(monkeypatch, tmp_path) -> None:
+ repo = tmp_path / "repo"
+ (repo / "packages" / "web").mkdir(parents=True)
+ (repo / "packages" / "web" / "package.json").write_text("{}")
+ deep = repo / "a" / "b"
+ deep.mkdir(parents=True)
+ # Retarget to the submodule that reads __file__ once serve_cmd is a package.
+ monkeypatch.setattr(serve_cmd, "__file__", str(tmp_path / "x" / "y" / "serve_cmd.py"))
+ monkeypatch.chdir(deep)
+ assert serve_cmd._find_local_web() == (repo / "packages" / "web").resolve()
+
+
+def test_find_local_web_none_without_package_json(monkeypatch, tmp_path) -> None:
+ (tmp_path / "packages" / "web").mkdir(parents=True) # no package.json
+ # Retarget to the submodule that reads __file__ once serve_cmd is a package.
+ monkeypatch.setattr(serve_cmd, "__file__", str(tmp_path / "x" / "serve_cmd.py"))
+ monkeypatch.chdir(tmp_path)
+ assert serve_cmd._find_local_web() is None
+
+
+def _make_web_tree(root: Path) -> tuple[Path, Path]:
+ """A monorepo with packages/web, ui and types sources plus a built bundle."""
+ web = root / "packages" / "web"
+ server_js = web / ".next" / "standalone" / "packages" / "web" / "server.js"
+ server_js.parent.mkdir(parents=True)
+ server_js.write_text("")
+ (web / "package.json").write_text("{}")
+ (web / "src").mkdir()
+ (web / "src" / "page.tsx").write_text("")
+ (root / "packages" / "ui" / "src").mkdir(parents=True)
+ (root / "packages" / "ui" / "src" / "button.tsx").write_text("")
+ (web / "src" / "node_modules").mkdir()
+ (web / "src" / "node_modules" / "dep.js").write_text("")
+ old, built = 1_000_000, 2_000_000
+ for p in root.rglob("*"):
+ if p.is_file():
+ os.utime(p, (old, old))
+ os.utime(server_js, (built, built))
+ return web, server_js
+
+
+def test_local_build_stale_without_bundle(tmp_path) -> None:
+ web = tmp_path / "packages" / "web"
+ web.mkdir(parents=True)
+ assert serve_cmd._local_build_is_stale(web) is True
+
+
+def test_local_build_fresh_when_sources_older(tmp_path) -> None:
+ web, _ = _make_web_tree(tmp_path)
+ assert serve_cmd._local_build_is_stale(web) is False
+
+
+ "newer",
+ ["packages/web/package.json", "packages/web/src/page.tsx", "packages/ui/src/button.tsx"],
+)
+def test_local_build_stale_when_an_input_is_newer(tmp_path, newer) -> None:
+ web, _ = _make_web_tree(tmp_path)
+ os.utime(tmp_path / newer, (3_000_000, 3_000_000))
+ assert serve_cmd._local_build_is_stale(web) is True
+
+
+def test_local_build_ignores_skipped_dirs(tmp_path) -> None:
+ web, _ = _make_web_tree(tmp_path)
+ os.utime(web / "src" / "node_modules" / "dep.js", (3_000_000, 3_000_000))
+ assert serve_cmd._local_build_is_stale(web) is False
+
+
+def _tarball(files: dict[str, bytes]) -> bytes:
+ buf = io.BytesIO()
+ with tarfile.open(fileobj=buf, mode="w:gz") as tar:
+ for name, data in files.items():
+ info = tarfile.TarInfo(name)
+ info.size = len(data)
+ tar.addfile(info, io.BytesIO(data))
+ return buf.getvalue()
+
+
+def fake_download(monkeypatch, tmp_path) -> dict:
+ """Route httpx.stream to canned bytes and tempfile into a watched dir."""
+ tmp_dir = tmp_path / "tmp"
+ tmp_dir.mkdir()
+ monkeypatch.setattr(tempfile, "tempdir", str(tmp_dir))
+ state: dict = {"body": b"", "error": None, "urls": [], "tmp_dir": tmp_dir}
+
+ class _Resp:
+ def raise_for_status(self) -> None:
+ if state["error"] is not None:
+ raise state["error"]
+
+ def iter_bytes(self, chunk_size: int):
+ body = state["body"]
+ for i in range(0, len(body), chunk_size):
+ yield body[i : i + chunk_size]
+
+ @contextmanager
+ def fake_stream(method, url, **_kw):
+ state["urls"].append((method, url))
+ yield _Resp()
+
+ monkeypatch.setattr(httpx, "stream", fake_stream)
+ return state
+
+
+def test_download_web_replaces_cache_and_writes_marker(web_cache, fake_download) -> None:
+ web_cache.mkdir()
+ (web_cache / "stale.js").write_text("old")
+ (web_cache / "old_dir").mkdir()
+ fake_download["body"] = _tarball({"server.js": b"// new", ".next/x.js": b"1"})
+
+ assert serve_cmd._download_web("1.2.3") is True
+ assert fake_download["urls"] == [
+ (
+ "GET",
+ "https://github.com/repowise-dev/repowise/releases/download/v1.2.3/repowise-web.tar.gz",
+ )
+ ]
+ assert sorted(p.name for p in web_cache.iterdir()) == [".next", ".version", "server.js"]
+ assert (web_cache / ".version").read_text() == "1.2.3"
+ assert list(fake_download["tmp_dir"].iterdir()) == []
+
+
+def test_download_web_http_error_keeps_cache(web_cache, fake_download) -> None:
+ web_cache.mkdir()
+ (web_cache / "server.js").write_text("old")
+ request = httpx.Request("GET", "https://example.invalid")
+ fake_download["error"] = httpx.HTTPStatusError(
+ "404", request=request, response=httpx.Response(404, request=request)
+ )
+ assert serve_cmd._download_web("1.2.3") is False
+ assert (web_cache / "server.js").read_text() == "old"
+ assert list(fake_download["tmp_dir"].iterdir()) == []
+
+
+def test_download_web_bad_archive_returns_false(web_cache, fake_download) -> None:
+ fake_download["body"] = b"not a tarball"
+ assert serve_cmd._download_web("1.2.3") is False
+ assert not (web_cache / ".version").exists()
+ assert list(fake_download["tmp_dir"].iterdir()) == []
+
+
+def fake_run(monkeypatch) -> dict:
+ """Record subprocess.run calls; raise on the call numbered ``fail_at``."""
+ st: dict = {"calls": [], "fail_at": None}
+
+ def _run(cmd, **kw):
+ st["calls"].append((cmd, kw))
+ if len(st["calls"]) == st["fail_at"]:
+ raise subprocess.CalledProcessError(1, cmd)
+
+ monkeypatch.setattr(serve_cmd.subprocess, "run", _run)
+ return st
+
+
+def test_build_local_web_installs_then_builds(tmp_path, fake_run) -> None:
+ calls = fake_run["calls"]
+ assert serve_cmd._build_local_web(tmp_path, "npm") is True
+ assert [c[0] for c in calls] == [["npm", "install"], ["npm", "run", "build"]]
+ assert all(c[1]["cwd"] == str(tmp_path) and c[1]["check"] for c in calls)
+
+
+def test_build_local_web_skips_install_with_node_modules(tmp_path, fake_run) -> None:
+ calls = fake_run["calls"]
+ (tmp_path / "node_modules").mkdir()
+ assert serve_cmd._build_local_web(tmp_path, "npm") is True
+ assert [c[0] for c in calls] == [["npm", "run", "build"]]
+
+
+def test_build_local_web_failure_returns_false(tmp_path, fake_run) -> None:
+ calls = fake_run["calls"]
+ fake_run["fail_at"] = 1
+ assert serve_cmd._build_local_web(tmp_path, "npm") is False
+ assert [c[0] for c in calls] == [["npm", "install"]]
+
+
+# ---------------------------------------------------------------------------
+# _start_frontend
+# ---------------------------------------------------------------------------
+
+
+def fake_popen(monkeypatch) -> list:
+ calls: list = []
+
+ def _popen(cmd, **kw):
+ calls.append((cmd, kw))
+ return "proc"
+
+ monkeypatch.setattr(serve_cmd.subprocess, "Popen", _popen)
+ return calls
+
+
+def test_start_frontend_local_build_copies_assets(tmp_path, web_cache, fake_popen) -> None:
+ web = tmp_path / "web"
+ app = web / ".next" / "standalone" / "packages" / "web"
+ app.mkdir(parents=True)
+ (app / "server.js").write_text("")
+ (web / ".next" / "static").mkdir()
+ (web / ".next" / "static" / "chunk.js").write_text("c")
+ (web / "public").mkdir()
+ (web / "public" / "logo.svg").write_text("l")
+
+ proc = serve_cmd._start_frontend("node", 7400, 3100, local_web=web, host="0.0.0.0")
+
+ assert proc == "proc"
+ assert (app / ".next" / "static" / "chunk.js").read_text() == "c"
+ assert (app / "public" / "logo.svg").read_text() == "l"
+ [(cmd, kw)] = fake_popen
+ assert cmd == ["node", str(app / "server.js")]
+ assert kw["cwd"] == str(app)
+ assert kw["env"]["REPOWISE_API_URL"] == "http://localhost:7400"
+ assert kw["env"]["HOSTNAME"] == "0.0.0.0"
+ assert kw["env"]["PORT"] == "3100"
+
+
+def test_start_frontend_leaves_existing_static_alone(tmp_path, web_cache, fake_popen) -> None:
+ web = tmp_path / "web"
+ app = web / ".next" / "standalone" / "packages" / "web"
+ (app / ".next" / "static").mkdir(parents=True)
+ (app / "server.js").write_text("")
+ (web / ".next" / "static").mkdir(parents=True)
+ (web / ".next" / "static" / "new.js").write_text("n")
+ serve_cmd._start_frontend("node", 7337, 3000, local_web=web)
+ assert not (app / ".next" / "static" / "new.js").exists()
+
+
+def test_start_frontend_falls_back_to_cache(tmp_path, web_cache, fake_popen) -> None:
+ web = tmp_path / "web" # no standalone bundle
+ web.mkdir()
+ web_cache.mkdir()
+ (web_cache / "server.js").write_text("")
+ assert serve_cmd._start_frontend("node", 7337, 3000, local_web=web) == "proc"
+ [(cmd, kw)] = fake_popen
+ assert cmd == ["node", str(web_cache / "server.js")]
+ assert kw["cwd"] == str(web_cache)
+
+
+def test_start_frontend_none_without_any_bundle(web_cache, fake_popen) -> None:
+ assert serve_cmd._start_frontend("node", 7337, 3000) is None
+ assert fake_popen == []
+
+
+# ---------------------------------------------------------------------------
+# serve_command branch order
+# ---------------------------------------------------------------------------
+
+
+class _Proc:
+ def __init__(self, events: list) -> None:
+ self.events = events
+
+ def terminate(self) -> None:
+ self.events.append("terminate")
+
+ def wait(self, timeout=None) -> None:
+ self.events.append(("wait", timeout))
+
+
+def serve(monkeypatch, tmp_path) -> dict:
+ """Stub every side effect of `serve` and record the order of calls."""
+ _own_env(monkeypatch, "REPOWISE_API_KEY")
+ monkeypatch.setenv("REPOWISE_HOST", "127.0.0.1")
+ monkeypatch.setenv("REPOWISE_DB_URL", "sqlite+aiosqlite:///:memory:")
+ (tmp_path / ".repowise").mkdir()
+ monkeypatch.chdir(tmp_path)
+
+ st: dict = {
+ "events": [],
+ "node": "node",
+ "npm": "npm",
+ "node_major": 22,
+ "local_web": None,
+ "stale": False,
+ "build_ok": True,
+ "cached": False,
+ "download_ok": False,
+ "proc": True,
+ "lock": None,
+ }
+ ev = st["events"]
+
+ def rec(name, value=None):
+ def _f(*a, **kw):
+ ev.append((name, *a, *sorted(kw.items())))
+ return st[value] if value else None
+
+ return _f
+
+ monkeypatch.setattr(serve_cmd, "_update_advisory_tick", lambda _a: None)
+ monkeypatch.setattr(serve_cmd, "_start_update_advisory_loop", lambda _a: None)
+ monkeypatch.setattr(serve_cmd, "_load_local_provider_config", rec("load_local"))
+ monkeypatch.setattr(serve_cmd, "_setup_embedder", rec("setup_embedder"))
+
+ def free_port(host, port, label):
+ ev.append(("port", host, port, label))
+ return port + 1
+
+ monkeypatch.setattr(serve_cmd, "_find_free_port", free_port)
+ monkeypatch.setattr(serve_cmd, "_node_available", lambda: st["node"])
+ monkeypatch.setattr(serve_cmd, "_npm_available", lambda: st["npm"])
+ monkeypatch.setattr(serve_cmd, "_node_major_version", lambda _n: st["node_major"])
+ monkeypatch.setattr(serve_cmd, "_find_local_web", rec("find_local", "local_web"))
+ monkeypatch.setattr(serve_cmd, "_local_build_is_stale", rec("stale", "stale"))
+ monkeypatch.setattr(serve_cmd, "_build_local_web", rec("build", "build_ok"))
+ monkeypatch.setattr(serve_cmd, "_web_is_cached", rec("cached", "cached"))
+ monkeypatch.setattr(serve_cmd, "_download_web", rec("download", "download_ok"))
+
+ def start(node, port, ui_port, local_web=None, host=None):
+ ev.append(("start", node, port, ui_port, local_web, host))
+ return _Proc(ev) if st["proc"] else None
+
+ monkeypatch.setattr(serve_cmd, "_start_frontend", start)
+
+ def fake_uvicorn(app, **kw):
+ lock = serve_cmd._serve_lock_path()
+ if lock is not None:
+ st["lock"] = json.loads(lock.read_text(encoding="utf-8"))
+ ev.append(("uvicorn", app, *sorted(kw.items())))
+
+ monkeypatch.setattr("uvicorn.run", fake_uvicorn)
+ st["tmp"] = tmp_path
+ return st
+
+
+def _invoke(*args: str):
+ return CliRunner().invoke(serve_cmd.serve_command, list(args))
+
+
+def _names(events: list) -> list:
+ return [e if isinstance(e, str) else e[0] for e in events]
+
+
+def test_serve_api_only_order_and_uvicorn_args(serve) -> None:
+ result = _invoke("--no-ui", "--port", "8000", "--workers", "2")
+ assert result.exit_code == 0, result.output
+ assert serve["events"] == [
+ ("load_local",),
+ ("setup_embedder",),
+ ("port", "127.0.0.1", 8000, "API server"),
+ (
+ "uvicorn",
+ "repowise.server.app:create_app",
+ ("factory", True),
+ ("host", "127.0.0.1"),
+ ("log_level", "info"),
+ ("port", 8001),
+ ("workers", 2),
+ ),
+ ]
+ assert serve["lock"]["port"] == 8001
+ assert serve["lock"]["ui_port"] is None
+ # The lock is removed once uvicorn returns.
+ assert not (serve["tmp"] / ".repowise" / "serve.lock.json").exists()
+
+
+def test_serve_without_node_skips_ui(serve) -> None:
+ serve["node"] = None
+ result = _invoke()
+ assert result.exit_code == 0, result.output
+ assert "Node.js" in result.output
+ assert _names(serve["events"]) == [
+ "load_local",
+ "setup_embedder",
+ "port",
+ "port",
+ "uvicorn",
+ ]
+ assert serve["events"][3] == ("port", "127.0.0.1", 3000, "web UI")
+ assert serve["lock"]["ui_port"] is None
+
+
+def test_serve_old_node_skips_ui(serve) -> None:
+ serve["node_major"] = 18
+ result = _invoke()
+ assert "too old" in result.output
+ assert "start" not in _names(serve["events"])
+
+
+def test_serve_unknown_node_version_still_tries_ui(serve) -> None:
+ serve["node_major"] = None
+ serve["cached"] = True
+ _invoke()
+ assert "start" in _names(serve["events"])
+
+
+def test_serve_fresh_local_build_starts_it(serve, tmp_path) -> None:
+ serve["local_web"] = tmp_path / "web"
+ result = _invoke("--host", "0.0.0.0")
+ assert result.exit_code == 0, result.output
+ assert _names(serve["events"]) == [
+ "load_local",
+ "setup_embedder",
+ "port",
+ "port",
+ "find_local",
+ "stale",
+ "start",
+ "uvicorn",
+ "terminate",
+ "wait",
+ ]
+ assert serve["events"][6] == ("start", "node", 7338, 3001, tmp_path / "web", "0.0.0.0")
+ assert serve["events"][-1] == ("wait", 5)
+ assert serve["lock"]["ui_port"] == 3001
+ assert serve["lock"]["url"] == "http://127.0.0.1:7338"
+
+
+def test_serve_stale_local_build_rebuilds(serve, tmp_path) -> None:
+ serve["local_web"] = tmp_path / "web"
+ serve["stale"] = True
+ _invoke()
+ names = _names(serve["events"])
+ assert names[4:8] == ["find_local", "stale", "build", "start"]
+ assert serve["events"][6] == ("build", tmp_path / "web", "npm")
+ assert serve["events"][7][4] == tmp_path / "web"
+
+
+def test_serve_failed_rebuild_falls_back_to_cache(serve, tmp_path) -> None:
+ serve["local_web"] = tmp_path / "web"
+ serve["stale"] = True
+ serve["build_ok"] = False
+ serve["cached"] = True
+ result = _invoke()
+ assert "rebuild failed" in result.output
+ names = _names(serve["events"])
+ assert names[4:9] == ["find_local", "stale", "build", "cached", "start"]
+ assert serve["events"][8][4] is None # local_web dropped
+
+
+def test_serve_stale_without_npm_downloads(serve, tmp_path) -> None:
+ serve["local_web"] = tmp_path / "web"
+ serve["stale"] = True
+ serve["npm"] = None
+ serve["download_ok"] = True
+ result = _invoke()
+ assert "npm" in result.output
+ names = _names(serve["events"])
+ assert names[4:9] == ["find_local", "stale", "cached", "download", "start"]
+ assert serve["events"][8][4] is None
+
+
+def test_serve_refresh_ui_skips_local_and_cache(serve) -> None:
+ serve["download_ok"] = True
+ _invoke("--refresh-ui")
+ names = _names(serve["events"])
+ assert "find_local" not in names and "cached" not in names
+ assert names[4:6] == ["download", "start"]
+
+
+def test_serve_no_assets_runs_api_only(serve) -> None:
+ result = _invoke()
+ assert "not available" in result.output
+ names = _names(serve["events"])
+ assert names[4:] == ["find_local", "cached", "download", "uvicorn"]
+ assert serve["lock"]["ui_port"] is None
+
+
+def test_serve_frontend_that_fails_to_start(serve) -> None:
+ serve["cached"] = True
+ serve["proc"] = False
+ result = _invoke()
+ assert "Could not start web UI" in result.output
+ assert serve["lock"]["ui_port"] is None
+ assert "terminate" not in _names(serve["events"])
+
+
+def test_serve_missing_uvicorn_exits_1(serve, monkeypatch) -> None:
+ monkeypatch.setitem(sys.modules, "uvicorn", None)
+ result = _invoke("--no-ui")
+ assert result.exit_code == 1
+ assert "uvicorn is not installed" in result.output
+ assert serve["events"] == []
+
+
+def test_serve_advisory_runs_only_on_a_terminal(serve, monkeypatch) -> None:
+ ticks: list = []
+ monkeypatch.setattr(serve_cmd, "_update_advisory_tick", lambda a: ticks.append("tick"))
+ monkeypatch.setattr(serve_cmd, "_start_update_advisory_loop", lambda a: ticks.append("loop"))
+ monkeypatch.setattr(type(serve_cmd.console), "is_terminal", property(lambda _s: False))
+ _invoke("--no-ui")
+ assert ticks == []
+ monkeypatch.setattr(type(serve_cmd.console), "is_terminal", property(lambda _s: True))
+ _invoke("--no-ui")
+ assert ticks == ["tick", "loop"]
+
+
+def test_serve_db_url_uses_posix_path(serve, monkeypatch, tmp_path) -> None:
+ # Unrecorded pop: the autouse guard in tests/conftest.py restores it.
+ os.environ.pop("REPOWISE_DB_URL", None)
+ _invoke("--no-ui")
+ expected = (tmp_path / ".repowise" / "wiki.db").as_posix()
+ assert os.environ["REPOWISE_DB_URL"] == f"sqlite+aiosqlite:///{expected}"
+
+
+def test_serve_no_db_url_without_local_store(serve, monkeypatch, tmp_path) -> None:
+ (tmp_path / "elsewhere").mkdir()
+ monkeypatch.chdir(tmp_path / "elsewhere")
+ os.environ.pop("REPOWISE_DB_URL", None)
+ result = _invoke("--no-ui")
+ assert result.exit_code == 0, result.output
+ assert "REPOWISE_DB_URL" not in os.environ
+ assert serve["lock"] is None # no index dir, no lockfile
diff --git a/tests/unit/cli/test_update_progress_json.py b/tests/unit/cli/test_update_progress_json.py
index a7cf5e86e..68ef1d04e 100644
--- a/tests/unit/cli/test_update_progress_json.py
+++ b/tests/unit/cli/test_update_progress_json.py
@@ -13,12 +13,16 @@ import json
import os
import tempfile
+import pytest
from click.testing import CliRunner
from repowise.cli.commands.update_cmd.reporting import JsonProgressEmitter
+from repowise.cli.helpers import save_state
from repowise.cli.main import cli
from repowise.core.ingestion.git_indexer import GIT_HISTORY_VERSION, GIT_HISTORY_VERSION_KEY
+from ._real_call_guard import guard_real_calls
+
# An index written by this build: its git rows follow the current rules.
CURRENT_GIT_HISTORY = {GIT_HISTORY_VERSION_KEY: GIT_HISTORY_VERSION}
@@ -182,3 +186,159 @@ class TestUpdateProgressJsonCli:
for line in result.stdout.splitlines():
if line.strip():
assert not line.strip().startswith("{")
+
+
+# ---------------------------------------------------------------------------
+# run_update call order: pinned before the function is split.
+# ---------------------------------------------------------------------------
+
+
+def _git(repo, *args: str) -> str:
+ import subprocess
+
+ result = subprocess.run(["git", *args], cwd=str(repo), capture_output=True, text=True)
+ return result.stdout.strip()
+
+
+def _indexed_repo(tmp_path):
+ """A two-file git repo with a real index-only index (no LLM)."""
+ import asyncio
+
+ from repowise.core.pipeline.full_index import index_repo_full
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(repo, "init")
+ _git(repo, "config", "user.email", "[email protected]")
+ _git(repo, "config", "user.name", "Test")
+ (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")
+ asyncio.run(index_repo_full(repo))
+ save_state(repo, {"last_sync_commit": _git(repo, "rev-parse", "HEAD"), "docs_enabled": False})
+ # A first update writes every stamp a fresh index lacks, so the run under
+ # test sees a settled store.
+ warm = CliRunner().invoke(cli, ["update", str(repo), "--index-only", "--no-workspace"])
+ assert warm.exit_code == 0, warm.output
+ _release_lock(repo)
+ return repo
+
+
+def _release_lock(repo) -> None:
+ """A content-changing run holds its lock until process exit (atexit), so
+ an in-process caller releases it before the next run, as watch does."""
+ from repowise.cli.commands.update_cmd.command import clear_update_queued, release_update_lock
+
+ release_update_lock(repo)
+ clear_update_queued(repo)
+
+
+def _spy_calls(monkeypatch) -> list[str]:
+ """Wrap the persistence steps in the namespaces run_update reads them from."""
+ from repowise.cli.commands.update_cmd import command, persistence
+
+ calls: list[str] = []
+
+ def spy(module, name: str, label: str) -> None:
+ real = getattr(module, name)
+
+ def _wrapped(*args, **kwargs):
+ calls.append(label)
+ return real(*args, **kwargs)
+
+ monkeypatch.setattr(module, name, _wrapped)
+
+ spy(command, "save_state", "save_state")
+ spy(persistence, "save_state", "save_state")
+ spy(command, "stamp_head_commit", "stamp_head_commit")
+ spy(command, "_finish_outcome", "finish_outcome")
+ spy(command, "consume_update_pending", "consume_update_pending")
+ spy(command, "_record_update_outcome", "record_update_outcome")
+ return calls
+
+
+def _events(result) -> list[dict]:
+ return [json.loads(line) for line in result.stdout.splitlines() if line.strip()]
+
+
+class TestRunUpdateSequence:
+ @pytest.fixture(autouse=True)
+ def _no_real_calls(self, monkeypatch) -> None:
+ # git stays real: the update reads an actual repository.
+ guard_real_calls(monkeypatch, allow_git=True)
+
+ def test_no_changed_files_path_order(self, monkeypatch):
+ """The --since early return persists state, then stamps, then finishes."""
+ calls = _spy_calls(monkeypatch)
+ runner = _split_output_runner()
+ with tempfile.TemporaryDirectory() as td:
+ os.makedirs(os.path.join(td, ".repowise"))
+ with open(os.path.join(td, ".repowise", "state.json"), "w") as f:
+ json.dump(
+ {"last_sync_commit": "deadbeef", "docs_mode": "none", **CURRENT_GIT_HISTORY},
+ f,
+ )
+ result = runner.invoke(
+ cli, ["update", td, "--since", "deadbeef", "--progress", "json"]
+ )
+
+ assert result.exit_code == 0, result.output
+ assert [e["event"] for e in _events(result)] == ["start", "stage", "done"]
+ assert _events(result)[1] == {"event": "stage", "name": "detect_changes"}
+ assert calls == [
+ "save_state",
+ "stamp_head_commit",
+ "finish_outcome",
+ "consume_update_pending",
+ ]
+
+ def test_incremental_index_only_update(self, monkeypatch, tmp_path):
+ repo = _indexed_repo(tmp_path)
+ (repo / "c.py").write_text("def gamma():\n return 3\n")
+ _git(repo, "add", ".")
+ _git(repo, "commit", "-m", "add c")
+ head = _git(repo, "rev-parse", "HEAD")
+
+ calls = _spy_calls(monkeypatch)
+ result = _split_output_runner().invoke(
+ cli, ["update", str(repo), "--index-only", "--no-workspace", "--progress", "json"]
+ )
+
+ assert result.exit_code == 0, result.output
+ events = _events(result)
+ assert [(e["event"], e.get("name")) for e in events] == [
+ ("start", None),
+ ("stage", "detect_changes"),
+ ("stage", "rebuild_graph"),
+ ("stage", "plan_pages"),
+ ("stage", "persist"),
+ ("done", None),
+ ]
+ assert events[-1]["ok"] is True
+ assert events[-1]["outcome"] == "regenerated"
+ # The index-only path stamps the DB head inside its persist step, not
+ # through stamp_head_commit.
+ assert calls == [
+ "save_state",
+ "finish_outcome",
+ "consume_update_pending",
+ "record_update_outcome",
+ ]
+ state = json.loads((repo / ".repowise" / "state.json").read_text(encoding="utf-8"))
+ assert state["last_sync_commit"] == head
+
+ def test_already_up_to_date_early_return(self, monkeypatch, tmp_path):
+ repo = _indexed_repo(tmp_path)
+ calls = _spy_calls(monkeypatch)
+ result = _split_output_runner().invoke(
+ cli, ["update", str(repo), "--index-only", "--no-workspace", "--progress", "json"]
+ )
+
+ assert result.exit_code == 0, result.output
+ events = _events(result)
+ assert [e["event"] for e in events] == ["start", "done"]
+ assert events[-1]["outcome"] == "noop"
+ assert "Already up to date" in result.stderr
+ # No save_state (nothing to backfill) and no outcome record on this path.
+ assert calls == ["stamp_head_commit", "finish_outcome", "consume_update_pending"]