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
"""``repowise status`` must not present a broken index as healthy (issue #1748).
In the reported state every obvious signal was green: ``indexed: true``, a correct
``last_sync_commit``, and ``health.file_count`` of 2,251 — while only 9 files
resolved through the repository identity ingestion uses. The repository row itself
resolved correctly (that is how ``status`` printed those numbers), so a row-exists
check cannot catch it; what catches it is comparing the index's file rows against
the checkout they should describe.
These tests build real stores. An earlier version wrote a zero-byte ``wiki.db``,
which is not a valid SQLite file, so ``_mapping_report`` returned through its own
``except`` without ever running the query and the test passed without covering the
path it named.
"""
from __future__ import annotations
import asyncio
import subprocess
from pathlib import Path
from repowise.cli.commands import status_cmd
def _seed(repo: Path, *, file_nodes: int, repository_row: bool = True) -> None:
"""A real store at *repo* holding *file_nodes* file rows.
``repository_row=False`` writes the file rows under a *different* repository
whose ``local_path`` does not match the checkout, which is the shape the
reported failure produces: the index holds data, and none of it resolves.
"""
from repowise.core.persistence import (
create_engine,
create_session_factory,
get_session,
init_db,
upsert_repository,
)
from repowise.core.persistence.models import GraphNode, _new_uuid
db_path = repo / ".repowise" / "wiki.db"
db_path.parent.mkdir(parents=True, exist_ok=True)
url = f"sqlite+aiosqlite:///{db_path}"
async def go() -> None:
engine = create_engine(url)
await init_db(engine)
sf = create_session_factory(engine)
async with get_session(sf) as session:
name = repo.name if repository_row else "some-other-checkout"
local = str(repo.resolve()) if repository_row else "/elsewhere/entirely"
row = await upsert_repository(session, name=name, local_path=local)
for i in range(file_nodes):
session.add(
GraphNode(
id=_new_uuid(),
repository_id=row.id,
node_id=f"src/mod_{i}.py",
node_type="file",
)
)
await engine.dispose()
asyncio.run(go())
def _checkout(tmp_path: Path, files: int) -> Path:
"""A checkout with *files* documentable files."""
repo = tmp_path / "repo"
(repo / "src").mkdir(parents=True)
for i in range(files):
(repo / "src" / f"mod_{i}.py").write_text("x = 1\n", encoding="utf-8")
return repo
def _git_checkout(tmp_path: Path, files: int) -> Path:
"""The same checkout, as a git repository with everything staged."""
repo = _checkout(tmp_path, files)
subprocess.run(["git", "init", "-q"], cwd=repo, check=True)
subprocess.run(["git", "add", "-A"], cwd=repo, check=True)
return repo
def test_an_unindexed_directory_is_not_a_broken_mapping(tmp_path: Path) -> None:
"""The default this replaces was right, and stays: nothing to diverge from."""
report = status_cmd._mapping_report(tmp_path)
assert report["mapping_valid"] is True
assert report["reason"] is None
def test_a_store_with_no_database_is_invalid(tmp_path: Path) -> None:
"""``.repowise/`` exists but holds no ``wiki.db``: a partial or stale init.
``status_command`` classifies the checkout as indexed on the directory's
existence alone, so this state has to be refused here or the healthy
reading carries through to both the table and the JSON.
"""
repo = _checkout(tmp_path, 3)
(repo / ".repowise").mkdir()
report = status_cmd._mapping_report(repo)
assert report["mapping_valid"] is False
assert report["reason"] == "index database is missing"
def test_a_store_with_no_repository_row_is_invalid(tmp_path: Path) -> None:
"""``.repowise/`` exists but no row resolves the checkout."""
repo = _checkout(tmp_path, 3)
_seed(repo, file_nodes=0, repository_row=False)
report = status_cmd._mapping_report(repo)
assert report["mapping_valid"] is False
assert "no repository row" in report["reason"]
def test_a_far_smaller_index_than_the_checkout_is_invalid(tmp_path: Path) -> None:
"""The reported failure: 9 file rows against a working tree of 2,251.
This is the case a row-exists check cannot see, because the row resolves.
"""
repo = _checkout(tmp_path, 40)
_seed(repo, file_nodes=2)
report = status_cmd._mapping_report(repo)
assert report["mapping_valid"] is False
assert report["indexed_files"] == 2
assert report["working_tree_files"] == 40
assert "resolve" in report["reason"]
def test_a_far_smaller_index_than_a_git_checkout_is_invalid(tmp_path: Path) -> None:
"""The reported case stays caught when the count comes from git's listing."""
repo = _git_checkout(tmp_path, 40)
_seed(repo, file_nodes=2)
report = status_cmd._mapping_report(repo)
assert report["mapping_valid"] is False
assert report["indexed_files"] == 2
assert report["working_tree_files"] == 40
assert "resolve" in report["reason"]
def test_the_count_comes_from_git_without_walking_the_tree(tmp_path: Path, monkeypatch) -> None:
"""A git checkout is counted from its listing, never by a walk.
The walk reads every file for its generated and size checks (Raghav
measured 35s on this repo), and it ran on every ``status`` call. The
listing is path-shape only, which is all the fourfold comparison needs.
The asset folder here is the discriminating half: a filter-free count
would read 52 against an index of 12 and report a healthy repo as broken.
"""
from repowise.core.ingestion.traverser import FileTraverser
calls: list[int] = []
def _record_a_walk(_self):
calls.append(1)
return iter(())
repo = _git_checkout(tmp_path, 12)
_seed(repo, file_nodes=12)
assets = repo / "assets"
assets.mkdir()
for i in range(40):
(assets / f"icon_{i}.png").write_text("PNGDATA", encoding="utf-8")
subprocess.run(["git", "add", "-A"], cwd=repo, check=True)
monkeypatch.setattr(FileTraverser, "traverse", _record_a_walk)
report = status_cmd._mapping_report(repo)
assert report["working_tree_files"] == 12
assert report["mapping_valid"] is True
assert calls == [], "the working tree was walked on a git checkout"
def test_the_walk_answers_when_git_cannot_list_the_checkout(tmp_path: Path, monkeypatch) -> None:
"""No listing (no git, or not a repository): the traverser still answers."""
import repowise.core.analysis.git_cli as git_cli
repo = _checkout(tmp_path, 7)
_seed(repo, file_nodes=7)
monkeypatch.setattr(git_cli, "_git", lambda *args, **kwargs: "")
report = status_cmd._mapping_report(repo)
assert report["working_tree_files"] == 7
assert report["mapping_valid"] is True
def test_a_matching_index_is_valid(tmp_path: Path) -> None:
"""The normal case: the counts agree, so nothing is reported."""
repo = _checkout(tmp_path, 12)
_seed(repo, file_nodes=12)
report = status_cmd._mapping_report(repo)
assert report["mapping_valid"] is True
assert report["reason"] is None
assert report["indexed_files"] == 12
assert report["working_tree_files"] == 12
def test_a_slightly_behind_index_is_still_valid(tmp_path: Path) -> None:
"""A lagging index is normal and must not be reported as broken.
The ratio is deliberately loose for this reason: an index one edit behind is
the ordinary state of a working repository.
"""
repo = _checkout(tmp_path, 20)
_seed(repo, file_nodes=19)
assert status_cmd._mapping_report(repo)["mapping_valid"] is True
def test_assets_beside_a_fully_indexed_tree_are_still_valid(tmp_path: Path) -> None:
"""The count must be the ingestion set, not every path the walk yields.
``_walk()`` yields images, fonts and lockfiles; ``traverse()`` drops them in
``_build_file_info``, so only the second answers "what can be indexed". With
the walk count, a frontend with an assets folder trips ``indexed * 4 < tree``
and tells the user to re-run ``init`` over a healthy index, which is #1748
pointed the other way.
"""
repo = _checkout(tmp_path, 12)
_seed(repo, file_nodes=12)
assets = repo / "assets"
assets.mkdir()
for i in range(40):
(assets / f"icon_{i}.png").write_text("PNGDATA", encoding="utf-8")
report = status_cmd._mapping_report(repo)
assert report["working_tree_files"] == 12
assert report["mapping_valid"] is True
assert report["reason"] is None
def test_the_single_repo_json_carries_the_preflight(tmp_path: Path, monkeypatch) -> None:
"""#1748 asks for a machine-readable check an automation can run first."""
from click.testing import CliRunner
from repowise.cli.main import cli
repo = _checkout(tmp_path, 40)
_seed(repo, file_nodes=2)
(repo / ".repowise" / "state.json").write_text("{}", encoding="utf-8")
result = CliRunner().invoke(cli, ["status", str(repo), "--format", "json"])
assert result.exit_code == 0, result.output
payload = __import__("json").loads(result.output)
assert payload["mapping_valid"] is False
assert payload["mapping"]["indexed_files"] == 2
assert payload["mapping"]["working_tree_files"] == 40