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): honor repo settings excludes in health sync (#638)
joptimuse5d91e10054c
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis.py b/packages/core/src/repowise/core/persistence/crud/analysis.pyindex 8a55dc232..53e8998e9 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis.py@@ -8,9 +8,10 @@ from __future__ import annotationsimport jsonfrom datetime import datetime+from pathlib import Pathfrom typing import Any-from sqlalchemy import func, or_, select+from sqlalchemy import or_, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.analysis.dead_code.risk_factors import effective_safe_to_delete@@ -22,6 +23,7 @@ from ..models import (HealthFinding,HealthSnapshot,RefactoringSuggestion,+ Repository,_new_uuid,_now_utc,)@@ -420,6 +422,52 @@ async def save_health_metrics(await session.flush()+async def _health_exclude_spec(session: AsyncSession, repository_id: str) -> Any:+ repo = await session.get(Repository, repository_id)+ if repo is None:+ return None++ patterns: list[str] = []+ seen: set[str] = set()++ def _add(values: Any) -> None:+ if not isinstance(values, list):+ return+ for value in values:+ if isinstance(value, str) and value not in seen:+ seen.add(value)+ patterns.append(value)++ try:+ settings = json.loads(getattr(repo, "settings_json", "") or "{}")+ if isinstance(settings, dict):+ _add(settings.get("exclude_patterns"))+ except (TypeError, ValueError):+ pass++ try:+ from repowise.core.repo_config import load_repo_config++ cfg = load_repo_config(Path(repo.local_path))+ if isinstance(cfg, dict):+ _add(cfg.get("exclude_patterns"))+ except Exception:+ pass++ if not patterns:+ return None++ import pathspec++ return pathspec.PathSpec.from_lines("gitwildmatch", patterns)+++def _filter_excluded_paths(rows: list[Any], spec: Any) -> list[Any]:+ if spec is None:+ return rows+ return [row for row in rows if not spec.match_file(getattr(row, "file_path", ""))]++async def get_health_findings(session: AsyncSession,repository_id: str,@@ -458,7 +506,10 @@ async def get_health_findings(q = q.where(HealthFinding.severity.in_(allowed))q = q.order_by(HealthFinding.health_impact.desc())result = await session.execute(q)- return list(result.scalars().all())+ return _filter_excluded_paths(+ list(result.scalars().all()),+ await _health_exclude_spec(session, repository_id),+ )async def get_health_metrics(@@ -472,7 +523,10 @@ async def get_health_metrics(q = q.where(HealthFileMetric.file_path.in_(file_paths))q = q.order_by(HealthFileMetric.score.asc())result = await session.execute(q)- return list(result.scalars().all())+ return _filter_excluded_paths(+ list(result.scalars().all()),+ await _health_exclude_spec(session, repository_id),+ )async def get_health_summary(session: AsyncSession, repository_id: str) -> dict:@@ -541,27 +595,17 @@ async def get_health_summary(session: AsyncSession, repository_id: str) -> dict:worst_performance_path = perf_worst.file_pathworst_performance_score = round(perf_worst.performance_score, 2)- # Open-finding counts split by home dimension (NULL homes under "defect"),- # so each pillar can show its own actionable count.- dim_rows = await session.execute(- select(HealthFinding.dimension, func.count())- .where(- HealthFinding.repository_id == repository_id,- HealthFinding.status == "open",- )- .group_by(HealthFinding.dimension)- )+ findings = await get_health_findings(session, repository_id)by_dim: dict[str, int] = {}- for dim, count in dim_rows.all():- by_dim[dim or "defect"] = by_dim.get(dim or "defect", 0) + int(count)- open_findings = sum(by_dim.values())-+ for finding in findings:+ dim = finding.dimension or "defect"+ by_dim[dim] = by_dim.get(dim, 0) + 1return {"file_count": len(metrics),"average_health": round(avg, 2),"worst_performer_path": worst.file_path,"worst_performer_score": round(worst.score, 2),- "open_findings": open_findings,+ "open_findings": len(findings),"maintainability_average": (round(maintainability_average, 2) if maintainability_average is not None else None),diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex 981a40f0f..be879aae8 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -403,6 +403,7 @@ async def persist_incremental_index(partial_health_report: Any,changed_paths: list[str],*,+ current_graph_file_paths: set[str] | None = None,file_diffs: list[Any] | None = None,log: LogFn | None = None,) -> None:@@ -433,6 +434,16 @@ async def persist_incremental_index(repo = await upsert_repository(session, name=repo_path.name, local_path=str(repo_path))repo_id = repo.id+ if current_graph_file_paths:+ try:+ from repowise.core.pipeline.persist import _prune_stale_file_rows++ await _prune_stale_file_rows(+ session, repo_id, current_graph_file_paths, set()+ )+ except Exception as exc:+ log(f"[yellow]Stale row prune skipped: {exc}[/yellow]")+# Tombstone pages for deleted/renamed files FIRST — a fresh page# for a file that no longer exists misleads every retrieval# consumer until the next full regeneration.diff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.pyindex 077e9b0c1..f09f841dc 100644--- a/packages/core/src/repowise/core/workspace/update.py+++ b/packages/core/src/repowise/core/workspace/update.py@@ -10,12 +10,15 @@ import asyncioimport json as _jsonimport loggingimport os+import sqlite3import subprocessimport time-from dataclasses import dataclass, field-from datetime import datetime, timezone+from collections.abc import Callable+from contextlib import suppress+from dataclasses import dataclass+from datetime import UTC, datetimefrom pathlib import Path-from typing import Any, Callable+from typing import Anyfrom .config import WorkspaceConfig@@ -35,6 +38,32 @@ _LOCK_FILENAME = ".update.lock"_LOCK_STALE_AFTER_SECONDS = 30 * 60+def _merged_repo_excludes(+ repo_path: Path,+ extra_exclude_patterns: list[str] | None = None,+) -> list[str]:+ from ..repo_config import load_repo_config++ patterns: list[str] = list(load_repo_config(repo_path).get("exclude_patterns") or [])+ db_path = repo_path / ".repowise" / "wiki.db"+ if db_path.is_file():+ try:+ with sqlite3.connect(str(db_path)) as conn:+ row = conn.execute("SELECT settings_json FROM repositories LIMIT 1").fetchone()+ if row and row[0]:+ settings = _json.loads(row[0])+ if isinstance(settings, dict):+ for value in settings.get("exclude_patterns") or []:+ if isinstance(value, str) and value not in patterns:+ patterns.append(value)+ except Exception:+ pass+ for pattern in extra_exclude_patterns or []:+ if pattern not in patterns:+ patterns.append(pattern)+ return patterns++def _lock_path(repo_path: Path) -> Path:return repo_path / ".repowise" / _LOCK_FILENAME@@ -98,10 +127,8 @@ def _acquire_lock(repo_path: Path, target_commit: str | None) -> None:def _release_lock(repo_path: Path) -> None:- try:+ with suppress(OSError):_lock_path(repo_path).unlink(missing_ok=True)- except OSError:- pass# ---------------------------------------------------------------------------@@ -295,7 +322,7 @@ async def reconcile_repo_head_commit(repo_path: Path, head: str | None) -> None:if repo is not None:if repo.head_commit != head:repo.head_commit = head- repo.updated_at = datetime.now(timezone.utc)+ repo.updated_at = datetime.now(UTC)await session.flush()finally:await engine.dispose()@@ -335,8 +362,6 @@ async def _incremental_repo_update(run_partial_analysis,)from ..pipeline.phases.git import drop_transient_git_signals- from ..repo_config import load_repo_config-alias = repo_path.namehead = get_head_commit(repo_path) or "HEAD"@@ -360,11 +385,10 @@ async def _incremental_repo_update(# Per-repo config, like the single-repo update path. The workspace-level# ``exclude_patterns`` (when provided) apply on top.+ from ..repo_config import load_repo_config+cfg = load_repo_config(repo_path)- merged_excludes = list(cfg.get("exclude_patterns") or [])- for pattern in exclude_patterns or []:- if pattern not in merged_excludes:- merged_excludes.append(pattern)+ merged_excludes = _merged_repo_excludes(repo_path, exclude_patterns)(parsed_files,@@ -400,6 +424,7 @@ async def _incremental_repo_update(dead_code_report,partial_health_report,[fd.path for fd in file_diffs],+ current_graph_file_paths={pf.file_info.path for pf in parsed_files},log=_log.info,)@@ -440,6 +465,7 @@ async def update_single_repo_index(alias = repo_path.namestate = read_repo_state(repo_path)base_ref = state.get("last_sync_commit")+ merged_excludes = _merged_repo_excludes(repo_path, exclude_patterns)if (base_ref@@ -467,7 +493,7 @@ async def update_single_repo_index(result = await run_pipeline(repo_path,commit_depth=commit_depth,- exclude_patterns=exclude_patterns,+ exclude_patterns=merged_excludes or None,include_submodules=bool(state.get("include_submodules", False)),include_nested_repos=bool(state.get("include_nested_repos", False)),generate_docs=False,@@ -580,9 +606,8 @@ async def update_workspace(except Exception:pass- is_stale, current_head, commits_behind = check_repo_staleness(- abs_path,- stored_commit,+ is_stale, current_head, _commits_behind = check_repo_staleness(+ abs_path, stored_commit,)if not is_stale:@@ -641,10 +666,10 @@ async def update_workspace(elapsed,)# Record pending so the running update can roll forward.- try:- (path / ".repowise" / ".update.pending").write_text(new_head, encoding="utf-8")- except OSError:- pass+ with suppress(OSError):+ (path / ".repowise" / ".update.pending").write_text(+ new_head, encoding="utf-8"+ )return RepoUpdateResult(alias=alias,updated=False,@@ -670,10 +695,8 @@ async def update_workspace(state_path = path / ".repowise" / "state.json"state: dict[str, Any] = {}if state_path.is_file():- try:+ with suppress(Exception):state = _json.loads(state_path.read_text(encoding="utf-8"))- except Exception:- passstate["last_sync_commit"] = new_head# Mark first-time so downstream tooling (status, doctor) can# distinguish a never-indexed repo from one that's been@@ -699,7 +722,7 @@ async def update_workspace(if result.updated:entry = ws_config.get_repo(alias)if entry is not None:- entry.indexed_at = datetime.now(timezone.utc).isoformat()+ entry.indexed_at = datetime.now(UTC).isoformat()entry.last_commit_at_index = new_headif on_repo_done:diff --git a/tests/unit/server/test_health_excludes.py b/tests/unit/server/test_health_excludes.pynew file mode 100644index 000000000..64a8abed5--- /dev/null+++ b/tests/unit/server/test_health_excludes.py@@ -0,0 +1,176 @@+from __future__ import annotations++from repowise.core.persistence.crud import (+ get_health_findings,+ get_health_metrics,+ get_health_summary,+ save_health_findings,+ save_health_metrics,+ upsert_repository,+)+from repowise.core.pipeline.persist import _prune_stale_file_rows+++async def test_health_reads_honor_repo_settings_excludes(session, tmp_path) -> None:+ repo = await upsert_repository(+ session,+ name="repo",+ local_path=str(tmp_path),+ settings={"exclude_patterns": ["tools/"]},+ )++ await save_health_metrics(+ session,+ repo.id,+ [+ {+ "file_path": "tools/gen.py",+ "score": 1.5,+ "max_ccn": 8,+ "max_nesting": 3,+ "nloc": 80,+ "duplication_pct": 0.0,+ "has_test_file": False,+ "line_coverage_pct": 0.0,+ "branch_coverage_pct": 0.0,+ "module": "tools",+ },+ {+ "file_path": "src/app.py",+ "score": 8.5,+ "max_ccn": 2,+ "max_nesting": 1,+ "nloc": 40,+ "duplication_pct": 0.0,+ "has_test_file": True,+ "line_coverage_pct": 90.0,+ "branch_coverage_pct": 80.0,+ "module": "src",+ },+ ],+ )+ await save_health_findings(+ session,+ repo.id,+ [+ {+ "file_path": "tools/gen.py",+ "biomarker_type": "complex_method",+ "severity": "high",+ "function_name": "build",+ "line_start": 1,+ "line_end": 20,+ "details": {},+ "health_impact": 2.5,+ "reason": "generated file finding",+ },+ {+ "file_path": "src/app.py",+ "biomarker_type": "complex_method",+ "severity": "low",+ "function_name": "run",+ "line_start": 1,+ "line_end": 10,+ "details": {},+ "health_impact": 0.5,+ "reason": "real file finding",+ },+ ],+ )++ metrics = await get_health_metrics(session, repo.id)+ findings = await get_health_findings(session, repo.id)+ summary = await get_health_summary(session, repo.id)++ assert [m.file_path for m in metrics] == ["src/app.py"]+ assert [f.file_path for f in findings] == ["src/app.py"]+ assert await get_health_metrics(session, repo.id, file_paths=["tools/gen.py"]) == []+ assert await get_health_findings(session, repo.id, file_path="tools/gen.py") == []+ assert summary == {+ "file_count": 1,+ "average_health": 8.5,+ "worst_performer_path": "src/app.py",+ "worst_performer_score": 8.5,+ "open_findings": 1,+ "maintainability_average": None,+ "performance_average": None,+ "maintainability_findings": 0,+ "performance_findings": 0,+ "worst_performance_path": None,+ "worst_performance_score": None,+ }+++async def test_prune_stale_rows_removes_excluded_health_data(session, tmp_path) -> None:+ repo = await upsert_repository(+ session,+ name="repo",+ local_path=str(tmp_path),+ )++ await save_health_metrics(+ session,+ repo.id,+ [+ {+ "file_path": "tools/gen.py",+ "score": 1.5,+ "max_ccn": 8,+ "max_nesting": 3,+ "nloc": 80,+ "duplication_pct": 0.0,+ "has_test_file": False,+ "line_coverage_pct": 0.0,+ "branch_coverage_pct": 0.0,+ "module": "tools",+ },+ {+ "file_path": "src/app.py",+ "score": 8.5,+ "max_ccn": 2,+ "max_nesting": 1,+ "nloc": 40,+ "duplication_pct": 0.0,+ "has_test_file": True,+ "line_coverage_pct": 90.0,+ "branch_coverage_pct": 80.0,+ "module": "src",+ },+ ],+ )+ await save_health_findings(+ session,+ repo.id,+ [+ {+ "file_path": "tools/gen.py",+ "biomarker_type": "complex_method",+ "severity": "high",+ "function_name": "build",+ "line_start": 1,+ "line_end": 20,+ "details": {},+ "health_impact": 2.5,+ "reason": "generated file finding",+ },+ {+ "file_path": "src/app.py",+ "biomarker_type": "complex_method",+ "severity": "low",+ "function_name": "run",+ "line_start": 1,+ "line_end": 10,+ "details": {},+ "health_impact": 0.5,+ "reason": "real file finding",+ },+ ],+ )++ await _prune_stale_file_rows(session, repo.id, {"src/app.py"}, set())++ metrics = await get_health_metrics(session, repo.id)+ findings = await get_health_findings(session, repo.id)++ assert [m.file_path for m in metrics] == ["src/app.py"]+ assert [f.file_path for f in findings] == ["src/app.py"]diff --git a/tests/unit/workspace/test_incremental_update.py b/tests/unit/workspace/test_incremental_update.pyindex 12e3737c4..5fb9b7135 100644--- a/tests/unit/workspace/test_incremental_update.py+++ b/tests/unit/workspace/test_incremental_update.py@@ -57,6 +57,32 @@ def _mark_indexed(repo: Path, commit: str, **extra_state) -> None:(state_dir / "wiki.db").touch()+def _write_repo_settings(repo: Path, settings: dict) -> None:+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_repository,+ )+ from repowise.core.persistence.database import resolve_db_url++ async def _seed() -> None:+ engine = create_engine(resolve_db_url(repo))+ await init_db(engine)+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ await upsert_repository(+ session,+ name=repo.name,+ local_path=str(repo),+ settings=settings,+ )+ await engine.dispose()++ asyncio.run(_seed())++def _add_commit(repo: Path, filename: str = "b.py") -> str:(repo / filename).write_text("def beta():\n return 2\n")_git(repo, "add", ".")@@ -64,6 +90,11 @@ def _add_commit(repo: Path, filename: str = "b.py") -> str:return _git(repo, "rev-parse", "HEAD")+def _assert_full_pipeline_fallback(result, calls: list[dict]) -> None:+ assert len(calls) == 1+ assert result.updated is True++@pytest.fixturedef forbid_full_pipeline(monkeypatch):"""Make the full pipeline unreachable so tests prove the incremental@@ -153,8 +184,7 @@ def test_deleted_file_falls_back_to_full_pipeline(tmp_path, stub_full_pipeline):result = asyncio.run(update_single_repo_index(repo))- assert len(stub_full_pipeline) == 1- assert result.updated is True+ _assert_full_pipeline_fallback(result, stub_full_pipeline)def test_renamed_file_falls_back_to_full_pipeline(tmp_path, stub_full_pipeline):@@ -168,8 +198,7 @@ def test_renamed_file_falls_back_to_full_pipeline(tmp_path, stub_full_pipeline):result = asyncio.run(update_single_repo_index(repo))- assert len(stub_full_pipeline) == 1- assert result.updated is True+ _assert_full_pipeline_fallback(result, stub_full_pipeline)def test_never_indexed_repo_runs_full_pipeline(tmp_path, stub_full_pipeline):@@ -177,8 +206,7 @@ def test_never_indexed_repo_runs_full_pipeline(tmp_path, stub_full_pipeline):result = asyncio.run(update_single_repo_index(repo))- assert len(stub_full_pipeline) == 1- assert result.updated is True+ _assert_full_pipeline_fallback(result, stub_full_pipeline)assert result.file_count == 7@@ -191,8 +219,7 @@ def test_unresolvable_base_commit_falls_back_to_full_pipeline(tmp_path, stub_fulresult = asyncio.run(update_single_repo_index(repo))- assert len(stub_full_pipeline) == 1- assert result.updated is True+ _assert_full_pipeline_fallback(result, stub_full_pipeline)def test_incremental_failure_falls_back_to_full_pipeline(tmp_path, stub_full_pipeline, monkeypatch):@@ -210,8 +237,7 @@ def test_incremental_failure_falls_back_to_full_pipeline(tmp_path, stub_full_pipresult = asyncio.run(update_single_repo_index(repo))- assert len(stub_full_pipeline) == 1- assert result.updated is True+ _assert_full_pipeline_fallback(result, stub_full_pipeline)assert result.error is None@@ -255,6 +281,48 @@ def test_incremental_threads_persisted_state_flags(tmp_path, forbid_full_pipelinassert captured["include_nested_repos"] is True+def test_incremental_merges_repo_settings_excludes(tmp_path, forbid_full_pipeline, monkeypatch):+ import repowise.core.pipeline.incremental as incremental_mod++ repo = _make_git_repo(tmp_path)+ base = get_head_commit(repo)+ _mark_indexed(repo, base)+ _write_repo_settings(repo, {"exclude_patterns": ["tools/"]})+ _add_commit(repo, "b.py")++ captured: dict = {}++ async def _fake_rebuild(repo_path, file_diffs, cfg, exclude_patterns, **kwargs):+ captured["exclude_patterns"] = exclude_patterns+ return [], {}, None, None, 0, {}++ def _fake_analysis(*args, **kwargs):+ return None, None++ async def _fake_persist(*args, **kwargs):+ return None++ monkeypatch.setattr(incremental_mod, "rebuild_graph_and_git", _fake_rebuild)+ monkeypatch.setattr(incremental_mod, "run_partial_analysis", _fake_analysis)+ monkeypatch.setattr(incremental_mod, "persist_incremental_index", _fake_persist)++ result = asyncio.run(update_single_repo_index(repo))++ assert result.updated is True+ assert captured["exclude_patterns"] == ["tools/"]+++def test_full_pipeline_merges_repo_settings_excludes(tmp_path, stub_full_pipeline):+ repo = _make_git_repo(tmp_path)+ _mark_indexed(repo, "deadbeef" * 5)+ _write_repo_settings(repo, {"exclude_patterns": ["tools/"]})++ result = asyncio.run(update_single_repo_index(repo))++ _assert_full_pipeline_fallback(result, stub_full_pipeline)+ assert stub_full_pipeline[0]["exclude_patterns"] == ["tools/"]++# ---------------------------------------------------------------------------# Helpers under test# ---------------------------------------------------------------------------diff --git a/tests/unit/workspace/test_update.py b/tests/unit/workspace/test_update.pyindex 363232169..382fb0a52 100644--- a/tests/unit/workspace/test_update.py+++ b/tests/unit/workspace/test_update.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport jsonimport subprocess+from datetime import UTC, datetimefrom pathlib import Pathfrom unittest.mock import AsyncMock, patch@@ -252,6 +253,70 @@ class TestUpdateWorkspace:assert results[0].updated is Falseassert results[0].skipped_reason == "up_to_date"+ def test_up_to_date_repo_reconciles_freshness_stamp(self, tmp_path: Path) -> None:+ """An up-to-date workspace sync still refreshes the repo row timestamp."""+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ )+ from repowise.core.persistence.crud import get_repository_by_path, upsert_repository+ from repowise.core.persistence.database import resolve_db_url++ repo = _make_git_repo(tmp_path, "backend")+ head = get_head_commit(repo)+ _write_state(repo, head)++ ws_config = WorkspaceConfig(+ repos=[RepoEntry(path="backend", alias="backend", last_commit_at_index=head)],+ default_repo="backend",+ )+ ws_config.save(tmp_path)++ stale_dt = datetime(2026, 7, 1, 12, 0, tzinfo=UTC)++ async def _seed() -> None:+ engine = create_engine(resolve_db_url(repo))+ await init_db(engine)+ sf = create_session_factory(engine)+ try:+ async with get_session(sf) as session:+ row = await upsert_repository(+ session,+ name="backend",+ local_path=str(repo),+ head_commit="deadbeef" + "0" * 32,+ )+ row.updated_at = stale_dt+ await session.flush()+ finally:+ await engine.dispose()++ async def _read_back():+ engine = create_engine(resolve_db_url(repo))+ sf = create_session_factory(engine)+ try:+ async with get_session(sf) as session:+ return await get_repository_by_path(session, str(repo))+ finally:+ await engine.dispose()++ async def _run():+ await _seed()+ return await update_workspace(tmp_path, ws_config)++ import asyncio++ results = asyncio.run(_run())+ row = asyncio.run(_read_back())+ assert len(results) == 1+ assert results[0].updated is False+ assert results[0].skipped_reason == "up_to_date"+ assert row is not None+ assert row.head_commit == head+ assert row.updated_at.replace(tzinfo=UTC) > stale_dt+def test_detects_stale_repo(self, tmp_path: Path) -> None:"""Repos with new commits should be detected as stale."""repo = _make_git_repo(tmp_path, "backend")