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(status): surface a broken repository/path mapping as invalid (#1812)

Nehal Kb0823812c90b
diff --git a/packages/cli/src/repowise/cli/commands/status_cmd.py b/packages/cli/src/repowise/cli/commands/status_cmd.py
index ddd222c2e..bd3a7d254 100644
--- a/packages/cli/src/repowise/cli/commands/status_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/status_cmd.py
@@ -3,8 +3,10 @@
from __future__ import annotations
import contextlib
+import subprocess
from datetime import UTC
from pathlib import Path
+from typing import Any
import click
from rich.table import Table
@@ -103,6 +105,182 @@ def _query_repo_counts(repo_path: Path) -> tuple[int, int]:
return 0, 0
+def _working_tree_file_count(repo_path: Path) -> int:
+ """Documentable files in the checkout, without reading them.
+
+ The count exists to catch an index that resolves almost none of the
+ checkout (#1748's repro was 9 against 2,251), so only its order of
+ magnitude matters. ``is_candidate_source_path`` applies the same path-shape
+ filter the change sources use, and ``git ls-files`` lists the paths in one
+ call. The traverser is exact but reads every file for its generated and
+ size checks, which is tens of seconds on a large checkout, so it answers
+ only when git cannot list the directory.
+ """
+ try:
+ from repowise.core.analysis.git_cli import _git
+ from repowise.core.ingestion import is_candidate_source_path
+
+ listing = _git(
+ ["ls-files", "-z", "--cached", "--others", "--exclude-standard"],
+ str(repo_path),
+ check=False,
+ )
+ paths = [p for p in listing.split("\0") if p]
+ if paths:
+ return sum(1 for p in paths if is_candidate_source_path(p))
+ except (OSError, subprocess.SubprocessError):
+ pass
+
+ from repowise.core.ingestion.traverser import FileTraverser
+
+ return sum(1 for _ in FileTraverser(repo_path).traverse())
+
+
+def _mapping_report(repo_path: Path) -> dict[str, Any]:
+ """Compare the index's file rows against the checkout they should describe.
+
+ The row-exists check this replaces did not catch #1748. In their repro the
+ ``Repository`` row resolved correctly — that is the same lookup
+ :func:`_query_page_count` goes through, and it is how ``status`` managed to
+ print ``indexed: true`` with a correct ``last_sync_commit`` at all. The
+ divergence was one level down, between the repository row and the file rows
+ hanging off it: 9 files resolved through the identity ingestion uses, against
+ a working tree of 2,251. So the cheap check that actually fires is the
+ comparison of the two counts, which is what this returns.
+
+ Keys, per the fields #1748 asks for:
+ ``indexed_files`` file rows for this repository id
+ ``working_tree_files`` documentable files the checkout holds now
+ (from git's listing; the traverser answers when git cannot)
+ ``mapping_valid`` False when the index cannot describe this checkout
+ ``reason`` why, for the JSON consumer and the table's status column
+ """
+
+ async def _query() -> dict[str, Any]:
+ from sqlalchemy import func as sa_func
+ from sqlalchemy import select as sa_select
+
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ )
+ from repowise.core.persistence.models import GraphNode, Repository
+
+ url = get_db_url_for_repo(repo_path)
+ await reconcile_schema_best_effort(url)
+ engine = create_engine(url)
+ sf = create_session_factory(engine)
+ try:
+ async with get_session(sf) as session:
+ row = await session.execute(
+ sa_select(Repository.id, Repository.name, Repository.local_path).where(
+ Repository.local_path == str(repo_path)
+ )
+ )
+ found = row.first()
+ if found is None:
+ return {
+ "repository_id": None,
+ "indexed_root": None,
+ "indexed_files": 0,
+ "working_tree_files": None,
+ "mapping_valid": False,
+ "reason": "no repository row resolves this checkout",
+ }
+ repo_id, repo_name, indexed_root = found
+ count = await session.execute(
+ sa_select(sa_func.count())
+ .select_from(GraphNode)
+ .where(GraphNode.repository_id == repo_id, GraphNode.node_type == "file")
+ )
+ return {
+ "repository_id": repo_id,
+ "repository_name": repo_name,
+ "indexed_root": indexed_root,
+ "indexed_files": int(count.scalar_one() or 0),
+ "working_tree_files": None,
+ "mapping_valid": True,
+ "reason": None,
+ }
+ finally:
+ await engine.dispose()
+
+ db_path = get_repowise_dir(repo_path) / "wiki.db"
+ if not db_path.exists() and not db_configured():
+ if get_repowise_dir(repo_path).exists():
+ # A store directory with no database in it is a partial or stale
+ # init. The caller reads ``indexed`` off the directory's existence
+ # alone, so calling the mapping valid here would carry that reading
+ # through as healthy.
+ return {
+ "repository_id": None,
+ "indexed_root": None,
+ "indexed_files": 0,
+ "working_tree_files": None,
+ "mapping_valid": False,
+ "reason": "index database is missing",
+ }
+ # Nothing indexed to diverge from; a checkout with no store at all is
+ # not a broken mapping.
+ return {
+ "repository_id": None,
+ "indexed_root": None,
+ "indexed_files": 0,
+ "working_tree_files": None,
+ "mapping_valid": True,
+ "reason": None,
+ }
+ try:
+ report = run_async(_query())
+ except Exception as exc: # a store that will not open cannot describe the tree
+ return {
+ "repository_id": None,
+ "indexed_root": None,
+ "indexed_files": 0,
+ "working_tree_files": None,
+ "mapping_valid": False,
+ "reason": f"index could not be read: {type(exc).__name__}",
+ }
+
+ # The count that actually catches the reported failure, from git's listing
+ # rather than a walk: the comparison below needs the right order of
+ # magnitude, and the full traversal reads every file for its generated and
+ # size checks, which is tens of seconds on a large checkout and ran on
+ # every ``status`` call. The paths only a content read can classify (a
+ # generated banner) or a ``.repowiseIgnore`` entry can drop sit far inside
+ # the fourfold margin.
+ if report["mapping_valid"]:
+ try:
+ report["working_tree_files"] = _working_tree_file_count(repo_path)
+ except Exception as exc:
+ report["reason"] = f"working tree could not be walked: {type(exc).__name__}"
+ return report
+
+ indexed = report["indexed_files"]
+ tree = report["working_tree_files"] or 0
+ if indexed == 0 and tree == 0:
+ report["mapping_valid"] = True
+ elif indexed == 0:
+ report["mapping_valid"] = False
+ report["reason"] = (
+ f"the index holds no file rows for this repository, but the "
+ f"checkout has {tree:,}"
+ )
+ elif tree and indexed * 4 < tree:
+ # A wide margin on purpose: an index legitimately lags the tree, and
+ # a tight ratio would report every mid-edit tree as broken. #1748's
+ # repro was 9 against 2,251, which is three orders of magnitude, so
+ # anything near parity is deliberately left alone.
+ report["mapping_valid"] = False
+ report["reason"] = (
+ f"only {indexed:,} of {tree:,} files in the checkout resolve "
+ f"through the index's repository identity"
+ )
+
+ return report
+
+
def _query_page_count(repo_path: Path) -> int:
"""Return the number of generated wiki pages for a repo, or 0."""
@@ -505,6 +683,7 @@ def _workspace_rows(target: CommandTarget) -> list[dict]:
"head": None,
"stale": None,
"commits_behind": None,
+ "mapping_valid": None,
}
if not row["indexed"]:
rows.append(row)
@@ -526,6 +705,9 @@ def _workspace_rows(target: CommandTarget) -> list[dict]:
head=current_head,
stale=is_stale,
commits_behind=behind,
+ # False when the index cannot describe this checkout, even though
+ # .repowise/ exists (issue #1748).
+ mapping_valid=_mapping_report(abs_path)["mapping_valid"],
)
rows.append(row)
return rows
@@ -602,7 +784,13 @@ def _workspace_status(target: CommandTarget, fmt: str = "table") -> None:
no_docs.append(row["alias"])
behind = row["commits_behind"]
- if row["stale"] and behind > 0:
+ # Mapping validity is read before the count, because a broken mapping is
+ # what makes the count small: #1748's repo rendered as "[yellow]empty"
+ # on the strength of `files == 0`, which is the presentation the issue
+ # objects to. A false verdict is not a quiet repo.
+ if row.get("mapping_valid") is False:
+ status = "[red]mapping broken[/red]"
+ elif row["stale"] and behind > 0:
status = f"[yellow]{behind} new commit(s)[/yellow]"
total_stale += 1
elif row["stale"]:
@@ -631,8 +819,21 @@ def _workspace_status(target: CommandTarget, fmt: str = "table") -> None:
summary = f"\n {indexed}/{len(rows)} repos indexed. Default: {ws_config.default_repo}"
if total_stale:
summary += f". [yellow]{total_stale} stale[/yellow]"
+ broken = [r for r in rows if r.get("mapping_valid") is False]
+ if broken:
+ summary += f". [red]{len(broken)} with a broken path mapping[/red]"
console.print(summary)
+ # A count that disagrees with the checkout is the cheap preflight #1748 asks
+ # for, and it is invisible in the row above: both numbers look fine on their
+ # own. Print them side by side for anyone who has to act on it.
+ for r in broken:
+ console.print(
+ f" [red]{r['alias']}[/red]: only {r['files']:,} file(s) resolve through "
+ f"the index; re-run [bold]repowise init {r['alias']}[/bold] to rebuild the "
+ "repository identity"
+ )
+
# Honest "no docs" tip — print the exact remediation command so the
# user never has to dig through docs to figure out what to do next.
if no_docs:
@@ -713,9 +914,16 @@ def status_command(path: str | None, workspace: bool, no_workspace: bool, fmt: s
counts, total_db_tokens = (
run_async(_query_pages(repo_path)) if has_db else ({}, 0)
)
+ mapping = _mapping_report(repo_path)
emit_json(
{
"repo": str(repo_path),
+ # The preflight #1748 asks for: a machine consumer can read this
+ # before paying for a coverage job, which today it cannot,
+ # because every other field here reads healthy in the broken
+ # state.
+ "mapping_valid": mapping["mapping_valid"],
+ "mapping": mapping,
"indexed": True,
"incomplete": incomplete,
"state": {
@@ -742,6 +950,16 @@ def status_command(path: str | None, workspace: bool, no_workspace: bool, fmt: s
)
return
+ mapping = _mapping_report(repo_path)
+ if mapping["mapping_valid"] is False:
+ # Printed before the state table: in the broken state every field in that
+ # table reads correct, so a reader who sees it first has already been
+ # told the index is fine.
+ notices.print(
+ f"[red]Path mapping broken:[/red] {mapping['reason']}. "
+ "Run [bold]repowise init[/bold] to rebuild the repository identity."
+ )
+
# The page query runs first so the state table can show its totals, but
# its error is held until the state table is printed: on a wiki.db whose
# schema predates the current models it raises, and a reader should still
diff --git a/tests/unit/cli/test_status_mapping.py b/tests/unit/cli/test_status_mapping.py
new file mode 100644
index 000000000..fa7122ccd
--- /dev/null
+++ b/tests/unit/cli/test_status_mapping.py
@@ -0,0 +1,251 @@
+"""``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