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(update): keep governance findings when health is rescored (#2926)

Raghav Chamadiyaf9509f00d3ae
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
index 4c50ec74f..deb4a5f7f 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -1141,27 +1141,10 @@ async def _persist_full_update_async(
if timings is not None:
timings.start("persist.governance")
try:
- from sqlalchemy import select as _sel_dec
+ from repowise.core.pipeline.persist import refresh_governance_findings
- from repowise.core.analysis.health.governance import build_governance_findings
- from repowise.core.persistence.crud import (
- get_decision_health_summary,
- get_scored_file_paths,
- replace_governance_findings,
- )
- from repowise.core.persistence.models import DecisionRecord
-
- _dr = await session.execute(
- _sel_dec(DecisionRecord).where(DecisionRecord.repository_id == repo_id)
- )
- _decisions = list(_dr.scalars().all())
- _summary = await get_decision_health_summary(session, repo_id)
- _gov = build_governance_findings(
- health_summary=_summary,
- decisions=_decisions,
- scored_paths=await get_scored_file_paths(session, repo_id),
- )
- await replace_governance_findings(session, repo_id, _gov)
+ # The health step below finalizes the refactoring queue.
+ await refresh_governance_findings(session, repo_id, recompose_queue=False)
except Exception as exc:
_skip("Governance findings", exc)
finally:
@@ -1431,6 +1414,7 @@ async def _rescore_health_from_db(
from repowise.core.persistence.models import GitMetadata, HealthFinding
from repowise.core.pipeline.persist import (
persist_graph_nodes,
+ refresh_governance_findings,
save_full_health_report,
)
from repowise.core.pipeline.resume.rehydrate import (
@@ -1531,6 +1515,12 @@ async def _rescore_health_from_db(
await save_full_health_report(
session, repo_id, report, analyzed_commit=get_head_commit(Path(repo_path))
)
+ # That writer replaced every open finding, the governance ones too,
+ # and only the governance pass produces those.
+ try:
+ await refresh_governance_findings(session, repo_id)
+ except Exception as exc:
+ console.print(f"[yellow]Governance findings skipped: {exc}[/yellow]")
# Rows for the files blamed above, so the next re-score reads them.
if report.function_blame_rows:
await upsert_git_function_blame_bulk(session, repo_id, report.function_blame_rows)
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index e7bc15f7a..b6c5eb0da 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -1979,6 +1979,61 @@ async def save_full_health_report(
await finalize_refactoring_opportunities(session, repo_id, analyzed_commit=analyzed_commit)
+async def refresh_governance_findings(
+ session: Any, repo_id: str, *, recompose_queue: bool = True
+) -> int:
+ """Rebuild the governance findings from the stored decisions and health rows.
+
+ Every writer that runs the governance pass comes through here: the index
+ after its decisions are stored, the update after its decision steps, and
+ the full health re-score, whose findings replace deletes these rows along
+ with every other open finding. Returns the number of findings written.
+
+ ``recompose_queue`` re-folds the refactoring queue when findings were
+ written, since it is composed over the stored findings and may have been
+ built before these rows existed. Only that queue: the performance
+ finalizer reads ``performance`` findings, and every governance biomarker
+ is ``organizational``. A caller that finalizes the queue next anyway
+ passes ``False``.
+ """
+ from sqlalchemy import select
+
+ from repowise.core.analysis.health.governance import build_governance_findings
+ from repowise.core.persistence.crud import (
+ finalize_refactoring_opportunities,
+ get_decision_health_summary,
+ get_scored_file_paths,
+ replace_governance_findings,
+ )
+ from repowise.core.persistence.models import DecisionRecord
+
+ # One savepoint: the replace deletes before it inserts, and the queue
+ # reconciles as a whole, so a failure must leave neither half-written.
+ async with session.begin_nested():
+ decisions = list(
+ (
+ await session.execute(
+ select(DecisionRecord).where(DecisionRecord.repository_id == repo_id)
+ )
+ )
+ .scalars()
+ .all()
+ )
+ findings = build_governance_findings(
+ health_summary=await get_decision_health_summary(session, repo_id),
+ decisions=decisions,
+ scored_paths=await get_scored_file_paths(session, repo_id),
+ )
+ await replace_governance_findings(session, repo_id, findings)
+ if findings and recompose_queue:
+ await finalize_refactoring_opportunities(
+ session, repo_id, analyzed_commit=await _analyzed_commit(session, repo_id)
+ )
+ if findings:
+ logger.info("governance_findings_persisted", repo_id=repo_id, count=len(findings))
+ return len(findings)
+
+
async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
"""Persist analysis-phase outputs: dead code, health, decisions, drift.
@@ -2213,53 +2268,9 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
# ---- Governance findings (additive pass, after decisions are persisted) ----
# Runs after bulk_upsert_decisions + detect_supersessions_and_conflicts so
- # the decision graph is complete. Best-effort — never breaks persist.
+ # the decision graph is complete. Best-effort: never breaks persist.
try:
- from sqlalchemy import select as _select
-
- from repowise.core.analysis.health.governance import build_governance_findings
- from repowise.core.persistence.crud import (
- get_decision_health_summary,
- get_scored_file_paths,
- replace_governance_findings,
- )
- from repowise.core.persistence.models import DecisionRecord
-
- _dr_result = await session.execute(
- _select(DecisionRecord).where(DecisionRecord.repository_id == repo_id)
- )
- _decisions = list(_dr_result.scalars().all())
- _health_summary = await get_decision_health_summary(session, repo_id)
- _gov_findings = build_governance_findings(
- health_summary=_health_summary,
- decisions=_decisions,
- scored_paths=await get_scored_file_paths(session, repo_id),
- )
- await replace_governance_findings(session, repo_id, _gov_findings)
- if _gov_findings:
- logger.info(
- "governance_findings_persisted",
- repo_id=repo_id,
- count=len(_gov_findings),
- )
- # The refactoring queue is a fold over the stored findings and was
- # composed above, before these rows existed, so without a second
- # pass a fresh index ranks every opportunity against a finding set
- # holding none of its governance causes. Only this queue: the
- # performance finalizer reads ``performance`` findings, and every
- # governance biomarker is ``organizational``.
- from repowise.core.persistence.crud import (
- finalize_refactoring_opportunities,
- )
-
- # Savepointed like the first composition: this writer reconciles
- # the whole queue, so a half-failed one would leave it half-described.
- async with session.begin_nested():
- await finalize_refactoring_opportunities(
- session,
- repo_id,
- analyzed_commit=await _analyzed_commit(session, repo_id),
- )
+ await refresh_governance_findings(session, repo_id)
except Exception as _gov_err:
logger.debug("governance_findings_skipped", error=str(_gov_err))
diff --git a/tests/unit/cli/test_rescore_rebuilds_read_models.py b/tests/unit/cli/test_rescore_rebuilds_read_models.py
index 4a61173a1..de48eb0e0 100644
--- a/tests/unit/cli/test_rescore_rebuilds_read_models.py
+++ b/tests/unit/cli/test_rescore_rebuilds_read_models.py
@@ -250,3 +250,14 @@ class TestRescoreKeepsHistoryMarkers:
assert {"prior_defect", "co_change_scatter"} <= types
# No blame index is persisted, so the stored finding is kept, not deleted.
assert "function_hotspot" in types
+
+
+class TestRescoreKeepsGovernanceFindings:
+ async def test_an_ungoverned_hotspot_survives_the_rescore(self, git_repo: Path):
+ # A hotspot no decision names: the governance pass, not the analyzer,
+ # writes its finding, and the re-score replaces every open finding.
+ repo_id = await _seed_history(git_repo)
+
+ await _rescore_health_from_db(git_repo, _EmptyGraphBuilder(), [_parsed_file(git_repo)], [])
+
+ assert "ungoverned_hotspot" in await _finding_types(git_repo, repo_id)