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): let delete use a configured database (#2338)
Nehal kanak kuniyil thottathilceebf73b51c9
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex bde152f1f..c60300910 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1796,16 +1796,23 @@ repowise whoamiDelete a repository's index and all stored intelligence (wiki, graph, embeddings,git metadata). Does **not** touch your source files. Prompts for confirmation-unless `--force` is passed.+unless `--force` is passed. The index may live in a shared database configured+with `REPOWISE_DB_URL`; no repository-local `.repowise/wiki.db` is required.| Flag | Description ||------|-------------|| `--force` / `-f` | Skip the confirmation prompt || `--path` / `-p` | Path to the repository directory |+With `--path`, the repository whose stored `local_path` matches that path is+selected, so a shared `REPOWISE_DB_URL` (PostgreSQL) database does not prompt+for a numbered choice. Without `--path` the command lists every repository in+the database and prompts.+```bashrepowise delete # delete the current repo's index (prompts)repowise delete <repo-id> --force # delete a specific repo's index, no prompt+repowise delete --path /workspace/api -f # delete the repo indexed at that path```---diff --git a/packages/cli/src/repowise/cli/commands/delete_cmd.py b/packages/cli/src/repowise/cli/commands/delete_cmd.pyindex ae065a370..5a2eaa415 100644--- a/packages/cli/src/repowise/cli/commands/delete_cmd.py+++ b/packages/cli/src/repowise/cli/commands/delete_cmd.py@@ -2,11 +2,14 @@from __future__ import annotations+from pathlib import Path+import clickfrom rich.table import Tablefrom repowise.cli.helpers import (console,+ db_configured,get_db_url_for_repo,get_repowise_dir,resolve_repo_path,@@ -14,23 +17,53 @@ from repowise.cli.helpers import ()+def _same_local_path(stored: str | None, repo_path: Path) -> bool:+ """True when *stored* (a ``Repository.local_path``) names *repo_path*.++ Rows are written from a resolved absolute path, but a caller may reach the+ same repository through a symlink or a relative argument, so both sides are+ resolved before comparing. A path that no longer exists still compares by+ string rather than raising.+ """+ if not stored:+ return False+ try:+ return Path(stored).resolve() == repo_path+ except OSError:+ return stored == str(repo_path)++@click.command("delete")@click.argument("repo_id", required=False, default=None)@click.option("--force", "-f", is_flag=True, default=False, help="Skip confirmation prompt.")[email protected]("--path", "-p", default=None, help="Path to the repository directory.")[email protected]("--path", "-p", default=None, help="Path to the repository to delete.")def delete_command(repo_id: str | None, force: bool, path: str | None) -> None:- """Delete a repository and all its generated data."""+ """Delete a repository and all its generated data.++ ``--path`` (or the current directory) names the repository to delete: the+ row whose ``local_path`` matches it is selected. The path is only a+ database-location hint when nothing matches and no path was given, in which+ case every known repository is listed for a numbered selection.+ """repo_path = resolve_repo_path(path)repowise_dir = get_repowise_dir(repo_path)- if not repowise_dir.exists():- console.print("[yellow]No .repowise/ directory found. Run 'repowise init' first.[/yellow]")- return+ # These two checks describe the repo-local SQLite default, and only it. A+ # shared store (REPOWISE_DB_URL pointing at PostgreSQL) holds this+ # repository's index somewhere the repo has no file for, so demanding+ # .repowise/wiki.db here refused to delete a repository the configured+ # database knows about. With no configured URL the messages are unchanged.+ if not db_configured():+ if not repowise_dir.exists():+ console.print(+ "[yellow]No .repowise/ directory found. Run 'repowise init' first.[/yellow]"+ )+ return- db_path = repowise_dir / "wiki.db"- if not db_path.exists():- console.print("[yellow]Database not found.[/yellow]")- return+ db_path = repowise_dir / "wiki.db"+ if not db_path.exists():+ console.print("[yellow]Database not found.[/yellow]")+ returnasync def _run() -> None:from sqlalchemy import func, select@@ -70,8 +103,23 @@ def delete_command(repo_id: str | None, force: bool, path: str | None) -> None:await engine.dispose()return- # If no repo_id given, let the user pick+ # Find the target repo infotarget_id = repo_id+ if target_id is None and path is not None:+ # --path names a repository, so it selects that repository. The+ # numbered list stays for the no-path case only; offering to delete+ # some other row after the user named a path is how the wrong+ # repository gets removed from a shared database.+ match = next((r for r in repos if _same_local_path(r[2], repo_path)), None)+ if match is None:+ console.print(+ f"[yellow]No repository in the database matches {repo_path}.[/yellow]"+ )+ await engine.dispose()+ return+ target_id = match[0]++ # If no repo_id given, let the user pickif target_id is None:table = Table(title="Repositories")table.add_column("#", style="cyan", justify="right")diff --git a/tests/integration/test_cli.py b/tests/integration/test_cli.pyindex df6548d26..f4a712a3d 100644--- a/tests/integration/test_cli.py+++ b/tests/integration/test_cli.py@@ -487,6 +487,209 @@ class TestStatusDoctorWithEnvDb:assert "wiki.db not found" not in result.output+class TestDeleteWithConfiguredDb:+ """Regression guard for #2320: ``repowise delete`` must reach the configured+ database, and ``--path`` must select the repository at that path.++ The command checked for a repo-local ``.repowise/wiki.db`` before it+ resolved the configured URL, so a repository indexed into a shared+ PostgreSQL store (which has no local file at all) could not be deleted.+ """++ @pytest.fixture+ def shared_db(self, tmp_path, monkeypatch):+ """An external DB holding one indexed repo that has no local store.++ ``REPOWISE_DB_URL`` points outside the repo, the way a PostgreSQL+ container does. Nothing in the repo is created: the whole scenario is+ "the rows live in the shared database, the checkout has no wiki.db".+ """+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_page,+ upsert_repository,+ )++ repo_path = tmp_path / "example-repository"+ repo_path.mkdir()+ db_path = tmp_path / "shared" / "wiki.db"+ db_path.parent.mkdir()+ url = f"sqlite+aiosqlite:///{db_path}"+ monkeypatch.setenv("REPOWISE_DB_URL", url)++ async def seed(*, pages: int = 1) -> str:+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ repo = await upsert_repository(+ session, name=repo_path.name, local_path=str(repo_path.resolve())+ )+ for i in range(pages):+ await upsert_page(+ session,+ page_id=f"file_page:src/module_{i}.py",+ repository_id=repo.id,+ page_type="file_page",+ title=f"module_{i}.py",+ content=f"# module {i}\n\nBody text for module {i}.",+ target_path=f"src/module_{i}.py",+ source_hash=f"hash-{i}",+ model_name="mock",+ provider_name="mock",+ )+ await engine.dispose()+ return repo.id++ return {"repo_path": repo_path, "db_path": db_path, "seed": seed}++ def test_deletes_from_configured_db_without_local_wiki_db(self, runner, shared_db, monkeypatch):+ """The reported bug: no ``.repowise/`` at all, rows in the shared DB."""+ import asyncio++ repo_path = shared_db["repo_path"]+ repo_id = asyncio.run(shared_db["seed"]())+ assert not (repo_path / ".repowise").exists()++ result = runner.invoke(+ cli,+ ["delete", "--path", str(repo_path), "--force"],+ catch_exceptions=False,+ )++ assert result.exit_code == 0, result.output+ assert "Database not found" not in result.output+ assert "No .repowise/ directory found" not in result.output+ assert "Deleted" in result.output+ # The rows really went: the repository is gone from the shared store.+ assert _db_scalar(shared_db["db_path"], "SELECT COUNT(*) FROM repositories") == 0+ assert _db_scalar(shared_db["db_path"], "SELECT COUNT(*) FROM wiki_pages") == 0+ assert repo_id # the seed returned a real primary key++ def test_path_selects_the_matching_repo_instead_of_prompting(self, runner, shared_db, tmp_path):+ """``--path`` names the repository; a second row must not be offered.++ The command listed every repository and prompted for a number even+ when a path was supplied, so in a shared database the deletion target+ came from the prompt rather than from the argument.+ """+ import asyncio++ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ upsert_repository,+ )++ repo_path = shared_db["repo_path"]+ asyncio.run(shared_db["seed"]())+ other_path = tmp_path / "other-repository"+ other_path.mkdir()++ async def add_other() -> None:+ engine = create_engine(f"sqlite+aiosqlite:///{shared_db['db_path']}")+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ await upsert_repository(+ session, name=other_path.name, local_path=str(other_path.resolve())+ )+ await engine.dispose()++ asyncio.run(add_other())++ result = runner.invoke(+ cli,+ ["delete", "--path", str(repo_path), "--force"],+ catch_exceptions=False,+ )++ assert result.exit_code == 0, result.output+ assert "Deleted" in result.output+ assert "Enter number to delete" not in result.output+ remaining = _db_column(shared_db["db_path"], "SELECT local_path FROM repositories")+ assert remaining == [str(other_path.resolve())]++ def test_path_with_no_matching_row_does_not_delete_anything(self, runner, shared_db, tmp_path):+ """A path the database does not know must not fall back to the prompt."""+ import asyncio++ asyncio.run(shared_db["seed"]())+ unknown = tmp_path / "never-indexed"+ unknown.mkdir()++ result = runner.invoke(+ cli,+ ["delete", "--path", str(unknown), "--force"],+ catch_exceptions=False,+ )++ assert result.exit_code == 0, result.output+ assert f"No repository in the database matches {unknown.resolve()}" in result.output+ assert "Deleted" not in result.output+ assert _db_scalar(shared_db["db_path"], "SELECT COUNT(*) FROM repositories") == 1++ def test_local_sqlite_missing_messages_are_unchanged(+ self, runner, tmp_path, sample_repo_path, monkeypatch+ ):+ """With no configured URL the pre-existing messages still fire."""+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)+ dest = tmp_path / "repo"+ shutil.copytree(sample_repo_path, dest)++ result = runner.invoke(cli, ["delete", "--path", str(dest), "--force"])+ assert result.exit_code == 0, result.output+ assert "No .repowise/ directory found. Run 'repowise init' first." in result.output++ (dest / ".repowise").mkdir()+ result = runner.invoke(cli, ["delete", "--path", str(dest), "--force"])+ assert result.exit_code == 0, result.output+ assert "Database not found." in result.output++ def test_deletes_from_local_wiki_db_when_configured(+ self, runner, tmp_path, sample_repo_path, monkeypatch+ ):+ """The SQLite path still works: local wiki.db, no configured URL."""+ import asyncio++ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_repository,+ )++ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)+ dest = tmp_path / "repo"+ shutil.copytree(sample_repo_path, dest)+ db_path = dest / ".repowise" / "wiki.db"+ db_path.parent.mkdir()+ url = f"sqlite+aiosqlite:///{db_path}"++ async def seed() -> None:+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ await upsert_repository(session, name="repo", local_path=str(dest.resolve()))+ await engine.dispose()++ asyncio.run(seed())++ result = runner.invoke(+ cli, ["delete", "--path", str(dest), "--force"], catch_exceptions=False+ )+ assert result.exit_code == 0, result.output+ assert "Deleted" in result.output+ assert _db_scalar(db_path, "SELECT COUNT(*) FROM repositories") == 0++class TestSearchFulltext:def test_returns_results_or_no_error(self, runner, work_repo):runner.invoke(diff --git a/tests/integration/test_delete_cmd_postgres.py b/tests/integration/test_delete_cmd_postgres.pynew file mode 100644index 000000000..c9c8ad55e--- /dev/null+++ b/tests/integration/test_delete_cmd_postgres.py@@ -0,0 +1,149 @@+"""``repowise delete`` against a real PostgreSQL store (issue #2320).++The bug: the command demanded a repository-local ``.repowise/wiki.db`` before it+resolved the configured database URL, so a repository whose index lives in a+shared PostgreSQL database (and which therefore has no local file at all) could+not be deleted.++``tests/integration/test_cli.py::TestDeleteWithConfiguredDb`` covers the same+code path against an external SQLite store, which is what the default test run+exercises. This file repeats the scenario on the dialect from the report, where+the FTS sweep is a no-op and the child rows go with the server's cascade.++Skipped unless a PostgreSQL URL is configured, so a local ``pytest`` run is+unchanged::++ REPOWISE_TEST_PG_URL=postgresql+asyncpg://user@localhost:5432/repowise_test \\+ uv run pytest tests/integration/test_delete_cmd_postgres.py+"""++from __future__ import annotations++import asyncio+import os++import pytest+from click.testing import CliRunner+from sqlalchemy import text+from sqlalchemy.ext.asyncio import create_async_engine++from repowise.cli.main import cli+from repowise.core.persistence.database import init_db+from repowise.core.persistence.models import Base++PG_URL = os.environ.get("REPOWISE_TEST_PG_URL")++pytestmark = pytest.mark.skipif(+ not PG_URL, reason="REPOWISE_TEST_PG_URL not set — PostgreSQL-only regression"+)+++def _seed(url: str, repo_path) -> None:+ """One repository at *repo_path*, with its own two pages."""+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ upsert_page,+ upsert_repository,+ )++ async def run() -> None:+ engine = create_engine(url)+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ repo = await upsert_repository(+ session, name=repo_path.name, local_path=str(repo_path.resolve())+ )+ for i in range(2):+ await upsert_page(+ session,+ # Scoped by repo so two seeded repositories cannot share a+ # primary key and reassign each other's rows.+ page_id=f"file_page:{repo_path.name}/module_{i}.py",+ repository_id=repo.id,+ page_type="file_page",+ title=f"module_{i}.py",+ content=f"# module {i}\n\nBody text for module {i}.",+ target_path=f"src/module_{i}.py",+ source_hash=f"hash-{i}",+ model_name="mock",+ provider_name="mock",+ )+ await engine.dispose()++ asyncio.run(run())+++def _scalar(url: str, sql: str) -> int:+ async def run() -> int:+ engine = create_async_engine(url)+ try:+ async with engine.connect() as conn:+ return int((await conn.execute(text(sql))).scalar() or 0)+ finally:+ await engine.dispose()++ return asyncio.run(run())+++def pg_url(tmp_path, monkeypatch) -> str:+ """A scratch PostgreSQL database, exposed as ``REPOWISE_DB_URL``.++ The fixture drops every table, so it refuses a database that is not named+ like a scratch one. Pointing the env var at a real index and losing it+ should take more than a typo.+ """+ database = (PG_URL or "").rsplit("/", 1)[-1].split("?")[0]+ if "test" not in database and "scratch" not in database:+ pytest.skip(f"refusing to drop tables in {database!r}: name it *test* or *scratch*")++ async def reset() -> None:+ engine = create_async_engine(PG_URL or "")+ async with engine.begin() as conn:+ await conn.run_sync(Base.metadata.drop_all)+ await init_db(engine)+ await engine.dispose()++ asyncio.run(reset())+ monkeypatch.setenv("REPOWISE_DB_URL", PG_URL or "")+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)+ return PG_URL or ""+++def test_delete_reaches_the_configured_postgres_store(pg_url, tmp_path):+ """No ``.repowise/`` anywhere; ``--path`` alone is enough to delete the repo."""+ repo_path = tmp_path / "example-repository"+ repo_path.mkdir()+ _seed(pg_url, repo_path)+ assert not (repo_path / ".repowise").exists()++ result = CliRunner().invoke(+ cli, ["delete", "--path", str(repo_path), "--force"], catch_exceptions=False+ )++ assert result.exit_code == 0, result.output+ assert "Database not found" not in result.output+ assert "No .repowise/ directory found" not in result.output+ assert "Deleted" in result.output+ assert _scalar(pg_url, "SELECT count(*) FROM repositories") == 0+ assert _scalar(pg_url, "SELECT count(*) FROM wiki_pages") == 0+++def test_delete_path_leaves_other_repositories_in_place(pg_url, tmp_path):+ """The shared store keeps every row that ``--path`` did not name."""+ doomed = tmp_path / "doomed"+ keeper = tmp_path / "keeper"+ for repo_path in (doomed, keeper):+ repo_path.mkdir()+ _seed(pg_url, repo_path)++ result = CliRunner().invoke(+ cli, ["delete", "--path", str(doomed), "--force"], catch_exceptions=False+ )++ assert result.exit_code == 0, result.output+ assert "Enter number to delete" not in result.output+ assert _scalar(pg_url, "SELECT count(*) FROM repositories") == 1+ assert _scalar(pg_url, "SELECT count(*) FROM wiki_pages") == 2