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
feat(actions): act now on a week's defect-class regressions, plan its code shape (#4198)
Raghav Chamadiyacee995e8a08d
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.mdindex 5a0e82a5e..397f94044 100644--- a/docs/layers/CODE_HEALTH.md+++ b/docs/layers/CODE_HEALTH.md@@ -172,6 +172,9 @@ Now, Worth planning and Improve what Repowise can see. Within a group, rows rankby value times confidence over effort, and the top due Fix first item leads itsgroup, so Do next and Fix first lead with the same work. Dismissing or snoozing arow takes effect at once.+A fresh regression is in Now only when this week's commits added a proven+performance cause (one in the performance queue) or lost measured coverage. The+long, complex or nested code a week of work leaves becomes one row to plan.A fragile file asks for tests only when no measured coverage and no test in thecode graph reaches it; otherwise the row asks you to simplify its lead function. Afolder where bug fixes concentrate names its first step, the most fixed file's, ordiff --git a/packages/core/src/repowise/core/analysis/actions/build.py b/packages/core/src/repowise/core/analysis/actions/build.pyindex bd1a0e9cf..d0da80979 100644--- a/packages/core/src/repowise/core/analysis/actions/build.py+++ b/packages/core/src/repowise/core/analysis/actions/build.py@@ -28,11 +28,12 @@ Row shapes (the field names are the SQL columns):``commit_health````sha``, ``subject``, ``committed_at`` (the commit's), ``file_path``,``symbol``, ``biomarker_type``, ``severity``, ``change_kind``,- ``line_start``, ``reason``, ``attribution_basis``.+ ``line_start``, ``reason``, ``attribution_basis``, ``dimension``.``fix_first``One mapping of the Fix-first builder's own inputs (``metrics``,``findings``, ``refactoring``, ``performance``, ``plans``); shapes in- ``repowise.core.analysis.health.fix_first.build``.+ ``repowise.core.analysis.health.fix_first.build``. The recent findings+ also read ``performance`` rows' ``queue_eligible`` and ``cost_proof``.``security````file_path``, ``kind``, ``line_number``, ``snippet``, ``severity``,``commit_sha`` (empty for the working tree).@@ -278,27 +279,45 @@ def build_authors(rows: Rows, *, since: datetime | None) -> dict[str, Any]:return {"author_last_commit": last, "active_authors_90d": len(active)}+#: Markers that read a measured coverage report, so "worsened" is coverage the+#: change lost. ``untested_hotspot`` is left out: without a report it fires on a+#: missing test file, which no commit's lines decide.+COVERAGE_MARKERS = frozenset({"coverage_gap", "coverage_gradient"})++#: Commit-health rows a loader reads: the authored kinds, at a severity that+#: counts, or a performance marker of any severity (its proof is the cause's+#: place in the performance queue, not the marker's label).+SERIOUS = ("critical", "high")++def _authored_regression(row: Any) -> bool:- """The commit's own lines introduced or worsened a critical/high finding."""+ """The commit's own lines introduced or worsened the finding."""return (field(row, "change_kind") in ("introduced", "worsened")- and field(row, "severity") in ("critical", "high")and field(row, "attribution_basis") in AUTHORED_BASES)-def _shown_code_shape(row: Any, hidden: frozenset[str]) -> bool:- """A code-shape marker, not a history one, and one the registry serves."""+def recent_kind(row: Any, hidden: frozenset[str]) -> str | None:+ """What a commit-health row says the commit did: ``performance`` and+ ``coverage`` are defect-class, ``shape`` is a code-shape marker, and+ ``None`` is a history or hidden marker, or one below the bar."""biomarker = field(row, "biomarker_type")- return biomarker_category(biomarker) != HISTORY_CATEGORY and is_served(- "health", biomarker, field(row, "file_path"), hidden- )+ path = field(row, "file_path")+ # The row's own dimension, as the loader filters on it.+ if field(row, "dimension") == "performance":+ return "performance" if is_served("performance", biomarker, path, hidden) else None+ if field(row, "severity") not in SERIOUS or not is_served("health", biomarker, path, hidden):+ return None+ if biomarker in COVERAGE_MARKERS:+ return "coverage"+ return "shape" if biomarker_category(biomarker) != HISTORY_CATEGORY else Nonedef _recent_candidates(rows: Rows, *, week: datetime | None, files: Mapping[str, FileFacts]-) -> list[tuple[Any, datetime]]:- """Authored critical/high code-shape findings from commits since ``week``."""+) -> list[tuple[Any, datetime, str]]:+ """Authored findings from commits since ``week``, with their :func:`recent_kind`."""if week is None:return []hidden = excluded_types()@@ -309,47 +328,76 @@ def _recent_candidates(continueif _is_test(field(f, "file_path"), files):continue- if _shown_code_shape(f, hidden):- out.append((f, at))+ kind = recent_kind(f, hidden)+ if kind is not None:+ out.append((f, at, kind))return out+def proven_performance(rows: Rows) -> frozenset[tuple[str, str]]:+ """``(file, marker)`` of each open performance cause in the default queue+ whose cost is proven to grow: the bar a performance regression clears."""+ return frozenset(+ (field(r, "file_path"), field(r, "biomarker_type"))+ for r in rows+ if _open(r)+ and field(r, "queue_eligible") is True+ and (field(r, "cost_proof") or "proven") == "proven"+ )++def build_recent(rows: Rows,*,week: datetime | None,open_findings: Rows,files: Mapping[str, FileFacts],+ performance: Rows = (),) -> dict[str, Any]:- """Findings a commit in the last week wrote that are still open and serious,- as the open finding reads today."""+ """Findings a commit in the last week wrote that still count today.++ A code-shape or coverage finding counts while its open finding is still+ critical or high, and reads as that finding does today. A performance one+ counts while its file holds an open, proven cause of the same marker in+ the performance queue (``performance`` rows, :func:`proven_performance`).+ """if week is None:return {}candidates = _recent_candidates(rows, week=week, files=files)if not candidates:return {"recent_findings": ()}serious = _serious_open(open_findings)+ proven = proven_performance(performance)recent = []seen: set[tuple[str, str, str | None]] = set()- for f, at in sorted(candidates, key=lambda c: c[1], reverse=True):- key = (field(f, "file_path"), field(f, "biomarker_type"), field(f, "symbol"))- # Still serious today, and counted once however many commits touched it.- now = serious.get(key)- if now is None or key in seen:+ for f, at, kind in sorted(candidates, key=lambda c: c[1], reverse=True):+ path, biomarker = field(f, "file_path"), field(f, "biomarker_type")+ key = (path, biomarker, field(f, "symbol"))+ # Still counts today, and counted once however many commits touched it.+ if key in seen:continue+ if kind == "performance":+ if (path, biomarker) not in proven:+ continue+ now = f+ else:+ now = serious.get(key)+ if now is None:+ continueseen.add(key)recent.append(RecentFinding(sha=field(f, "sha"),subject=field(f, "subject") or "",committed_at=at,- file_path=field(f, "file_path"),+ file_path=path,symbol=field(f, "symbol"),- biomarker=field(f, "biomarker_type"),+ biomarker=biomarker,severity=field(now, "severity"),change_kind=field(f, "change_kind"),line=field(now, "line_start"),reason=field(now, "reason") or "",+ kind=kind,))return {"recent_findings": tuple(recent)}@@ -541,7 +589,11 @@ def build_repo_facts("commit_health",commit_health,lambda rows: build_recent(- rows, week=week, open_findings=health_findings, files=known_files+ rows,+ week=week,+ open_findings=health_findings,+ files=known_files,+ performance=(fix_first or {}).get("performance") or (),),)build("fix_first", fix_first, build_fix_first_store)@@ -557,8 +609,10 @@ def build_repo_facts(__all__ = ["ABSENT","AUTHORED_BASES",+ "COVERAGE_MARKERS","LEAD_LOOKUP_MIN_COMMITS","QUARTER",+ "SERIOUS","WEEK","build_authors","build_coverage",@@ -571,7 +625,9 @@ __all__ = ["build_repo_facts","build_secrets","lead_paths",+ "proven_performance","reach_paths",+ "recent_kind","with_leads","with_test_reach",]diff --git a/packages/core/src/repowise/core/analysis/actions/facts.py b/packages/core/src/repowise/core/analysis/actions/facts.pyindex 5dbd81468..d1578abc1 100644--- a/packages/core/src/repowise/core/analysis/actions/facts.py+++ b/packages/core/src/repowise/core/analysis/actions/facts.py@@ -68,6 +68,13 @@ class RecentFinding:change_kind: strline: int | Nonereason: str = ""+ #: ``performance`` or ``coverage`` for a defect-class+ #: finding; ``shape`` for a code-shape marker (a long or nested method).+ kind: str = "shape"++ @property+ def defect(self) -> bool:+ return self.kind != "shape"@dataclass(frozen=True, slots=True)diff --git a/packages/core/src/repowise/core/analysis/actions/rules/code.py b/packages/core/src/repowise/core/analysis/actions/rules/code.pyindex 2a1a76ea4..e860bc4e0 100644--- a/packages/core/src/repowise/core/analysis/actions/rules/code.py+++ b/packages/core/src/repowise/core/analysis/actions/rules/code.py@@ -10,6 +10,7 @@ from datetime import datetimefrom ..context import HISTORY_TOO_SHORT, RepoContextfrom ..facts import FileFacts, RepoFactsfrom ..model import (+ SEVERITY_VALUE,Action,ActionCommand,ActionDetail,@@ -50,60 +51,89 @@ REGRESSION_FILE_ROWS = 3def fresh_regressions(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:- """Serious findings the last week of commits added and nobody has fixed yet.+ """Findings the last week of commits added and nobody has fixed yet.The loader keeps only findings the commit demonstrably wrote (added lines,a new file, or a changed symbol), still open, in production code, and nothistory markers: "you made this worse" has to be true of the diff.++ Only defect-class findings act now: a proven performance cause or lost+ coverage. Code shape (a long or nested method) is what a week of feature+ work leaves on any active repository, so it rolls up into one maintainability+ item to plan. A credential is ``live_secret``'s whichever commit added it,+ and the scanner's pattern kinds stay on the Security tab (``hygiene``)."""rule = "fresh_regressions"if "commit_health" in facts.unavailable:return RuleOutcome(rule, "unavailable", facts.unavailable["commit_health"])if ctx.anchor is None:return RuleOutcome(rule, "not_applicable", "No commit history in the index.")- by_file: dict[str, list] = defaultdict(list)+ defects: dict[str, list] = defaultdict(list)+ shape: dict[str, list] = defaultdict(list)for f in facts.recent_findings:- by_file[f.file_path].append(f)- if not by_file:- return RuleOutcome(rule, "evaluated")-- def weight(found: list) -> float:- return sum(f.severity == "critical" for f in found) * 10.0 + len(found)-- ranked = sorted(by_file.items(), key=lambda kv: (-weight(kv[1]), kv[0]))- if len(ranked) > REGRESSION_FILE_ROWS:- return RuleOutcome(rule, "evaluated", "", (_regression_rollup(ranked),))- return RuleOutcome(- rule,- "evaluated",- "",- tuple(_regression_file(path, found, ctx, weight(found)) for path, found in ranked),- )+ (defects if f.defect else shape)[f.file_path].append(f)+ actions: list[Action] = []+ if defects:+ ranked = sorted(defects.items(), key=lambda kv: (-_regression_weight(kv[1]), kv[0]))+ if len(ranked) > REGRESSION_FILE_ROWS:+ actions.append(_regression_rollup(ranked))+ else:+ actions.extend(+ _regression_file(path, found, ctx, _regression_weight(found))+ for path, found in ranked+ )+ if shape:+ ranked = sorted(shape.items(), key=lambda kv: (-_shape_weight(kv[1]), kv[0]))+ actions.append(_shape_rollup(ranked))+ return RuleOutcome(rule, "evaluated", "", tuple(actions))+++#: How much each defect class weighs when files are ordered: a proven+#: performance cause runs on every call, lost coverage is a risk to the next one.+_KIND_WEIGHT = {"performance": 3.0, "coverage": 1.0}+#: How a defect-class finding is named in a sentence.+_KIND_NOUN = {"performance": "performance regression", "coverage": "coverage drop"}-def _regression_value(critical: int) -> int:- """The value a regression ranks on: a week with critical findings still- outranks one without, as it did when the action itself read critical.- The action's severity tops out at high. Health detectors tag a long method- critical, and a routine week of feature work leaves dozens of those, so a- critical label here would read as an emergency most weeks. Critical on an- action is kept for a live credential (``live_secret``).+def _regression_weight(found: list) -> float:+ return sum(_KIND_WEIGHT.get(f.kind, 1.0) for f in found)+++def _shape_weight(found: list) -> float:+ return sum(f.severity == "critical" for f in found) * 10.0 + len(found)+++def _regression_value(found: list) -> int:+ """The value a defect-class regression ranks on: a proven performance+ cause outranks lost coverage.++ The action's severity tops out at high. Critical on an action is kept for+ a live credential (``live_secret``)."""- return 4 if critical else 3+ return 4 if any(f.kind == "performance" for f in found) else 3+++def _kinds_text(found: list) -> str:+ """``1 performance regression and 2 coverage drops``, worst class first."""+ counts = {k: sum(f.kind == k for f in found) for k in _KIND_NOUN}+ parts = [plural(n, _KIND_NOUN[k]) for k, n in counts.items() if n]+ return " and ".join(parts) or plural(len(found), "finding")def _regression_file(path: str, found: list, ctx: RepoContext, weight: float) -> Action:symbols = sorted({f.symbol for f in found if f.symbol})- critical = sum(f.severity == "critical" for f in found)commits = {f.sha: f for f in found}- lead = max(found, key=lambda f: (f.severity == "critical", f.line or 0))- if len(symbols) == 1:- title = f"Simplify {code(symbols[0])} in {code(path)} while the change is fresh"- elif symbols:- title = f"Tidy {plural(len(symbols), 'function')} you changed in {code(path)} this week"+ lead = max(found, key=lambda f: (_KIND_WEIGHT.get(f.kind, 1.0), f.line or 0))+ kinds = {f.kind for f in found}+ if kinds == {"coverage"}:+ title = f"Restore the test coverage this week's changes lost in {code(path)}"+ elif kinds == {"performance"} and len(symbols) == 1:+ title = f"Fix the performance regression in {code(symbols[0])} in {code(path)}"+ elif kinds == {"performance"}:+ title = f"Fix the performance regressions this week's changes added to {code(path)}"else:- title = f"Tidy what this week's changes left in {code(path)}"+ title = f"Fix what this week's changes added to {code(path)}"latest = max(commits.values(), key=lambda f: f.committed_at or ctx.anchor)return Action(rule="fresh_regressions",@@ -112,35 +142,38 @@ def _regression_file(path: str, found: list, ctx: RepoContext, weight: float) ->severity="high",title=title,impact=(- f"{plural(len(commits), 'commit')} in the last 7 days added or worsened "- f"{plural(len(found), 'critical or high finding')} here, still open. "+ f"{plural(len(commits), 'commit')} in the last 7 days added "+ f"{_kinds_text(found)} here, still open. ""Fixing now costs less than after the next change."),why=(- WhyFact("serious findings", str(len(found))),- WhyFact("critical findings", str(critical)),+ WhyFact("defect findings", str(len(found))),+ WhyFact("kinds", ", ".join(sorted(kinds))),WhyFact("latest commit", latest.subject[:72] or latest.sha[:7]),),target_kind="symbol" if len(symbols) == 1 else "file",target_path=path,target_symbol=symbols[0] if len(symbols) == 1 else None,- surface="findings",+ surface="performance" if kinds == {"performance"} else "findings",effort="S" if len(symbols) <= 2 else "M",confidence="high",done_when="The findings close on the next update.",marker=lead.biomarker,weight=weight,- value=_regression_value(critical),+ value=_regression_value(found),evidence_ids=tuple(sorted(commits)),evidence_total=len(found),- fingerprint=fingerprint(len(found), critical),+ fingerprint=fingerprint(len(found), *sorted(kinds)),details=_regression_details(found),commands=_regression_commands([path], latest.sha),)def _regression_details(found: list) -> tuple[ActionDetail, ...]:- ordered = sorted(found, key=lambda f: (f.severity != "critical", f.file_path, f.line or 0))+ ordered = sorted(+ found,+ key=lambda f: (-_KIND_WEIGHT.get(f.kind, 0.0), f.severity != "critical", f.file_path, f.line or 0),+ )return tuple(ActionDetail(path=f.file_path,@@ -181,27 +214,24 @@ def _regression_commands(paths: list[str], sha: str) -> tuple[ActionCommand, ...def _regression_rollup(ranked: list[tuple[str, list]]) -> Action:found = [f for _, fs in ranked for f in fs]- critical = sum(f.severity == "critical" for f in found)commits = {f.sha for f in found}worst_path, worst = ranked[0]- worst_critical = sum(f.severity == "critical" for f in worst)return Action(rule="fresh_regressions",tier="act_now",horizons=("week",),severity="high",title=(- f"Clean up what this week's commits left: {plural(len(found), 'serious finding')} "+ f"Fix what this week's commits added: {_kinds_text(found)} "f"in {len(ranked):,} files"),impact=(- f"{plural(len(commits), 'commit')} in the last 7 days added or worsened them, and they are "- f"still open. Start with {code(worst_path)}"- + (f", which has {worst_critical} critical." if worst_critical else ".")+ f"{plural(len(commits), 'commit')} in the last 7 days added them, and they are "+ f"still open. Start with {code(worst_path)}, which has {_kinds_text(worst)}."),why=(- WhyFact("serious findings", str(len(found))),- WhyFact("critical findings", str(critical)),+ WhyFact("defect findings", str(len(found))),+ WhyFact("kinds", ", ".join(sorted({f.kind for f in found}))),WhyFact("files", str(len(ranked))),),target_kind="repo",@@ -210,12 +240,12 @@ def _regression_rollup(ranked: list[tuple[str, list]]) -> Action:effort="L" if len(ranked) > 10 else "M",confidence="high",done_when="The findings close on the next update.",- weight=float(critical * 10 + len(found)),- value=_regression_value(critical),+ weight=_regression_weight(found),+ value=_regression_value(found),evidence_ids=tuple(sorted(commits)),evidence_total=len(found),includes=tuple(path for path, _ in ranked[:10]),- fingerprint=fingerprint(len(found) // 10, critical // 5),+ fingerprint=fingerprint(len(found) // 10, *sorted({f.kind for f in found})),# Evidence in the order the files are ranked, so it starts where the# impact line says to start; the commit to inspect is the latest one# that touched that same file.@@ -228,6 +258,60 @@ def _regression_rollup(ranked: list[tuple[str, list]]) -> Action:)+def _shape_rollup(ranked: list[tuple[str, list]]) -> Action:+ """The week's code-shape findings as one maintainability item to plan.++ One item however many files: a week of feature work can leave long or+ nested methods in seventy files, and none of them is an emergency.+ """+ found = [f for _, fs in ranked for f in fs]+ commits = {f.sha for f in found}+ worst_path, worst = ranked[0]+ where = code(worst_path) if len(ranked) == 1 else f"{len(ranked):,} files"+ return Action(+ rule="fresh_regressions",+ tier="plan",+ horizons=("week",),+ severity="medium",+ title=(+ f"Tidy the code shape this week's commits left: "+ f"{plural(len(found), 'finding')} in {where}"+ ),+ impact=(+ f"{plural(len(commits), 'commit')} in the last 7 days added or worsened long, "+ f"complex or deeply nested code, still open. Start with {code(worst_path)}"+ f" ({plural(len(worst), 'finding')}): tidying it while the change is fresh "+ "costs less than after the next one."+ ),+ why=(+ WhyFact("code-shape findings", str(len(found))),+ WhyFact("files", str(len(ranked))),+ WhyFact("commits", str(len(commits))),+ ),+ target_kind="repo" if len(ranked) > 1 else "file",+ target_path="" if len(ranked) > 1 else worst_path,+ # Its own identity, so it never shares an id with a defect action.+ identity="code_shape",+ surface="commits" if len(ranked) > 1 else "findings",+ effort="L" if len(ranked) > 10 else "M",+ confidence="high",+ done_when="The findings close on the next update.",+ marker=max(worst, key=lambda f: (f.severity == "critical", f.line or 0)).biomarker,+ weight=float(len(found)),+ value=SEVERITY_VALUE["medium"],+ evidence_ids=tuple(sorted(commits)),+ evidence_total=len(found),+ includes=tuple(path for path, _ in ranked[:10]),+ fingerprint=fingerprint("shape", len(found) // 10),+ details=tuple(d for _, fs in ranked for d in _regression_details(fs)),+ details_total=len(found),+ commands=_regression_commands(+ [path for path, _ in ranked],+ max(worst, key=lambda f: f.committed_at or datetime.min).sha,+ ),+ )++def _coverage_fact(f: FileFacts, facts: RepoFacts) -> WhyFact:if f.line_coverage_pct is not None:basis = "measured"@@ -586,12 +670,20 @@ def fix_first(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:if "fix_first" in facts.unavailable:return RuleOutcome(rule, "unavailable", facts.unavailable["fix_first"])actions = []+ # A cause this week's commits added acts now as a fresh regression, with+ # the commit that added it; it is not listed twice.+ fresh_perf = {+ (f.file_path, _short(f.symbol)) for f in facts.recent_findings if f.kind == "performance"+ }# Do next's number for each item, held to the queue's order: a later item# never outranks an earlier one, whatever its effort.ceiling = math.inffor item in facts.fix_first:tier = _FIX_FIRST_TIER.get(item.tier)- if tier is None:+ if tier is None or (+ item.kind == "perf_fix"+ and (item.target.file_path, _short(item.target.symbol)) in fresh_perf+ ):continueeffort = _effort(item.effort.bucket)confidence = "high" if item.confidence.level == "high" else "medium"@@ -644,6 +736,11 @@ def fix_first(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:return RuleOutcome(rule, "evaluated", "", tuple(actions))+def _short(symbol: str | None) -> str | None:+ """A symbol's own name: ``a.py::Repo.load`` and ``Repo.load`` are ``load``."""+ return symbol.rsplit("::", 1)[-1].rsplit(".", 1)[-1] if symbol else None++def _effort(bucket: str | None) -> str:if bucket == "S":return "S"diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/actions.py b/packages/core/src/repowise/core/persistence/crud/analysis/actions.pyindex af2d87d88..153c0761a 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/actions.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/actions.py@@ -20,7 +20,7 @@ from collections.abc import Awaitable, Callablefrom datetime import UTC, datetimefrom typing import Any-from sqlalchemy import func, select+from sqlalchemy import func, or_, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.analysis.actions import (@@ -36,6 +36,7 @@ from repowise.core.analysis.actions.build import (ABSENT,AUTHORED_BASES,QUARTER,+ SERIOUS,WEEK,build_authors,build_coverage,@@ -71,6 +72,7 @@ from ...models import (GraphMetric,HealthFileMetric,HealthFinding,+ PerformanceOpportunity,SecurityFinding,)from ...read_snapshots import mark_current, read_snapshot, refresh_snapshot, snapshot_key@@ -204,6 +206,7 @@ async def _recent(GitCommitHealthFinding.line_start,GitCommitHealthFinding.reason,GitCommitHealthFinding.attribution_basis,+ GitCommitHealthFinding.dimension,GitCommit.subject,GitCommit.committed_at,)@@ -216,24 +219,59 @@ async def _recent(GitCommitHealthFinding.repository_id == repo_id,GitCommit.committed_at >= since,GitCommitHealthFinding.change_kind.in_(("introduced", "worsened")),- GitCommitHealthFinding.severity.in_(("critical", "high")),+ or_(+ GitCommitHealthFinding.severity.in_(SERIOUS),+ GitCommitHealthFinding.dimension == "performance",+ ),GitCommitHealthFinding.attribution_basis.in_(AUTHORED_BASES),))).all()open_findings: list[Any] = []+ performance: list[Any] = []if rows:open_findings = (await session.execute(select(*_HEALTH_FINDING_COLUMNS).where(HealthFinding.repository_id == repo_id,HealthFinding.status == "open",- HealthFinding.severity.in_(("critical", "high")),+ HealthFinding.severity.in_(SERIOUS),HealthFinding.file_path.in_({r.file_path for r in rows}),))).all()- return build_recent(rows, week=since, open_findings=open_findings, files=files)+ perf_paths = {r.file_path for r in rows if r.dimension == "performance"}+ if perf_paths:+ performance = await _proven_performance(session, repo_id, perf_paths)+ return build_recent(+ rows, week=since, open_findings=open_findings, files=files, performance=performance+ )+++async def _proven_performance(session: AsyncSession, repo_id: str, paths: set[str]) -> list[Any]:+ """The queue's open causes in ``paths``; none when the store cannot be+ read, which costs only the performance regressions, not the week's rest."""+ try:+ async with session.begin_nested():+ return (+ await session.execute(+ select(+ PerformanceOpportunity.file_path,+ PerformanceOpportunity.biomarker_type,+ PerformanceOpportunity.status,+ PerformanceOpportunity.queue_eligible,+ PerformanceOpportunity.cost_proof,+ ).where(+ PerformanceOpportunity.repository_id == repo_id,+ PerformanceOpportunity.status == "open",+ PerformanceOpportunity.queue_eligible.is_(True),+ PerformanceOpportunity.file_path.in_(paths),+ )+ )+ ).all()+ except Exception as exc: # an index from before the performance store+ logger.warning("actions: performance causes unavailable: %s", exc)+ return []async def _history(session: AsyncSession, repo_id: str) -> dict[str, Any]:diff --git a/tests/unit/analysis/test_actions_rules.py b/tests/unit/analysis/test_actions_rules.pyindex 6b06eaacc..3501a13b1 100644--- a/tests/unit/analysis/test_actions_rules.py+++ b/tests/unit/analysis/test_actions_rules.py@@ -140,67 +140,102 @@ def test_fragile_week_horizon_only_for_top_five_touched_this_week() -> None:# ----------------------------------------------------------------------------def _recent(path: str, symbol: str | None = "fn", severity: str = "high", sha: str = "c1") -> RecentFinding:+def _recent(+ path: str,+ symbol: str | None = "fn",+ severity: str = "high",+ sha: str = "c1",+ kind: str = "coverage",+) -> RecentFinding:return RecentFinding(sha=sha,subject="feat: thing",committed_at=ANCHOR - timedelta(days=1),file_path=path,symbol=symbol,- biomarker="complex_method",+ biomarker={"shape": "complex_method", "performance": "io_in_loop"}.get(kind, "coverage_gap"),severity=severity,change_kind="introduced",line=10,+ kind=kind,)def test_regressions_up_to_three_files_are_per_file() -> None:- found = (_recent("src/a.py", "build"), _recent("src/b.py", "x"), _recent("src/b.py", "y"))+ found = (+ _recent("src/a.py", "build", kind="performance"),+ _recent("src/b.py", "x"),+ _recent("src/b.py", "y"),+ )out = _run(code.fresh_regressions, _facts(recent_findings=found))assert {a.target_path for a in out.actions} == {"src/a.py", "src/b.py"}a = next(a for a in out.actions if a.target_path == "src/a.py")assert a.tier == "act_now"assert a.horizons == ("week",)assert a.target_kind == "symbol"- assert a.title == "Simplify `build` in `src/a.py` while the change is fresh"+ assert a.title == "Fix the performance regression in `build` in `src/a.py`"+ b = next(a for a in out.actions if a.target_path == "src/b.py")+ assert b.title == "Restore the test coverage this week's changes lost in `src/b.py`"+ assert "2 coverage drops" in b.impactdef test_regressions_over_three_files_roll_up() -> None:found = (*(_recent(f"src/f{i}.py") for i in range(4)),- _recent("src/worst.py", severity="critical"),+ _recent("src/worst.py", kind="performance"),)out = _run(code.fresh_regressions, _facts(recent_findings=found))(a,) = out.actionsassert a.target_kind == "repo"+ assert a.tier == "act_now"assert a.severity == "high"assert a.includes[0] == "src/worst.py"assert set(a.includes) == {"src/worst.py", *(f"src/f{i}.py" for i in range(4))}+ assert a.title == (+ "Fix what this week's commits added: 1 performance regression and 4 coverage drops in 5 files"+ )-def test_regressions_with_many_critical_findings_top_out_at_high() -> None:- """heyputer/everything: 132 detector-critical findings in a week of commits- read as a CRITICAL action. The count stays a fact; the label stays high."""+def test_code_shape_from_the_week_is_one_maintainability_item_to_plan() -> None:+ """heyputer/everything: 132 detector-critical code-shape findings in a week+ of feature work read as a CRITICAL action, every week. They are one item to+ plan, below anything defect-class."""found = tuple(- _recent(f"src/f{i}.py", severity="critical", sha=f"s{i}") for i in range(40)+ _recent(f"src/f{i}.py", severity="critical", sha=f"s{i}", kind="shape") for i in range(40))- (rollup,) = _run(code.fresh_regressions, _facts(recent_findings=found)).actions+ for subset in (found, found[:1]):+ (a,) = _run(code.fresh_regressions, _facts(recent_findings=subset)).actions+ assert (a.tier, a.severity, a.effective_value) == ("plan", "medium", SEVERITY_VALUE["medium"])+ assert a.horizons == ("week",)+ assert dict((w.label, w.value) for w in a.why)["code-shape findings"] == str(len(subset))(single,) = _run(code.fresh_regressions, _facts(recent_findings=found[:1])).actions- for a in (rollup, single):- assert a.severity == "high"- assert dict((w.label, w.value) for w in a.why)["critical findings"] == (- "40" if a is rollup else "1"- )+ assert single.target_path == "src/f0.py"+ assert single.title == "Tidy the code shape this week's commits left: 1 finding in `src/f0.py`"++def test_shape_and_defects_in_one_week_are_separate_actions() -> None:+ found = (+ _recent("src/a.py", kind="shape"),+ _recent("src/a.py", kind="performance"),+ *(_recent(f"src/s{i}.py", kind="shape") for i in range(5)),+ )+ out = _run(code.fresh_regressions, _facts(recent_findings=found))+ by_tier = {a.tier: a for a in out.actions}+ assert set(by_tier) == {"act_now", "plan"}+ assert by_tier["act_now"].evidence_total == 1+ assert by_tier["plan"].evidence_total == 6+ assert by_tier["act_now"].action_id != by_tier["plan"].action_id-def test_a_week_with_critical_findings_still_outranks_one_without() -> None:- critical = _run(- code.fresh_regressions, _facts(recent_findings=(_recent("src/a.py", severity="critical"),))++def test_a_proven_performance_regression_outranks_lost_coverage() -> None:+ perf = _run(+ code.fresh_regressions, _facts(recent_findings=(_recent("src/a.py", kind="performance"),))).actions[0]- high = _run(code.fresh_regressions, _facts(recent_findings=(_recent("src/a.py"),))).actions[0]- assert critical.effective_value == SEVERITY_VALUE["critical"]- assert high.effective_value == SEVERITY_VALUE["high"]- assert critical.effective_priority > high.effective_priority+ cov = _run(code.fresh_regressions, _facts(recent_findings=(_recent("src/a.py"),))).actions[0]+ assert perf.effective_value == SEVERITY_VALUE["critical"]+ assert cov.effective_value == SEVERITY_VALUE["high"]+ assert perf.effective_priority > cov.effective_priority+ assert perf.severity == cov.severity == "high"def test_only_a_live_credential_is_critical() -> None:@@ -213,7 +248,9 @@ def test_only_a_live_credential_is_critical() -> None:facts = _facts([hot],recent_findings=tuple(- _recent(f"src/f{i}.py", severity="critical", sha=f"s{i}") for i in range(10)+ _recent(f"src/f{i}.py", severity="critical", sha=f"s{i}", kind=kind)+ for i in range(10)+ for kind in ("performance", "shape")),secrets=(SecretFacts("src/config.py", "hardcoded_secret", 4, 'API_KEY = "sk_live_abc1"'),),fix_first=_fix_items(),@@ -355,6 +392,17 @@ def test_fix_first_emits_now_and_next_and_leaves_later() -> None:assert len({a.action_id for a in actions}) == 2+def test_fix_first_leaves_a_cause_the_week_added_to_fresh_regressions() -> None:+ perf = _fix_items()[0]+ assert perf.kind == "perf_fix" and perf.target.symbol+ path, symbol = perf.target.file_path, perf.target.symbol.rsplit(".", 1)[-1]+ same = _recent(path, symbol, kind="performance")+ other = _recent(path, "elsewhere", kind="performance")+ for found, listed in (((same,), False), ((other,), True)):+ actions = _run(code.fix_first, _facts(fix_first=_fix_items(), recent_findings=found)).actions+ assert (perf.title in [a.title for a in actions]) is listed++def test_fix_first_unavailable_is_named() -> None:outcome = _run(code.fix_first, _facts(unavailable={"fix_first": "Not here."}))assert (outcome.status, outcome.reason) == ("unavailable", "Not here.")@@ -744,7 +792,7 @@ def test_secret_ignores_a_dummy_word_value() -> None:def test_rollup_carries_evidence_starting_with_the_worst_file_and_commands() -> None:found = (*(_recent(f"src/f{i}.py", sha=f"s{i}") for i in range(4)),- _recent("src/worst.py", severity="critical", sha="w1"),+ _recent("src/worst.py", sha="w1", kind="performance"),)(a,) = _run(code.fresh_regressions, _facts(recent_findings=found)).actionsassert a.details[0].path == "src/worst.py" == a.includes[0]diff --git a/tests/unit/persistence/test_actions_build.py b/tests/unit/persistence/test_actions_build.pyindex 3204cd0d6..3f2896580 100644--- a/tests/unit/persistence/test_actions_build.py+++ b/tests/unit/persistence/test_actions_build.py@@ -61,11 +61,14 @@ HEALTH_FINDINGS = [COMMIT_HEALTH = [{**_BY_SHA[sha], "sha": sha, "change_kind": "introduced", "biomarker_type": biomarker,- "severity": "high", "file_path": path, "symbol": symbol, "attribution_basis": basis}- for sha, biomarker, path, symbol, basis in [- ("recent", "complex_method", "src/new.py", "build", "added_lines"),- ("recent", "long_method", "src/touched.py", "x", "file_change"),- ("recent", "change_entropy", "src/hist.py", None, "added_lines"),+ "severity": severity, "file_path": path, "symbol": symbol, "attribution_basis": basis,+ "dimension": dimension}+ for sha, biomarker, path, symbol, basis, severity, dimension in [+ ("recent", "complex_method", "src/new.py", "build", "added_lines", "high", "defect"),+ ("recent", "long_method", "src/touched.py", "x", "file_change", "high", "defect"),+ ("recent", "change_entropy", "src/hist.py", None, "added_lines", "high", "defect"),+ ("recent", "n_plus_one", "src/repo.py", "load", "added_lines", "medium", "performance"),+ ("recent", "n_plus_one", "src/other.py", "f", "added_lines", "medium", "performance"),]]@@ -75,7 +78,7 @@ PERFORMANCE = ["fix_strategy": "batch_or_prefetch_io", "boundary_kind": "db","biomarker_type": "n_plus_one", "rank_position": 0,"file_path": "src/repo.py", "intervention_symbol": "src/repo.py::Repo.load",- "affected_call_sites_total": 4, "affected_files_total": 2,+ "affected_call_sites_total": 4, "affected_files_total": 2, "queue_eligible": True,"details": {"facets": {"exposure": "entry_reachable", "loop_magnitude": "grows_with_data","actionability_confidence": "medium"},"plan": {"effort_bucket": "S"}}},@@ -188,7 +191,9 @@ async def test_builder_on_rows_matches_the_sql_loader(async_session) -> None:assert built == loaded# The seed exercises every store, so equality is not over empty facts.assert built.files["src/core.py"].lead.biomarker == "complex_method"- assert [f.file_path for f in built.recent_findings] == ["src/new.py"]+ assert sorted((f.file_path, f.kind) for f in built.recent_findings) == [+ ("src/new.py", "shape"), ("src/repo.py", "performance")+ ]assert [s.file_path for s in built.secrets] == ["src/settings.py"]assert [i.target.file_path for i in built.fix_first] == ["src/repo.py", "src/core.py", "src/new.py"]assert (built.fix_commits_90d, built.active_authors_90d, len(built.dead)) == (4, 3, 3)@@ -248,7 +253,7 @@ def test_only_a_recent_authored_code_shape_regression_is_a_candidate(monkeypatchrows = [kept, *({**kept, **change} for change in dropped.values())]out = _recent_candidates(rows, week=week, files=files)- assert [row for row, _at in out] == [kept]+ assert [row for row, _at, _kind in out] == [kept]assert _recent_candidates(rows, week=None, files=files) == []# The week's own instant is inside it.edge = {**kept, "committed_at": week.isoformat()}diff --git a/tests/unit/persistence/test_actions_loader.py b/tests/unit/persistence/test_actions_loader.pyindex 5371cc7b6..07a502b3a 100644--- a/tests/unit/persistence/test_actions_loader.py+++ b/tests/unit/persistence/test_actions_loader.py@@ -106,6 +106,16 @@ async def _seed(session) -> str:biomarker_type="change_entropy", severity="high",file_path="src/hist.py", symbol=None,attribution_basis="added_lines"),+ GitCommitHealthFinding(repository_id=rid, sha="recent", change_finding_id="c4",+ change_kind="introduced", dimension="performance",+ biomarker_type="n_plus_one", severity="medium",+ file_path="src/repo.py", symbol="load",+ attribution_basis="added_lines"),+ GitCommitHealthFinding(repository_id=rid, sha="recent", change_finding_id="c5",+ change_kind="introduced", dimension="performance",+ biomarker_type="n_plus_one", severity="medium",+ file_path="src/other.py", symbol="f",+ attribution_basis="added_lines"),HealthFinding(repository_id=rid, file_path="src/new.py", biomarker_type="complex_method",severity="high", function_name="build", health_impact=1.0,line_start=10, line_end=60, details_json=DEEP),@@ -122,7 +132,7 @@ async def _seed(session) -> str:plan_state="available", fix_strategy="batch_or_prefetch_io",boundary_kind="db", biomarker_type="n_plus_one", file_path="src/repo.py",intervention_symbol="src/repo.py::Repo.load", affected_call_sites_total=4,- affected_files_total=2,+ affected_files_total=2, queue_eligible=True,details_json=json.dumps({"facets": {"exposure": "entry_reachable", "loop_magnitude": "grows_with_data","actionability_confidence": "medium"},@@ -191,12 +201,12 @@ async def test_load_actions_view_composes_every_store(async_session) -> None:rules = _by_rule(view)# Fix first names the busy bug magnet by its code-shape finding, not the- # higher-impact history marker, and the plan-ready loop; the fragile-file- # rule does not repeat the file it already names.+ # higher-impact history marker; the fragile-file rule does not repeat the+ # file it already names. The plan-ready loop this week's commit added is a+ # fresh regression (below), so Fix first does not list it again.fixes = {a["target"]["path"]: a for a in rules["fix_first"]}assert fixes["src/core.py"]["title"] == "Break up run (CCN 44)"- assert fixes["src/repo.py"]["title"] == "Batch the database calls loops make through Repo.load"- assert fixes["src/repo.py"]["effort"] == "S"+ assert "src/repo.py" not in fixesassert "fragile_file" not in rules(secret,) = rules["live_secret"]@@ -207,9 +217,15 @@ async def test_load_actions_view_composes_every_store(async_session) -> None:assert dead["evidence_total"] == 3week = _by_rule(view, "week")- (fresh,) = week["fresh_regressions"]- assert fresh["title"] == "Simplify `build` in `src/new.py` while the change is fresh"- assert fresh["evidence_ids"] == ["recent"]+ # The proven performance cause acts now; the unproven one is left out, and+ # the code-shape finding is one item to plan.+ perf, shape = sorted(week["fresh_regressions"], key=lambda a: a["tier"])+ assert (perf["tier"], perf["target"]["path"]) == ("act_now", "src/repo.py")+ assert perf["title"] == "Fix the performance regression in `load` in `src/repo.py`"+ assert (shape["tier"], shape["severity"], shape["target"]["path"]) == (+ "plan", "medium", "src/new.py"+ )+ assert shape["evidence_ids"] == ["recent"]async def test_a_missing_store_is_reported_and_the_rest_still_load(async_session) -> None: