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(workspace): filtered diagnostics reason counts and list counts like status (#3984)
Raghav Chamadiyac1bfb5a871f4
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.py b/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.pyindex f3ff565dc..466caf87a 100644--- a/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.py+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.py@@ -2,6 +2,7 @@from __future__ import annotations+from collections import Counterfrom typing import TYPE_CHECKINGimport click@@ -64,7 +65,7 @@ def workspace_diagnostics(_print_breakdown_table(ws_root.name, breakdown)_print_link_totals(diag)_print_extraction_coverage(diag)- _print_unmatched(unmatched, diag.unmatched_by_reason)+ _print_unmatched(unmatched)_print_orphans(orphans)if not unmatched and not orphans:@@ -183,10 +184,14 @@ _REASON_LABELS = {}-def _print_unmatched(unmatched: list[UnmatchedConsumer], by_reason: dict[str, int]) -> None:- """Unmatched consumers grouped by reason."""+def _print_unmatched(unmatched: list[UnmatchedConsumer]) -> None:+ """Unmatched consumers grouped by reason.++ Counts come from the (possibly filtered) list, so they agree with the total.+ """if not unmatched:return+ by_reason = Counter(u.reason for u in unmatched)console.print(f"\n [bold]{len(unmatched)}[/bold] unmatched consumer(s):")for reason, count in sorted(by_reason.items()):label = _REASON_LABELS.get(reason, reason)diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd/group.py b/packages/cli/src/repowise/cli/commands/workspace_cmd/group.pyindex 63e5f3e1f..d56bc5b2d 100644--- a/packages/cli/src/repowise/cli/commands/workspace_cmd/group.py+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd/group.py@@ -2,14 +2,14 @@from __future__ import annotations-from datetime import UTCfrom pathlib import Pathimport clickfrom rich.table import Tablefrom repowise.cli._setup import configure_cli_logging-from repowise.cli.helpers import console, resolve_repo_path, run_async+from repowise.cli.commands.status_cmd import _format_relative_time, _query_repo_counts+from repowise.cli.helpers import console, resolve_repo_pathfrom ._index import _resolve_docs_flag, _run_index_for_repofrom ._shared import _require_workspace@@ -101,86 +101,6 @@ def workspace_list(path: str | None) -> None:console.print(summary)-def _query_repo_counts(repo_path: Path) -> tuple[int, int]:- """Return ``(file_count, symbol_count)`` from a repo's DB, or ``(0, 0)``."""- from repowise.cli.helpers import get_db_url_for_repo, get_repowise_dir-- db_path = get_repowise_dir(repo_path) / "wiki.db"- if not db_path.exists():- return 0, 0-- async def _query() -> tuple[int, int]:- 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)- engine = create_engine(url)- sf = create_session_factory(engine)- try:- async with get_session(sf) as session:- repo_result = await session.execute(- sa_select(Repository.id).where(Repository.local_path == str(repo_path))- )- repo_id = repo_result.scalar_one_or_none()- if repo_id is None:- return 0, 0- file_result = await session.execute(- sa_select(sa_func.count())- .select_from(GraphNode)- .where(- GraphNode.repository_id == repo_id,- GraphNode.node_type == "file",- )- )- symbol_result = await session.execute(- sa_select(sa_func.count())- .select_from(GraphNode)- .where(- GraphNode.repository_id == repo_id,- GraphNode.node_type == "symbol",- )- )- return file_result.scalar_one(), symbol_result.scalar_one()- finally:- await engine.dispose()-- try:- return run_async(_query())- except Exception:- return 0, 0---def _format_relative_time(iso_timestamp: str | None) -> str:- """Format an ISO 8601 timestamp as a human-readable relative string."""- if not iso_timestamp:- return "-"- try:- from datetime import datetime-- dt = datetime.fromisoformat(iso_timestamp)- if dt.tzinfo is None:- dt = dt.replace(tzinfo=UTC)- now = datetime.now(UTC)- delta = now - dt- seconds = int(delta.total_seconds())- if seconds < 60:- return f"{seconds}s ago"- if seconds < 3600:- return f"{seconds // 60}m ago"- if seconds < 86400:- return f"{seconds // 3600}h ago"- return f"{seconds // 86400}d ago"- except Exception:- return iso_timestamp[:10] if len(iso_timestamp) >= 10 else iso_timestamp--# ---------------------------------------------------------------------------# workspace add# ---------------------------------------------------------------------------diff --git a/tests/unit/cli/test_workspace_cmd.py b/tests/unit/cli/test_workspace_cmd.pyindex ac795166c..3f8f8c610 100644--- a/tests/unit/cli/test_workspace_cmd.py+++ b/tests/unit/cli/test_workspace_cmd.py@@ -87,6 +87,25 @@ class TestWorkspaceList:# Summary line: "X/Y repos indexed"assert "repos indexed" in result.output+ def test_list_counts_from_configured_db_url(self, runner, tmp_path, monkeypatch):+ # A configured DB URL with no local wiki.db still has counts to show.+ from repowise.cli.commands import status_cmd++ repo = tmp_path / "svc"+ (repo / ".repowise").mkdir(parents=True)+ _write_workspace_config(tmp_path, repos=[{"path": "svc", "alias": "svc"}])+ monkeypatch.setenv("REPOWISE_DB_URL", f"sqlite+aiosqlite:///{tmp_path / 'shared.db'}")++ def _fake_run_async(coro):+ coro.close()+ return 7, 4321++ monkeypatch.setattr(status_cmd, "run_async", _fake_run_async)++ result = runner.invoke(cli, ["workspace", "list", str(tmp_path)])+ assert result.exit_code == 0, result.output+ assert "4,321" in result.output+def test_list_marks_primary_repo(self, runner, tmp_path):repo_a = tmp_path / "main-svc"repo_a.mkdir()@@ -636,6 +655,27 @@ class TestWorkspaceDiagnosticsReport:assert data["http_consumer_coverage"] == 0.75assert data["generated_at"] == "not-a-date"+ def test_repo_filter_text_reason_counts(self, runner, tmp_path):+ from repowise.core.workspace.diagnostics import UnmatchedConsumer+ from repowise.core.workspace.system_graph import load_system_graph, save_system_graph++ self._save(tmp_path)+ graph = load_system_graph(tmp_path)+ diag = graph.diagnostics+ diag.unmatched_consumers.append(+ UnmatchedConsumer("api", "c.py", "http::GET::/z", "http", "internal_only")+ )+ diag.unmatched_by_reason["internal_only"] = 1+ save_system_graph(graph, tmp_path)++ result = runner.invoke(+ cli, ["workspace", "diagnostics", str(tmp_path), "--repo", "web"]+ )+ assert result.exit_code == 0, result.output+ assert "2 unmatched consumer(s)" in result.output+ # Reason counts follow the filtered list, not the workspace roll-up.+ assert "intra-service" not in result.output+# ---------------------------------------------------------------------------# workspace check