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.

fix(cli): let update --full reuse an index copied to a new path (#4308)

Raghav Chamadiyab60f9c34932b
diff --git a/packages/cli/src/repowise/cli/commands/upgrade_flow.py b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
index bdfe628c2..cabefa8a8 100644
--- a/packages/cli/src/repowise/cli/commands/upgrade_flow.py
+++ b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
@@ -310,8 +310,17 @@ async def _run_upgrade(
# 3. Rehydrate the graph from SQL — no parse, no resolution, no recompute.
from repowise.core.persistence import get_session
- async with get_session(sf) as session:
- graph_builder = await rehydrate_graph_builder(session, repo_id, repo_path)
+ try:
+ async with get_session(sf) as session:
+ graph_builder = await rehydrate_graph_builder(session, repo_id, repo_path)
+ except ValueError as exc:
+ # Only the empty-graph case; any other ValueError is a real fault.
+ if "No persisted graph nodes" not in str(exc):
+ raise
+ await engine.dispose()
+ raise click.ClickException(
+ f"The index at {repo_path} has no code graph. Run `repowise init` to rebuild it."
+ ) from None
# 4. Re-parse for ASTs + source (the only unavoidable re-work). The graph
# is NOT rebuilt — generation traverses the rehydrated SQL graph.
@@ -456,21 +465,38 @@ async def _open_repository(repo_path: Path) -> tuple[Any, Any, Any]:
The row comes FIRST: pipeline_jobs.repository_id is an FK to repositories.id,
so it must exist before the backfill creates its checkpoint job.
+
+ A repo-local store copied from another path keeps the old ``local_path``.
+ Its single row is rebound here, as ``repo_index_session`` reads it, so the
+ upsert reuses the indexed row instead of adding an empty one.
"""
+ from sqlalchemy import select
+
from repowise.cli.helpers import get_db_url_for_repo
from repowise.core.persistence import (
create_engine,
create_session_factory,
+ get_configured_db_url,
+ get_repository_by_path,
get_session,
init_db,
upsert_repository,
)
+ from repowise.core.persistence.models import Repository
url = get_db_url_for_repo(repo_path)
engine = create_engine(url)
await init_db(engine)
sf = create_session_factory(engine)
async with get_session(sf) as session:
+ if (
+ get_configured_db_url() is None
+ and await get_repository_by_path(session, str(repo_path)) is None
+ ):
+ repos = (await session.scalars(select(Repository).limit(2))).all()
+ if len(repos) == 1:
+ repos[0].local_path = str(repo_path)
+ await session.flush()
repo = await upsert_repository(
session, name=repo_path.name, local_path=str(repo_path), stamp_head=True
)
diff --git a/tests/unit/cli/test_full_upgrade_moved_index.py b/tests/unit/cli/test_full_upgrade_moved_index.py
new file mode 100644
index 000000000..d87ff069b
--- /dev/null
+++ b/tests/unit/cli/test_full_upgrade_moved_index.py
@@ -0,0 +1,122 @@
+"""``repowise update --full`` on an index copied to a new path.
+
+The copied ``wiki.db`` keeps the old ``local_path``. The upgrade must reuse
+that repository row, not add an empty one whose missing graph then fails the
+rehydrate with a raw traceback.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+import click
+import pytest
+
+from repowise.cli.commands import upgrade_flow as up_mod
+
+
+def _seed_store(repo: Path, local_path: str) -> str:
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ upsert_repository,
+ )
+
+ async def _run() -> str:
+ engine = create_engine(f"sqlite+aiosqlite:///{repo / '.repowise' / 'wiki.db'}")
+ await init_db(engine)
+ async with get_session(create_session_factory(engine)) as session:
+ row = await upsert_repository(session, name=Path(local_path).name, local_path=local_path)
+ repo_id = row.id
+ await engine.dispose()
+ return repo_id
+
+ return asyncio.run(_run())
+
+
+def _repo_rows(repo: Path) -> list[tuple[str, str]]:
+ import sqlite3
+ from contextlib import closing
+
+ with closing(sqlite3.connect(repo / ".repowise" / "wiki.db")) as conn:
+ return conn.execute("SELECT id, local_path FROM repositories").fetchall()
+
+
+def moved_repo(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Path, str]:
+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)
+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)
+ repo = tmp_path / "repo-b"
+ (repo / ".repowise").mkdir(parents=True)
+ repo_id = _seed_store(repo, str(tmp_path / "repo-a"))
+ return repo, repo_id
+
+
+def test_open_repository_reuses_the_moved_row(moved_repo: tuple[Path, str]) -> None:
+ repo, repo_id = moved_repo
+
+ async def _open() -> str:
+ engine, _sf, opened_id = await up_mod._open_repository(repo)
+ await engine.dispose()
+ return opened_id
+
+ assert asyncio.run(_open()) == repo_id
+ assert _repo_rows(repo) == [(repo_id, str(repo))]
+
+
+def test_missing_graph_is_a_clear_error(
+ moved_repo: tuple[Path, str], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ repo, _ = moved_repo
+
+ async def _no_backfill(*a: object, **k: object) -> tuple[dict, None]:
+ return {}, None
+
+ monkeypatch.setattr(up_mod, "_backfill_git", _no_backfill)
+ run = up_mod._run_upgrade(
+ repo,
+ None,
+ None,
+ exclude_patterns=[],
+ commit_limit=None,
+ follow_renames=False,
+ embedder_name=None,
+ yes=True,
+ )
+ with pytest.raises(click.ClickException, match="repowise init"):
+ asyncio.run(run)
+
+
+def test_a_store_with_several_repos_is_not_rebound(
+ moved_repo: tuple[Path, str],
+) -> None:
+ repo, repo_id = moved_repo
+ other_id = _seed_store(repo, str(repo.parent / "repo-c"))
+
+ async def _open() -> str:
+ engine, _sf, opened_id = await up_mod._open_repository(repo)
+ await engine.dispose()
+ return opened_id
+
+ opened = asyncio.run(_open())
+ assert opened not in (repo_id, other_id)
+ assert (repo_id, str(repo.parent / "repo-a")) in _repo_rows(repo)
+
+
+def test_a_configured_database_is_not_rebound(
+ moved_repo: tuple[Path, str], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ repo, repo_id = moved_repo
+ monkeypatch.setattr("repowise.core.persistence.get_configured_db_url", lambda: "sqlite://")
+ monkeypatch.setattr("repowise.cli.helpers.get_db_url_for_repo", lambda _p: f"sqlite+aiosqlite:///{repo / '.repowise' / 'wiki.db'}")
+
+ async def _open() -> str:
+ engine, _sf, opened_id = await up_mod._open_repository(repo)
+ await engine.dispose()
+ return opened_id
+
+ assert asyncio.run(_open()) != repo_id
+ assert (repo_id, str(repo.parent / "repo-a")) in _repo_rows(repo)