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
fix(cli): read the local index after repository relocation (#3240)
abhi265f32b2546100
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.pyindex ac4db646e..fdde04ed3 100644--- a/packages/cli/src/repowise/cli/helpers.py+++ b/packages/cli/src/repowise/cli/helpers.py@@ -306,11 +306,17 @@ async def repo_index_session(root: Path) -> AsyncIterator[tuple[AsyncSession, ststore skips it. A store still behind after it raises :class:`StaleIndexError`,since every answer read from it would be missing what it lacks."""+ from sqlalchemy import selectfrom sqlalchemy.exc import SQLAlchemyErrorfrom repowise.core.persistence import create_engine, create_session_factory, get_sessionfrom repowise.core.persistence.crud import get_repository_by_path- from repowise.core.persistence.database import has_db_store, schema_behind+ from repowise.core.persistence.database import (+ get_configured_db_url,+ has_db_store,+ schema_behind,+ )+ from repowise.core.persistence.models import Repository# The configured store, which may live outside the repo (REPOWISE_DB_URL).if not has_db_store(root):@@ -331,6 +337,13 @@ async def repo_index_session(root: Path) -> AsyncIterator[tuple[AsyncSession, stfactory = create_session_factory(engine)session = await stack.enter_async_context(get_session(factory))repo = await get_repository_by_path(session, str(root))+ if repo is None and get_configured_db_url() is None:+ # A moved repo carries its local store but retains the old+ # local_path. Never infer identity in a configured/shared store+ # or when the local store contains more than one repository.+ repos = (await session.scalars(select(Repository).limit(2))).all()+ if len(repos) == 1:+ repo = repos[0]if repo is not None:opened = (session, repo.id)except (SQLAlchemyError, OSError, LookupError):diff --git a/tests/unit/cli/test_next_cmd.py b/tests/unit/cli/test_next_cmd.pyindex 8ccb93d30..3d32158bc 100644--- a/tests/unit/cli/test_next_cmd.py+++ b/tests/unit/cli/test_next_cmd.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport asyncioimport datetimeimport json+import sqlite3from pathlib import Pathfrom typing import Any@@ -252,3 +253,70 @@ def test_reads_a_real_index(tmp_path: Path) -> None:out = _run(str(repo_path), "--horizon", "quarter").outputassert "Worth planning" in outassert "unused" in out++[email protected]("outdated_schema", [False, True])+def test_reads_a_repo_local_index_after_the_folder_is_moved(+ tmp_path: Path, outdated_schema: bool+) -> None:+ original = tmp_path / "original"+ original.mkdir()+ asyncio.run(_build_index(original))+ if outdated_schema:+ # Reconciliation must finish before the relocated repository is read.+ with sqlite3.connect(original / ".repowise" / "wiki.db") as conn:+ conn.execute("ALTER TABLE health_file_metrics DROP COLUMN analyzed_commit")+ moved = tmp_path / "moved"+ original.rename(moved)++ result = _run(str(moved), "--format", "json")+ assert result.exit_code == 0, result.output+ view = json.loads(result.stdout)+ assert view["status"] == "available"+ assert "dead_code_batch" in {+ a["rule"] for a in view["horizons"]["quarter"]["actions"]+ }++[email protected]("env_name", ["REPOWISE_DB_URL", "REPOWISE_DATABASE_URL"])+def test_a_configured_store_does_not_fall_back_to_another_repo(+ tmp_path: Path, monkeypatch, env_name: str+) -> None:+ indexed = tmp_path / "indexed"+ indexed.mkdir()+ asyncio.run(_build_index(indexed))+ other = tmp_path / "other"+ other.mkdir()+ monkeypatch.setenv(env_name, f"sqlite:///{indexed}/.repowise/wiki.db")++ result = _run(str(other), "--format", "json")+ assert result.exit_code == 0, result.output+ assert json.loads(result.stdout)["status"] == "unavailable"+++def test_a_local_store_with_multiple_repositories_requires_an_exact_path(tmp_path: Path):+ from repowise.cli.helpers import repo_index_session+ from repowise.core.persistence import create_engine, create_session_factory, get_session+ from repowise.core.persistence.crud import upsert_repository++ indexed = tmp_path / "indexed"+ indexed.mkdir()+ asyncio.run(_build_index(indexed))++ async def check():+ engine = create_engine(f"sqlite+aiosqlite:///{indexed}/.repowise/wiki.db")+ try:+ async with get_session(create_session_factory(engine)) as session:+ await upsert_repository(session, name="other", local_path=str(tmp_path / "other"))+ await session.commit()+ finally:+ await engine.dispose()+ # An exact match still wins in a multi-repository local store.+ async with repo_index_session(indexed) as opened:+ assert opened is not None+ moved = tmp_path / "moved"+ indexed.rename(moved)+ async with repo_index_session(moved) as opened:+ assert opened is None++ asyncio.run(check())