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(refactoring): annotate plans with decisions, consumers, dead code and recent edits (#3348)
Raghav Chamadiyaf5fbf67cfe01
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.mdindex 461855c74..956ab3d98 100644--- a/docs/layers/REFACTORING.md+++ b/docs/layers/REFACTORING.md@@ -89,6 +89,13 @@ earlier step moves a symbol to another file, the later step carries`relocated_by`: its stored location is where the symbol was before, so find itagain before applying.+Plan detail also lists `risks`, one sentence each, to read before applying the+plan: an accepted decision that governs the file, callers or importers of what+the plan moves, a target nothing reaches (delete it instead), and recent commits+on the same lines. A governed plan's steps are `judgment`, and its+`blast_radius.co_change_partners` names the files that usually change with it.+A newly accepted decision shows here after the next index or update.+Break Cycle is advisory. Its plan names edges to cut, not which symbols crossthem or how to move them, so an opportunity carries it as `evidence` rather thanas a numbered step: it never leads, and never reaches Fix first. The plan itselfdiff --git a/packages/core/src/repowise/core/analysis/health/fix_first/build.py b/packages/core/src/repowise/core/analysis/health/fix_first/build.pyindex 7567c104c..a364c2f06 100644--- a/packages/core/src/repowise/core/analysis/health/fix_first/build.py+++ b/packages/core/src/repowise/core/analysis/health/fix_first/build.py@@ -60,9 +60,13 @@ from repowise.core.analysis.finding_registry import excluded_typesfrom repowise.core.analysis.health.complexity.dispatch import DISPATCH_SHAREfrom repowise.core.analysis.health.models import primary_finding, split_by_originfrom repowise.core.analysis.health.queue.eligibility import (+ DEAD_CONFIDENCE,DEFAULT_QUEUE_CONTEXTS,+ DeadSpan,Tally,Verdict,+ dead_spans,+ dead_target,finding_verdict,path_verdict,perf_fix_verdict,@@ -114,8 +118,6 @@ from .model import ()Rows = Iterable[Any]-#: A dead-code finding's ``(symbol, start line, end line)``; no symbol for a whole file.-DeadSpan = tuple[str | None, int | None, int | None]#: Measured size (CCN, lines or nesting alone, before the severity floor and#: the hot-file bonus) from which an item leads as "break up", naming the whole@@ -128,9 +130,6 @@ MAX_TESTS = 5MAX_STEPS = 5MAX_CONTEXT = 3DEFAULT_LIMIT = 10-#: A dead-code finding this sure (or marked safe to delete) makes its target-#: ``unreachable``: no plan beats deleting it.-DEAD_CONFIDENCE = 0.8#: Class-level findings: a fix names member groups, which only a plan holds.CLASS_MARKERS = frozenset({"low_cohesion", "god_class"})@@ -345,16 +344,7 @@ class _Files:``path``: the whole file, the line inside the finding's span, or, for afinding stored with no lines, the same name as written (``Old.run`` isnot ``New.run``)."""- name_here = text.short_symbol(symbol)- for name, start, end in self.dead.get(path, ()):- if name is None:- return True- if start and end:- if line and start <= line <= end:- return True- elif name_here and name == name_here:- return True- return False+ return dead_target(self.dead, path, symbol, line)def why(self,@@ -1049,15 +1039,7 @@ def _severity(severity: str | None, low: str | None) -> str:def _dead_spans(rows: Rows) -> dict[str, list[DeadSpan]]:"""Sure, open dead-code findings by file: ``(symbol, start, end)``, thesymbol ``None`` for an unreachable file."""- out: dict[str, list[DeadSpan]] = defaultdict(list)- for row in rows:- sure = _num(field(row, "confidence")) >= DEAD_CONFIDENCE or field(row, "safe_to_delete")- whole = field(row, "kind") == "unreachable_file"- name = None if whole else field(row, "symbol_name")- if _open(row) and sure and (whole or name):- span = (name, field(row, "start_line"), field(row, "end_line"))- out[field(row, "file_path")].append(span)- return dict(out)+ return dead_spans(rows)def _clone_spans(plans: Iterable[Any]) -> dict[str, list[tuple[int, int]]]:diff --git a/packages/core/src/repowise/core/analysis/health/queue/eligibility.py b/packages/core/src/repowise/core/analysis/health/queue/eligibility.pyindex e2f7f9d0d..3cd7c132c 100644--- a/packages/core/src/repowise/core/analysis/health/queue/eligibility.py+++ b/packages/core/src/repowise/core/analysis/health/queue/eligibility.py@@ -215,6 +215,48 @@ UNAUDITED_KINDS: dict[str, str] = {}+#: A dead-code finding's ``(symbol, start line, end line)``; no symbol for a whole file.+DeadSpan = tuple[str | None, int | None, int | None]+#: A dead-code finding this sure (or marked safe to delete) makes its target+#: ``unreachable``: no plan beats deleting it.+DEAD_CONFIDENCE = 0.8+++def dead_spans(rows: Iterable[Any]) -> dict[str, list[DeadSpan]]:+ """Sure, open dead-code findings by file: ``(symbol, start, end)``, the+ symbol ``None`` for an unreachable file."""+ out: dict[str, list[DeadSpan]] = {}+ for row in rows:+ sure = float(field(row, "confidence") or 0.0) >= DEAD_CONFIDENCE or field(+ row, "safe_to_delete"+ )+ whole = field(row, "kind") == "unreachable_file"+ name = None if whole else field(row, "symbol_name")+ if (field(row, "status") or "open") == "open" and sure and (whole or name):+ span = (name, field(row, "start_line"), field(row, "end_line"))+ out.setdefault(field(row, "file_path"), []).append(span)+ return out+++def dead_target(+ spans: Mapping[str, Iterable[DeadSpan]], path: str, symbol: str | None, line: int | None+) -> bool:+ """Whether a sure dead-code finding covers ``symbol`` (at ``line``) in+ ``path``: the whole file, the line inside the finding's span, or, for a+ finding stored with no lines, the same name as written (``Old.run`` is+ not ``New.run``)."""+ name_here = symbol.rsplit("::", 1)[-1] if symbol else None+ for name, start, end in spans.get(path, ()):+ if name is None:+ return True+ if start and end:+ if line and start <= line <= end:+ return True+ elif name_here and name == name_here:+ return True+ return False++class UnitFacts(Protocol):"""What the code-shape ladders read about a function beyond its row."""@@ -438,6 +480,7 @@ def perf_fix_verdict(__all__ = [+ "DEAD_CONFIDENCE","DEFAULT_QUEUE_CONTEXTS","DEFAULT_QUEUE_EXCLUSIONS","DEFAULT_QUEUE_PROOFS",@@ -453,10 +496,13 @@ __all__ = ["SMALL_CCN","SMALL_NLOC","UNAUDITED_KINDS",+ "DeadSpan","Reason","Tally","UnitFacts","Verdict",+ "dead_spans",+ "dead_target","finding_verdict","path_verdict","perf_fix_verdict",diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/annotations.py b/packages/core/src/repowise/core/analysis/health/refactoring/annotations.pynew file mode 100644index 000000000..39539796b--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/refactoring/annotations.py@@ -0,0 +1,336 @@+"""What the other layers know about a plan's target, attached once at finalize.++Code shape decides whether a plan exists. Decisions, dead code, consumers and+git history only annotate it: a governing decision makes it a judgment call,+and everything else is a ``risks[]`` line a person reads before applying it.+Nothing here creates, removes or hides a plan.++Every read is one bulk query over the whole plan set, made at finalize and+stored with the plan's rank, so plan detail serves it without a query.+"""++from __future__ import annotations++import json+from collections.abc import Mapping, Sequence+from dataclasses import dataclass, field+from datetime import datetime, timedelta+from typing import Any, Literal++from sqlalchemy import func, select+from sqlalchemy.ext.asyncio import AsyncSession++from ....co_change import parse_partners+from ....persistence.crud.analysis.dead_code import get_dead_code_findings+from ....persistence.crud.authority import governing_decisions_by_file+from ....persistence.crud.git import get_git_metadata_bulk+from ....persistence.models import GitCommit, GitFunctionBlame+from ..queue.eligibility import DeadSpan, dead_spans, dead_target+from .extract_helper import ACTIVE_CO_CHANGE+from .models import RefactoringSuggestion++RiskKind = Literal["decision", "public_api", "active_edit", "dead_code"]++#: Commits on the target inside this many days before the newest indexed+#: commit read as someone working on it now.+ACTIVE_EDIT_DAYS = 14+ACTIVE_EDIT_MIN_COMMITS = 2+#: Stored history must reach back this many windows, or a shallow clone's+#: boundary commit and a capped walk read as recent activity everywhere.+_HISTORY_WINDOWS = 2+MAX_CO_CHANGE_PARTNERS = 5+_MAX_DECISION_RISKS = 3+#: Kinds that move a symbol out of its file, so its consumers see the change.+_RELOCATING = frozenset({"split_file", "extract_class", "move_method"})+#: The blast-radius key each file-level builder writes its dependents under.+_DEPENDENTS_KEY = {"split_file": "dependent_count", "extract_class": "dependents_count"}+_BATCH = 500++FunctionCommits = tuple[int, int, tuple[str, ...]]+++@dataclass(frozen=True, slots=True)+class PlanRisk:+ kind: RiskKind+ text: str+ ref: str | None = None++ def as_dict(self) -> dict[str, Any]:+ return {"kind": self.kind, "text": self.text, "ref": self.ref}+++@dataclass(frozen=True, slots=True)+class PlanAnnotations:+ """``governed_by`` decision ids, ``risks``, and co-change partners as+ ``(file, commits shared)``, strongest first."""++ governed_by: tuple[str, ...] = ()+ risks: tuple[PlanRisk, ...] = ()+ co_change_partners: tuple[tuple[str, int], ...] = ()++ def as_dict(self) -> dict[str, Any]:+ """Only the non-empty parts; ``{}`` still says the plan was checked."""+ out: dict[str, Any] = {}+ if self.governed_by:+ out["governed_by"] = list(self.governed_by)+ if self.risks:+ out["risks"] = [risk.as_dict() for risk in self.risks]+ if self.co_change_partners:+ out["co_change_partners"] = partner_rows(self.co_change_partners)+ return out++ @classmethod+ def from_dict(cls, stored: Any) -> PlanAnnotations | None:+ """``None`` when nothing was stored: the plan was never checked."""+ if not isinstance(stored, Mapping):+ return None+ risks = tuple(+ PlanRisk(row["kind"], row["text"], row.get("ref"))+ for row in stored.get("risks") or ()+ if isinstance(row, Mapping) and row.get("kind") and row.get("text")+ )+ partners = tuple(+ (row["file_path"], int(row.get("commits") or 0))+ for row in stored.get("co_change_partners") or ()+ if isinstance(row, Mapping) and isinstance(row.get("file_path"), str)+ )+ governed = tuple(str(item) for item in stored.get("governed_by") or ())+ return cls(governed, risks, partners)+++def partner_rows(partners: Sequence[tuple[str, int]]) -> list[dict[str, Any]]:+ return [{"file_path": path, "commits": commits} for path, commits in partners]+++@dataclass(frozen=True, slots=True)+class AnnotationFacts:+ """The repository facts every plan's annotations are read from.++ ``decisions`` maps each file a governing decision names to ``(id, title)``+ pairs. ``recent`` is each commit inside the active-edit window, ``sha ->+ (committed_at, author)``; ``None`` when history is too shallow to tell+ recent from all, which is no signal rather than a quiet target. ``dead``+ is the sure dead-code spans by file (:func:`..queue.eligibility.dead_spans`).+ """++ decisions: Mapping[str, list[tuple[str, str]]] = field(default_factory=dict)+ partners: Mapping[str, tuple[tuple[str, int], ...]] = field(default_factory=dict)+ functions: Mapping[str, list[FunctionCommits]] = field(default_factory=dict)+ recent: Mapping[str, tuple[datetime, str]] | None = None+ dead: Mapping[str, list[DeadSpan]] = field(default_factory=dict)+++def annotate(suggestion: RefactoringSuggestion, facts: AnnotationFacts) -> PlanAnnotations:+ """*suggestion*'s annotations from *facts*. Pure."""+ decisions = list(facts.decisions.get(suggestion.file_path, ()))+ risks = [+ PlanRisk(+ "decision",+ f'Decision "{title}" governs this file; check it allows this change first.',+ decision_id,+ )+ for decision_id, title in decisions[:_MAX_DECISION_RISKS]+ ]+ for risk in (+ _dead_code_risk(suggestion, facts.dead),+ _public_api_risk(suggestion),+ _active_edit_risk(suggestion, facts),+ ):+ if risk is not None:+ risks.append(risk)+ return PlanAnnotations(+ governed_by=tuple(decision_id for decision_id, _ in decisions),+ risks=tuple(risks),+ co_change_partners=facts.partners.get(suggestion.file_path, ()),+ )+++def _dead_code_risk(+ suggestion: RefactoringSuggestion, dead: Mapping[str, list[DeadSpan]]+) -> PlanRisk | None:+ """A target a sure dead-code finding covers, by the rule Fix first excludes it with."""+ if not dead_target(+ dead, suggestion.file_path, suggestion.target_symbol or None, suggestion.line_start+ ):+ return None+ what = f"`{suggestion.target_symbol}`" if suggestion.target_symbol else "this file"+ return PlanRisk("dead_code", f"Nothing reaches {what}; delete it instead of refactoring it.")+++def _public_api_risk(suggestion: RefactoringSuggestion) -> PlanRisk | None:+ """Consumers of a symbol the plan moves out of its file, from its own blast radius."""+ kind = suggestion.refactoring_type+ if kind not in _RELOCATING:+ return None+ blast = suggestion.blast_radius or {}+ if kind == "move_method":+ callers = _count(blast.get("callers"))+ method = suggestion.target_symbol.rsplit(".", 1)[-1]+ if not callers or method.startswith("_"):+ return None+ to_class = (suggestion.plan or {}).get("to_class") or "its new class"+ return PlanRisk(+ "public_api",+ f"`{suggestion.target_symbol}` has {callers} caller{_s(callers)}; each has to "+ f"reach it through `{to_class}` after the move.",+ )+ dependents = _count(blast.get(_DEPENDENTS_KEY[kind]))+ if not dependents:+ return None+ files = "1 file" if dependents == 1 else f"{dependents} files"+ if kind == "split_file":+ verb = "imports" if dependents == 1 else "import"+ text = f"{files} {verb} from this file; update them unless it re-exports what moves."+ else:+ verb = "depends" if dependents == 1 else "depend"+ text = f"{files} {verb} on this file; the class they use changes shape."+ return PlanRisk("public_api", text)+++def _active_edit_risk(suggestion: RefactoringSuggestion, facts: AnnotationFacts) -> PlanRisk | None:+ """Recent commits on the functions the plan's lines sit in. Function blame is+ the finest stored grain, so a span inside a long function counts all of it."""+ recent = facts.recent+ if recent is None:+ return None+ shas = {+ sha+ for _start, _end, commits in _target_functions(suggestion, facts.functions)+ for sha in commits+ if sha in recent+ }+ if len(shas) < ACTIVE_EDIT_MIN_COMMITS:+ return None+ latest = max(shas, key=lambda sha: recent[sha][0])+ authors = sorted({recent[sha][1] for sha in shas})+ who = authors[0] if len(authors) == 1 else f"{len(authors)} authors"+ return PlanRisk(+ "active_edit",+ f"Changed in {len(shas)} commits by {who} in the {ACTIVE_EDIT_DAYS} days before "+ "the last index; check nobody is mid-change.",+ latest,+ )+++def _target_functions(+ suggestion: RefactoringSuggestion, functions: Mapping[str, list[FunctionCommits]]+) -> list[FunctionCommits]:+ """The innermost function holding the plan's lines, else every function they+ overlap; the whole file for a plan with no lines."""+ rows = functions.get(suggestion.file_path, [])+ if not suggestion.line_start:+ return rows+ start, end = suggestion.line_start, suggestion.line_end or suggestion.line_start+ overlapping = [row for row in rows if row[0] <= end and row[1] >= start]+ enclosing = [row for row in overlapping if row[0] <= start and end <= row[1]]+ return [min(enclosing, key=lambda row: row[1] - row[0])] if enclosing else overlapping+++def _count(value: Any) -> int:+ return int(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else 0+++def _s(count: int) -> str:+ return "" if count == 1 else "s"+++async def load_annotation_facts(+ session: AsyncSession, repository_id: str, suggestions: Sequence[RefactoringSuggestion]+) -> AnnotationFacts:+ """Every fact :func:`annotate` reads, for the whole plan set at once."""+ files = sorted({item.file_path for item in suggestions if item.file_path})+ metadata = await get_git_metadata_bulk(session, repository_id, files)+ dead = await get_dead_code_findings(session, repository_id)+ recent = await _recent_commits(session, repository_id)+ return AnnotationFacts(+ decisions=await governing_decisions_by_file(session, repository_id),+ partners={path: _partners(meta) for path, meta in metadata.items()},+ functions=await _function_commits(session, repository_id, files) if recent else {},+ recent=recent,+ dead=dead_spans(dead),+ )+++def _partners(meta: Any) -> tuple[tuple[str, int], ...]:+ """Files that changed with this one often enough to update together."""+ strong = sorted(+ (+ (partner.file_path, partner.support)+ for partner in parse_partners(getattr(meta, "co_change_partners_json", None))+ if partner.support >= ACTIVE_CO_CHANGE+ ),+ key=lambda pair: (-pair[1], pair[0]),+ )+ return tuple(strong[:MAX_CO_CHANGE_PARTNERS])+++def _json_list(raw: Any) -> list[str]:+ try:+ value = json.loads(raw or "[]")+ except (TypeError, ValueError):+ return []+ return [item for item in value if isinstance(item, str) and item] if isinstance(value, list) else []+++async def _recent_commits(+ session: AsyncSession, repository_id: str+) -> dict[str, tuple[datetime, str]] | None:+ """Commits in the window before the newest indexed one, or ``None`` when+ stored history does not reach back far enough to tell.++ The guard measures the span of the stored ``git_commits`` rows, which a+ commit cap can shorten; a short span reads as no signal, never as quiet.+ A shallow clone's boundary commit, which blame credits with every older+ line, is the oldest stored row (or, capped, not stored at all), so the+ span guard already keeps it two windows clear of this one.+ """+ newest, oldest = (+ await session.execute(+ select(func.max(GitCommit.committed_at), func.min(GitCommit.committed_at)).where(+ GitCommit.repository_id == repository_id+ )+ )+ ).one()+ window = timedelta(days=ACTIVE_EDIT_DAYS)+ if newest is None or oldest is None or newest - oldest < window * _HISTORY_WINDOWS:+ return None+ rows = await session.execute(+ select(GitCommit.sha, GitCommit.committed_at, GitCommit.author_name).where(+ GitCommit.repository_id == repository_id,+ GitCommit.committed_at >= newest - window,+ )+ )+ return {sha: (when, author or "unknown") for sha, when, author in rows}+++async def _function_commits(+ session: AsyncSession, repository_id: str, files: Sequence[str]+) -> dict[str, list[FunctionCommits]]:+ """Each function's blame commits, for the plans' files."""+ blame = GitFunctionBlame+ out: dict[str, list[FunctionCommits]] = {}+ for index in range(0, len(files), _BATCH):+ rows = await session.execute(+ select(blame.file_path, blame.start_line, blame.end_line, blame.commit_shas_json).where(+ blame.repository_id == repository_id,+ blame.file_path.in_(list(files[index : index + _BATCH])),+ blame.commit_shas_json.is_not(None),+ )+ )+ for path, start, end, shas in rows:+ out.setdefault(path, []).append((int(start or 0), int(end or 0), tuple(_json_list(shas))))+ return out+++__all__ = [+ "ACTIVE_EDIT_DAYS",+ "ACTIVE_EDIT_MIN_COMMITS",+ "MAX_CO_CHANGE_PARTNERS",+ "AnnotationFacts",+ "PlanAnnotations",+ "PlanRisk",+ "RiskKind",+ "annotate",+ "load_annotation_facts",+ "partner_rows",+]diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.pyindex 0ddac4cdb..a14389fad 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py@@ -52,7 +52,7 @@ them in here would publish the same work twice under two ids.from __future__ import annotations-from collections.abc import Iterable, Mapping, Sequence+from collections.abc import Collection, Iterable, Mapping, Sequencefrom dataclasses import dataclassfrom typing import Any@@ -372,6 +372,7 @@ def _step_of(plan_id: str,relocated_by: str | None,findings: Sequence[Any] | None,+ governed: Collection[str] | None = None,) -> OpportunityStep:finding_ids = Noneif findings is not None and any(field(f, "public_id") for f in findings):@@ -392,7 +393,9 @@ def _step_of(impact_delta=float(suggestion.impact_delta or 0.0),source_biomarker=suggestion.source_biomarker,relocated_by=relocated_by,- applicability=classify_step(suggestion),+ applicability=classify_step(+ suggestion, governed=None if governed is None else plan_id in governed+ ),finding_ids=finding_ids,)@@ -414,6 +417,7 @@ def _evidence_of(suggestion: RefactoringSuggestion, plan_id: str) -> Opportunitydef _sequence(step_rows: Sequence[tuple[RefactoringSuggestion, str]],findings: Sequence[Any] | None,+ governed: Collection[str] | None = None,) -> list[OpportunityStep]:"""Build the steps in execution order, marking the ones a move displaces.@@ -426,7 +430,7 @@ def _sequence(steps: list[OpportunityStep] = []relocated_by: str | None = Nonefor suggestion, plan_id in step_rows:- steps.append(_step_of(suggestion, plan_id, relocated_by, findings))+ steps.append(_step_of(suggestion, plan_id, relocated_by, findings, governed))if suggestion.refactoring_type in _RELOCATING_TYPES:relocated_by = plan_idreturn steps@@ -437,6 +441,7 @@ def _compose_one(members: Sequence[tuple[RefactoringSuggestion, str]],primary_biomarker: str | None,findings: Sequence[Any] | None,+ governed: Collection[str] | None = None,) -> RefactoringOpportunity | None:ordered = sorted(members, key=_member_sort_key)step_rows = [row for row in ordered if _is_step(row[0])]@@ -445,7 +450,7 @@ def _compose_one(# own; there is simply no composed refactoring to publish for this file.return None- steps = tuple(_sequence(step_rows, findings))+ steps = tuple(_sequence(step_rows, findings, governed))evidence = tuple(_evidence_of(suggestion, plan_id)for suggestion, plan_id in ordered@@ -508,6 +513,7 @@ def compose_opportunities(*,primary_biomarker_by_file: Mapping[str, str] | None = None,findings: Iterable[Any] | None = None,+ governed: Collection[str] | None = None,) -> list[RefactoringOpportunity]:"""Fold plans into one ranked opportunity per file.@@ -526,6 +532,10 @@ def compose_opportunities(several steps answer it; omitting them leaves both unknown and sums everystep's own impact.+ *governed* are the plan ids an accepted decision governs, found once at+ finalize; each of those steps is a judgment call (:func:`.preconditions.classify_step`).+ Omitting it leaves governance unknown on every step, never "not governed".+A plan whose ``source_biomarker`` the finding registry withholds is leftout, as a step and as evidence; the plan row itself stays stored.Ranking puts test files after production (:func:`.opportunity_rank.rank_sort_key`).@@ -551,6 +561,7 @@ def compose_opportunities(by_file[file_path],leads.get(file_path),None if findings_by_file is None else findings_by_file.get(file_path, []),+ governed,))is not Nonediff --git a/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.py b/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.pyindex eda89d777..053b0d16f 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.py@@ -38,6 +38,7 @@ JUDGMENT_REASONS = ("call_site_bindings_unproven","changes_symbol_home","detector_confidence_below_high",+ "governed_by_decision","inverts_imports_across_files","needs_design","receiver_copy_written",@@ -47,6 +48,9 @@ JUDGMENT_REASONS = ("unclassified_refactoring_type",)+# Named in ``unknowns`` when composition was not told which plans a decision governs.+_GOVERNANCE = "governed_by_decision"+# The categorical blast radius Extract Method publishes: extraction adds a# private helper and changes no signature, so nothing outside the file moves._LOCAL_SCOPE = "local"@@ -182,8 +186,16 @@ _JUDGMENT_BY_TYPE: dict[str, tuple[str, ...]] = {}-def classify_step(suggestion: RefactoringSuggestion) -> StepApplicability:- """Whether *suggestion* is safe to automate, and the facts behind that."""+def classify_step(+ suggestion: RefactoringSuggestion, *, governed: bool | None = None+) -> StepApplicability:+ """Whether *suggestion* is safe to automate, and the facts behind that.++ *governed* says an accepted decision governs the target's file: whatever+ the shape proves, a person checks the decision allows the change. ``None``+ means nobody looked (composition from detector rows), and is named in+ ``unknowns`` rather than read as "not governed".+ """facts, unknowns = step_facts(suggestion)kind = suggestion.refactoring_typeif kind == "extract_method":@@ -194,6 +206,8 @@ def classify_step(suggestion: RefactoringSuggestion) -> StepApplicability:reasons = list(_JUDGMENT_BY_TYPE.get(kind, ("unclassified_refactoring_type",)))if needs_design(suggestion):reasons.insert(0, "needs_design")+ if governed:+ reasons.append("governed_by_decision")# ``all`` over nothing is True, so a future branch that returned no reason# would promote silently. Mechanical has to be positively argued.mechanical = bool(reasons) and all(reason in MECHANICAL_REASONS for reason in reasons)@@ -201,7 +215,7 @@ def classify_step(suggestion: RefactoringSuggestion) -> StepApplicability:classification="mechanical" if mechanical else "judgment",reasons=tuple(reasons),facts=facts,- unknowns=unknowns,+ unknowns=(*unknowns, _GOVERNANCE) if governed is None else unknowns,)diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.pyindex de67b6547..d65651fcd 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py@@ -40,6 +40,7 @@ from repowise.core.analysis.test_reachability import (from repowise.core.code_origin import ship_rankfrom repowise.core.test_paths import is_test_support_path, names_test_for, paired_test_names+from .annotations import PlanAnnotations, partner_rowsfrom .models import RefactoringSuggestionRecommendationView = Literal["canonical", "file_spread"]@@ -1016,6 +1017,9 @@ class Recommendation:validation: ValidationPlan# The reads a rank-only pass made, so detailing a page reuses them.inputs: ValidationInputs | None = field(default=None, repr=False, compare=False)+ # What other layers say about the target (:mod:`.annotations`), stored at+ # finalize and served on plan detail only; ``None`` when never checked.+ annotations: PlanAnnotations | None = field(default=None, repr=False, compare=False)@propertydef id(self) -> str:@@ -1050,7 +1054,8 @@ class Recommendation:def detail_dict(self) -> dict[str, Any]:""":meth:`as_dict` for one plan read alone: a step whose checks differ- from the plan's carries its ``verify``."""+ from the plan's carries its ``verify``, and the plan carries its+ ``governed_by``, ``risks`` and co-change partners."""payload = self.as_dict()steps = payload["plan"].get("steps")if isinstance(steps, list) and self.validation.step_verify:@@ -1058,6 +1063,17 @@ class Recommendation:**payload["plan"],"steps": steps_with_verify(steps, self.validation),}+ notes = self.annotations+ if notes is None:+ # Never checked (an older or unfinalized row): absent, not "none found".+ return payload+ payload["governed_by"] = list(notes.governed_by)+ payload["risks"] = [risk.as_dict() for risk in notes.risks]+ if notes.co_change_partners:+ payload["blast_radius"] = {+ **payload["blast_radius"],+ "co_change_partners": partner_rows(notes.co_change_partners),+ }return payloaddef rank_facts(self) -> dict[str, Any]:@@ -1075,6 +1091,11 @@ class Recommendation:"blast_radius": self.suggestion.blast_radius or {},"validation": self.validation.as_dict(),**({"step_verify": self.validation.step_verify} if self.validation.step_verify else {}),+ **(+ {"annotations": self.annotations.as_dict()}+ if self.annotations is not None+ else {}+ ),}@@ -1116,6 +1137,7 @@ def stored_recommendation(row: Any) -> Recommendation | None:return Recommendation(suggestion=suggestion,validation=validation,+ annotations=PlanAnnotations.from_dict(facts.get("annotations")),**{name: facts[name] for name in _RANK_FACTS},)diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.pyindex 3fe3c88e4..832474427 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py@@ -263,7 +263,7 @@ def _summary_payload(async def _rank_live_plans(session: AsyncSession, repository_id: str) -> list[Any]:- """Rank and validate every live plan the lists can show, and store it.+ """Rank, validate and annotate every live plan the lists can show, and store it.Performance plans are not composed here, but they share the plan lists, sotheir positions come from the same pass. Plans the finding registry@@ -271,6 +271,9 @@ async def _rank_live_plans(session: AsyncSession, repository_id: str) -> list[Anis batch-sensitive, so ranking them alongside would change the tests theshown plans list."""+ import dataclasses++ from ....analysis.health.refactoring.annotations import annotate, load_annotation_factsfrom ....analysis.health.refactoring.recommendations import hydrate_recommendationsfrom .refactoring import shown_plan_predicate, store_plan_ranks@@ -284,6 +287,13 @@ async def _rank_live_plans(session: AsyncSession, repository_id: str) -> list[An)).scalars()ranked = await hydrate_recommendations(session, repository_id, list(rows), step_verify=True)+ facts = await load_annotation_facts(+ session, repository_id, [item.suggestion for item in ranked]+ )+ ranked = [+ dataclasses.replace(item, annotations=annotate(item.suggestion, facts))+ for item in ranked+ ]await store_plan_ranks(session, repository_id, ranked)return ranked@@ -348,18 +358,29 @@ async def finalize_refactoring_opportunities(.all())+ # Rank and validation are resolved once, here, for every live plan. They+ # used to be rebuilt on every request for every open plan, which is the+ # single largest cost the serving path used to carry.+ ranked = await _rank_live_plans(session, repository_id)+ # Every ranked non-performance plan is a live plan, so the lookup is total;+ # a miss raises rather than leaving a governed step mechanical.+ public_of = {row.id: row.public_id for row in live_plans}+ governed = {+ public_of[item.id]+ for item in ranked+ if item.suggestion.refactoring_type != _PERF_TYPE+ and item.annotations is not None+ and item.annotations.governed_by+ }+# Findings let each step name the diagnosis its own target answers, so an# agent round-trips from a step to it in one call.opportunities = compose_opportunities(live_plans,primary_biomarker_by_file=primary_biomarker_by_file(findings),findings=findings,+ governed=governed,)-- # Rank and validation are resolved once, here, for every live plan. They- # used to be rebuilt on every request for every open plan, which is the- # single largest cost the serving path used to carry.- ranked = await _rank_live_plans(session, repository_id)step_plan_ids = {step.plan_id for item in opportunities for step in item.steps}step_rows = [row for row in live_plans if row.public_id in step_plan_ids]validations: dict[str, dict[str, Any]] = {}diff --git a/packages/core/src/repowise/core/persistence/crud/authority.py b/packages/core/src/repowise/core/persistence/crud/authority.pyindex 870ee500c..ef515b17b 100644--- a/packages/core/src/repowise/core/persistence/crud/authority.py+++ b/packages/core/src/repowise/core/persistence/crud/authority.py@@ -49,7 +49,7 @@ from repowise.core.analysis.decisions.lifecycle import (from repowise.core.analysis.decisions.lifecycle import (record_blockers as _record_blockers,)-from repowise.core.analysis.decisions.scope import SCOPE_BASIS_STATED+from repowise.core.analysis.decisions.scope import SCOPE_BASIS_STATED, binds_to_pathsfrom ..decision_graph import (set_record_scope,@@ -79,6 +79,7 @@ __all__ = ["decision_fields","decision_signatures","dismiss_candidate",+ "governing_decisions_by_file","is_accepted","latest_acceptance","list_candidates",@@ -256,6 +257,46 @@ async def decision_currencies(return out+async def governing_decisions_by_file(+ session: AsyncSession, repository_id: str+) -> dict[str, list[tuple[str, str]]]:+ """``(id, title)`` of the governing decisions naming each file, by id.++ The bulk form of "what governs this path": accepted, at a governing+ currency (``needs_review`` included: a decision whose code moved still+ binds until someone re-reads it), with a scope basis that binds to paths.+ Files are matched as named. A record's module list is derived from those+ files, so reading it would let a decision about two files govern their+ whole directory.+ """+ records = [+ record+ for record in (+ await session.execute(+ select(DecisionRecord)+ .where(DecisionRecord.repository_id == repository_id)+ .order_by(DecisionRecord.id)+ )+ ).scalars()+ if binds_to_paths(record.scope_basis)+ ]+ currencies = await decision_currencies(session, repository_id, records)+ out: dict[str, list[tuple[str, str]]] = {}+ for record in records:+ if record.id in currencies and is_governing(currencies[record.id]):+ for path in dict.fromkeys(_named_files(record.affected_files_json)):+ out.setdefault(path, []).append((record.id, record.title))+ return out+++def _named_files(raw: Any) -> list[str]:+ try:+ value = json.loads(raw or "[]")+ except (TypeError, ValueError):+ return []+ return [item for item in value if isinstance(item, str) and item] if isinstance(value, list) else []++def _record_currency(stored: str, record: DecisionRecord) -> str:""":func:`effective_currency` for an ORM *record* stored at *stored*."""return _row_currency(stored, *(getattr(record, c.key) for c in _CURRENCY_COLUMNS))diff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.pyindex e6e0f1cad..4381c01a8 100644--- a/packages/server/src/repowise/server/routers/refactoring.py+++ b/packages/server/src/repowise/server/routers/refactoring.py@@ -93,6 +93,21 @@ class RefactoringPlanResponse(BaseModel):validation: dict[str, Any] = Field(default_factory=dict)+class PlanRiskResponse(BaseModel):+ kind: str+ text: str+ ref: str | None = None+++class RefactoringPlanDetailResponse(RefactoringPlanResponse):+ """One plan read alone: what other layers say about its target. Lists stay+ on :class:`RefactoringPlanResponse` and never carry these; both are absent+ on a plan that was never checked."""++ governed_by: list[str] | None = None+ risks: list[PlanRiskResponse] | None = None++class RefactoringTypeCount(BaseModel):type: strcount: int@@ -491,18 +506,23 @@ async def update_refactoring_settings(return _read_refactoring_settings(config, repo_id, repo_path)[email protected]("/{repo_id}/refactoring/{suggestion_id}", response_model=RefactoringPlanResponse)+ "/{repo_id}/refactoring/{suggestion_id}",+ response_model=RefactoringPlanDetailResponse,+ # Unset annotations stay absent: "never checked" is not "none found".+ response_model_exclude_unset=True,+)async def get_refactoring_plan(repo_id: str,suggestion_id: str,session: AsyncSession = Depends(get_db_session),-) -> RefactoringPlanResponse:+) -> RefactoringPlanDetailResponse:"""One plan + its blast radius detail (deep-link / drill-down target)."""row = await crud.get_refactoring_suggestion(session, repo_id, suggestion_id)if row is None:raise HTTPException(status_code=404, detail=f"refactoring plan not found: {suggestion_id}")recommendation = await _service(session, repo_id).plan_recommendation(row)- return _to_response(recommendation.detail_dict())+ return RefactoringPlanDetailResponse(**recommendation.detail_dict())class RefactoringStatusUpdate(BaseModel):diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 18c543533..1261afb03 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -2616,6 +2616,12 @@ export interface PatchCoverageTestHint {total: number;}+export interface PlanRiskResponse {+ kind: string;+ text: string;+ ref?: string | null;+}+/*** What the map is counting.*@@ -2735,6 +2741,38 @@ export interface RefactoringOpportunityStatusUpdate {status: string;}+/**+ * One plan read alone: what other layers say about its target. Lists stay+ * on :class:`RefactoringPlanResponse` and never carry these; both are absent+ * on a plan that was never checked.+ */+export interface RefactoringPlanDetailResponse {+ id: string;+ refactoring_type: string;+ file_path: string;+ target_symbol: string;+ line_start?: number | null;+ line_end?: number | null;+ plan?: Record<string, unknown>;+ evidence?: Record<string, unknown>;+ impact_delta?: number;+ effort_bucket?: string;+ blast_radius?: Record<string, unknown>;+ confidence?: string;+ source_biomarker?: string;+ benefit?: number;+ leverage?: number;+ cost?: number;+ risk?: number;+ rank_score?: number;+ dependents?: number;+ file_nloc?: number;+ file_weighted_deficit?: number;+ validation?: Record<string, unknown>;+ governed_by?: string[] | null;+ risks?: PlanRiskResponse[] | null;+}+/** Bounded product page; the legacy targets response remains unpaged. */export interface RefactoringPlanPageResponse {items: RefactoringPlanResponse[];diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.tsindex da5652e9d..c1a21ec2f 100644--- a/packages/types/src/refactoring.ts+++ b/packages/types/src/refactoring.ts@@ -58,6 +58,27 @@ export interface StepVerify {coverage: StepVerifyCoverage;}+/** What another layer says to check before applying a plan: a decision that+ * governs its file, consumers of what it moves, dead code it touches, or+ * recent commits on its lines. */+export type PlanRiskKind = "decision" | "public_api" | "active_edit" | "dead_code";++/** One sentence to read before applying the plan. `ref` is the decision id or+ * the newest commit sha, when the risk has one. */+export interface PlanRisk {+ kind: PlanRiskKind;+ text: string;+ ref: string | null;+}++/** A file that changed together with the plan's file, and how many commits+ * they shared in the history the index walked. On plan detail, in+ * `blast_radius.co_change_partners`. */+export interface PlanCoChangePartner {+ file_path: string;+ commits: number;+}+export interface RefactoringPlan {id: string;refactoring_type: RefactoringType | string;@@ -83,6 +104,12 @@ export interface RefactoringPlan {file_nloc?: number;file_weighted_deficit?: number;validation?: RecommendationValidation;+ /** Plan detail only: ids of the accepted decisions governing the file.+ * Absent when the plan was never checked (not yet re-indexed). */+ governed_by?: string[];+ /** Plan detail only: what to check before applying it. Absent when the+ * plan was never checked; empty when nothing was found. */+ risks?: PlanRisk[];}export interface RefactoringTypeCount {diff --git a/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsx b/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsxindex 7d7ff475f..d92e0e914 100644--- a/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsx+++ b/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsx@@ -320,3 +320,28 @@ describe("RefactoringDrawer with no model configured", () => {expect(screen.queryByRole("button", { name: "Generate code" })).toBeNull();});});++describe("RefactoringDrawer risks", () => {+ it("lists each risk as one line before the change", () => {+ const risks = [+ {+ kind: "decision",+ text: 'Decision "Keep the writer inline" governs this file; check it allows this change first.',+ ref: "dec1",+ },+ {+ kind: "active_edit",+ text: "Changed in 3 commits by 2 authors in the 14 days before the last index; check nobody is mid-change.",+ ref: "abc123",+ },+ ] as const;+ render(<RefactoringDrawer plan={{ ...PLAN, risks: [...risks] }} open onOpenChange={() => {}} />);+ expect(screen.getByText("Before you start")).toBeTruthy();+ for (const risk of risks) expect(screen.getByText(risk.text)).toBeTruthy();+ });++ it("renders no risk section when the plan carries none", () => {+ render(<RefactoringDrawer plan={{ ...PLAN, risks: [] }} open onOpenChange={() => {}} />);+ expect(screen.queryByText("Before you start")).toBeNull();+ });+});diff --git a/packages/ui/src/refactoring/refactoring-drawer.tsx b/packages/ui/src/refactoring/refactoring-drawer.tsxindex 726f1b7f6..e2ebbd5ee 100644--- a/packages/ui/src/refactoring/refactoring-drawer.tsx+++ b/packages/ui/src/refactoring/refactoring-drawer.tsx@@ -180,6 +180,28 @@ function DrawerBody({{contextSlot}<p className="text-sm leading-relaxed text-[var(--color-text-secondary)]">{meta.blurb}</p>+ {plan.risks && plan.risks.length > 0 ? (+ <section>+ <h4 className="mb-2.5 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ Before you start+ </h4>+ <ul className="space-y-1">+ {plan.risks.map((risk) => (+ <li+ key={`${risk.kind}:${risk.ref ?? risk.text}`}+ className="flex items-start gap-2 text-sm text-[var(--color-text-secondary)]"+ >+ <span+ className="mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--color-warning)]"+ aria-hidden+ />+ {risk.text}+ </li>+ ))}+ </ul>+ </section>+ ) : null}+<section><h4 className="mb-3 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">The changediff --git a/tests/fixtures/refactoring_corpus/golden_opportunities.json b/tests/fixtures/refactoring_corpus/golden_opportunities.jsonindex ea393f61f..0f66961b9 100644--- a/tests/fixtures/refactoring_corpus/golden_opportunities.json+++ b/tests/fixtures/refactoring_corpus/golden_opportunities.json@@ -41,7 +41,9 @@"reasons": ["dataflow_proved_local_extraction"],- "unknowns": []+ "unknowns": [+ "governed_by_decision"+ ]},"confidence": "high","effort_bucket": "S",@@ -108,7 +110,9 @@"reasons": ["dataflow_proved_local_extraction"],- "unknowns": []+ "unknowns": [+ "governed_by_decision"+ ]},"confidence": "high","effort_bucket": "S",@@ -204,7 +208,9 @@"reasons": ["dataflow_proved_local_extraction"],- "unknowns": []+ "unknowns": [+ "governed_by_decision"+ ]},"confidence": "high","effort_bucket": "S",@@ -229,7 +235,9 @@"reasons": ["dataflow_proved_local_extraction"],- "unknowns": []+ "unknowns": [+ "governed_by_decision"+ ]},"confidence": "high","effort_bucket": "S",@@ -254,7 +262,9 @@"reasons": ["dataflow_proved_local_extraction"],- "unknowns": []+ "unknowns": [+ "governed_by_decision"+ ]},"confidence": "high","effort_bucket": "S",diff --git a/tests/unit/health/test_plan_annotations.py b/tests/unit/health/test_plan_annotations.pynew file mode 100644index 000000000..4ff0f8ae3--- /dev/null+++ b/tests/unit/health/test_plan_annotations.py@@ -0,0 +1,219 @@+"""What other layers say about a plan's target: annotate only, served on detail."""++from __future__ import annotations++import dataclasses+import re+from datetime import UTC, datetime+from pathlib import Path+from typing import get_args++from repowise.core.analysis.health.queue.eligibility import dead_spans+from repowise.core.analysis.health.refactoring.annotations import (+ AnnotationFacts,+ PlanAnnotations,+ PlanRisk,+ RiskKind,+ annotate,+ partner_rows,+)+from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion+from repowise.core.analysis.health.refactoring.opportunity import compose_opportunities+from repowise.core.analysis.health.refactoring.preconditions import (+ JUDGMENT_REASONS,+ classify_step,+)+from repowise.core.analysis.health.refactoring.recommendations import (+ build_recommendations,+ stored_recommendation,+)++_TYPES = Path(__file__).resolve().parents[3] / "packages" / "types" / "src" / "refactoring.ts"+_WHEN = datetime(2026, 10, 1, tzinfo=UTC)+++def plan(kind: str = "extract_method", **kwargs) -> RefactoringSuggestion:+ payload = {+ "refactoring_type": kind,+ "file_path": "svc/orders.py",+ "target_symbol": "handle",+ "line_start": 20,+ "line_end": 30,+ "plan": {},+ "evidence": {},+ "impact_delta": 1.0,+ "effort_bucket": "S",+ "blast_radius": {"scope": "local"},+ "confidence": "high",+ "source_biomarker": "large_method",+ }+ payload.update(kwargs)+ return RefactoringSuggestion(**payload)+++def annotate_any(item: RefactoringSuggestion, facts: AnnotationFacts) -> bool:+ notes = annotate(item, facts)+ return bool(notes.governed_by or notes.risks or notes.co_change_partners)+++def kinds(notes: PlanAnnotations) -> list[str]:+ return [risk.kind for risk in notes.risks]+++def test_a_decision_naming_the_file_governs_the_plan() -> None:+ facts = AnnotationFacts(decisions={"svc/orders.py": [("d1", "Keep handlers flat")]})+ notes = annotate(plan(), facts)+ assert notes.governed_by == ("d1",)+ assert notes.risks == (+ PlanRisk(+ "decision",+ 'Decision "Keep handlers flat" governs this file; check it allows this change first.',+ "d1",+ ),+ )+ # A module derived from a decision's files does not govern its other files.+ assert not annotate_any(plan(), AnnotationFacts(decisions={"svc": [("d1", "Keep handlers flat")]}))+++def test_a_dead_target_says_delete_it_by_the_fix_first_rule() -> None:+ rows = [+ {+ "kind": "unused_function",+ "file_path": "svc/orders.py",+ "symbol_name": "handle",+ "start_line": 18,+ "end_line": 40,+ "confidence": 0.9,+ "safe_to_delete": False,+ "status": "open",+ }+ ]+ notes = annotate(plan(), AnnotationFacts(dead=dead_spans(rows)))+ assert notes.risks[0].text == "Nothing reaches `handle`; delete it instead of refactoring it."+ # A finding below the sure bar is not a dead target.+ unsure = dead_spans([{**rows[0], "confidence": 0.5}])+ assert not annotate_any(plan(), AnnotationFacts(dead=unsure))+++def test_moving_a_public_method_names_its_callers() -> None:+ moved = plan(+ "move_method",+ target_symbol="Order.total",+ plan={"to_class": "Pricing"},+ blast_radius={"callers": 3},+ )+ notes = annotate(moved, AnnotationFacts())+ assert kinds(notes) == ["public_api"]+ assert "3 callers" in notes.risks[0].text and "`Pricing`" in notes.risks[0].text+ private = plan("move_method", target_symbol="Order._total", blast_radius={"callers": 3})+ assert not annotate_any(private, AnnotationFacts())+ # A split names its importers; a local extraction moves nothing out.+ split = plan("split_file", line_start=None, blast_radius={"dependent_count": 1})+ assert annotate(split, AnnotationFacts()).risks[0].text.startswith("1 file imports from")+ assert not annotate_any(plan(blast_radius={"callers": 9}), AnnotationFacts())+++def _recent(*shas: str) -> dict[str, tuple[datetime, str]]:+ return {sha: (_WHEN, f"author-{index % 2}") for index, sha in enumerate(shas)}+++def test_recent_commits_on_the_innermost_function_read_as_an_active_edit() -> None:+ functions = {+ "svc/orders.py": [+ (1, 100, ("a", "b", "old")), # the module-level wrapper+ (15, 35, ("c", "d")), # the function holding lines 20-30+ ]+ }+ notes = annotate(plan(), AnnotationFacts(functions=functions, recent=_recent("a", "b", "c", "d")))+ assert kinds(notes) == ["active_edit"]+ assert notes.risks[0].text.startswith("Changed in 2 commits by 2 authors")+ one = annotate(plan(), AnnotationFacts(functions=functions, recent=_recent("c")))+ assert not one.risks+++def test_shallow_history_gives_no_active_edit_signal() -> None:+ functions = {"svc/orders.py": [(15, 35, ("c", "d"))]}+ assert not annotate_any(plan(), AnnotationFacts(functions=functions, recent=None))+++def test_annotations_round_trip_through_the_stored_rank() -> None:+ notes = PlanAnnotations(+ governed_by=("d1",),+ risks=(PlanRisk("decision", "text", "d1"),),+ co_change_partners=(("svc/models.py", 7),),+ )+ assert PlanAnnotations.from_dict(notes.as_dict()) == notes+ # Checked with nothing found is stored as ``{}``; never checked as nothing.+ assert PlanAnnotations().as_dict() == {}+ assert PlanAnnotations.from_dict({}) == PlanAnnotations()+ assert PlanAnnotations.from_dict(None) is None+++def test_plan_detail_carries_annotations_and_lists_do_not() -> None:+ (item,) = build_recommendations([plan()])+ item.suggestion.id = "row-1" # type: ignore[attr-defined]+ notes = PlanAnnotations(+ governed_by=("d1",),+ risks=(PlanRisk("decision", "text", "d1"),),+ co_change_partners=(("svc/models.py", 7),),+ )+++ annotated = dataclasses.replace(item, annotations=notes)+ assert annotated.as_dict() == item.as_dict()+ detail = annotated.detail_dict()+ assert detail["governed_by"] == ["d1"]+ assert detail["risks"] == [{"kind": "decision", "text": "text", "ref": "d1"}]+ assert detail["blast_radius"]["co_change_partners"] == partner_rows(notes.co_change_partners)+ assert "co_change_partners" not in annotated.as_dict()["blast_radius"]++ # Never checked: absent, so it cannot read as "checked, nothing found".+ bare = item.detail_dict()+ assert "governed_by" not in bare and "risks" not in bare+ checked = dataclasses.replace(item, annotations=PlanAnnotations()).detail_dict()+ assert checked["governed_by"] == [] and checked["risks"] == []++ row = {"id": "row-1", **item.as_dict(), "rank_json": annotated.rank_facts()}+ assert stored_recommendation(row).detail_dict() == detail # type: ignore[union-attr]+ unannotated = {"id": "row-1", **item.as_dict(), "rank_json": item.rank_facts()}+ assert "annotations" not in item.rank_facts()+ older = stored_recommendation(unannotated)+ assert older is not None and older.annotations is None+ assert "risks" not in older.detail_dict()+++def test_a_governing_decision_makes_a_proved_extraction_a_judgment_call() -> None:+ assert classify_step(plan(), governed=False).classification == "mechanical"+ assert "governed_by_decision" not in classify_step(plan(), governed=False).unknowns+ governed = classify_step(plan(), governed=True)+ assert governed.classification == "judgment"+ assert governed.reasons == ("dataflow_proved_local_extraction", "governed_by_decision")+ assert "governed_by_decision" in JUDGMENT_REASONS++ (free,) = compose_opportunities([plan()], governed=set())+ plan_id = free.steps[0].plan_id+ (held,) = compose_opportunities([plan()], governed={plan_id})+ assert free.mechanical_steps == 1+ assert held.mechanical_steps == 0+ assert held.steps[0].applicability.reasons[-1] == "governed_by_decision"+++def test_the_risk_contract_matches_the_typescript_one() -> None:+ source = _TYPES.read_text(encoding="utf-8")+ union = re.search(r"type PlanRiskKind\s*=\s*([^;]+);", source)+ assert union and set(re.findall(r'"([^"]+)"', union.group(1))) == set(get_args(RiskKind))+ for name, sample in (+ ("PlanRisk", PlanRisk("decision", "t").as_dict()),+ ("PlanCoChangePartner", partner_rows([("a.py", 1)])[0]),+ ):+ body = re.search(rf"interface {name} \{{([^}}]+)\}}", source)+ assert body, name+ assert set(re.findall(r"^\s*(\w+)\??:", body.group(1), re.MULTILINE)) == set(sample)+++def test_composition_not_told_about_decisions_leaves_governance_unknown() -> None:+ """The CLI composes detector rows with no decisions read: unknown, not "not governed"."""+ (live,) = compose_opportunities([plan()])+ step = live.steps[0].applicability+ assert "governed_by_decision" in step.unknowns+ assert "governed_by_decision" not in step.reasonsdiff --git a/tests/unit/persistence/test_governing_decisions_by_file.py b/tests/unit/persistence/test_governing_decisions_by_file.pynew file mode 100644index 000000000..f673d1a96--- /dev/null+++ b/tests/unit/persistence/test_governing_decisions_by_file.py@@ -0,0 +1,88 @@+"""Which decisions govern a file, read in bulk for the refactoring plan annotations."""++from __future__ import annotations++from sqlalchemy import select++from repowise.core.persistence.crud import bulk_upsert_decisions+from repowise.core.persistence.crud.authority import (+ accept_decision,+ current_currency,+ dismiss_candidate,+ governing_decisions_by_file,+ return_to_review,+ supersede_decision,+)+from repowise.core.persistence.models import DecisionRecord+from tests.unit.persistence.helpers import insert_repo+from tests.unit.persistence.test_decision_authority import _dict+++async def test_only_accepted_governing_decisions_govern_the_files_they_name(async_session):+ repo = await insert_repo(async_session)+ titles = ("Active", "Review", "Candidate", "Superseded", "Withdrawn", "Footprint", "Successor")+ await bulk_upsert_decisions(+ async_session,+ repo.id,+ [+ _dict(title, affected_files=[f"src/{t}.py"], evidence_file=f"src/{t}.py")+ for title in titles+ if (t := title.lower())+ ],+ )+ stored = (+ await async_session.execute(+ select(DecisionRecord).where(DecisionRecord.repository_id == repo.id)+ )+ ).scalars()+ by_title = {record.title: record for record in stored}+ rows = [by_title[title] for title in titles]+ active, review, _candidate, superseded, withdrawn, footprint, successor = rows+ for record in (active, review, superseded, withdrawn, footprint, successor):+ await accept_decision(async_session, record, accepter="tester")+ await return_to_review(async_session, review, accepter="tester")+ await supersede_decision(async_session, superseded, successor_id=successor.id, accepter="tester")+ await dismiss_candidate(async_session, withdrawn, accepter="tester")+ # A commit's footprint is not a claim about those files.+ footprint.scope_basis = "commit_footprint"+ await async_session.flush()+ assert await current_currency(async_session, review) == "needs_review"++ governed = await governing_decisions_by_file(async_session, repo.id)++ # ``needs_review`` still binds: its code moved, so it is re-read, not ignored.+ assert set(governed) == {"src/active.py", "src/review.py", "src/successor.py"}+ assert governed["src/active.py"] == [(active.id, "Active")]+ # Files are named exactly; the derived module does not govern its directory.+ assert "src" not in governed+++async def test_recent_commits_leave_out_a_shallow_boundary_and_short_history(async_session):+ from datetime import UTC, datetime, timedelta++ from repowise.core.analysis.health.refactoring.annotations import load_annotation_facts+ from repowise.core.persistence.models import GitCommit++ repo = await insert_repo(async_session)+ head = datetime(2026, 10, 1, tzinfo=UTC)++ def commit(sha: str, days_ago: int) -> GitCommit:+ return GitCommit(+ repository_id=repo.id,+ sha=sha,+ author_name="dev",+ author_email="[email protected]",+ committed_at=head - timedelta(days=days_ago),+ )++ async_session.add_all([commit("new", 0), commit("old", 10)])+ await async_session.flush()+ # Ten days of stored history cannot tell recent from all of it.+ assert (await load_annotation_facts(async_session, repo.id, [])).recent is None++ # A depth-limited clone: its boundary commit is the oldest row, which blame+ # credits with every older line; the span guard keeps it out of the window.+ async_session.add(commit("boundary", 30))+ await async_session.flush()+ recent = (await load_annotation_facts(async_session, repo.id, [])).recent+ assert recent is not None and set(recent) == {"new", "old"}diff --git a/tests/unit/server/test_refactoring_plan_annotations.py b/tests/unit/server/test_refactoring_plan_annotations.pynew file mode 100644index 000000000..24b31f70d--- /dev/null+++ b/tests/unit/server/test_refactoring_plan_annotations.py@@ -0,0 +1,123 @@+"""Finalize annotates plans before composing them, without changing the composition.++Runs with the finding registry as shipped, so the seeded ``dry_violation``+clone plan is withheld: it is neither ranked, annotated, nor composed.+"""++from __future__ import annotations++import pytest+from httpx import AsyncClient+from sqlalchemy import select++from repowise.core.analysis.health.refactoring import opportunity+from repowise.core.persistence import crud+from repowise.core.persistence.crud.analysis.refactoring import _refactoring_row_kwargs+from repowise.core.persistence.crud.authority import accept_decision+from repowise.core.persistence.models import DecisionRecord, RefactoringSuggestion++from .test_refactoring import _seed+from .test_refactoring_plan_rank import _EXTRA+++async def _seed_plans(client: AsyncClient, app) -> str:+ repo_id = await _seed(client, app)+ async with app.state.session_factory() as session:+ for plan in _EXTRA:+ session.add(RefactoringSuggestion(**_refactoring_row_kwargs(plan, repo_id)))+ await session.commit()+ return repo_id+++def _capture(monkeypatch: pytest.MonkeyPatch) -> list[tuple[dict, list]]:+ calls: list[tuple[dict, list]] = []+ compose = opportunity.compose_opportunities++ def recording(rows, **kwargs):+ result = compose(rows, **kwargs)+ calls.append((kwargs, result))+ return result++ monkeypatch.setattr(opportunity, "compose_opportunities", recording)+ return calls+++async def _plan_rows(app, repo_id: str) -> list[RefactoringSuggestion]:+ async with app.state.session_factory() as session:+ return list(+ (+ await session.execute(+ select(RefactoringSuggestion).where(+ RefactoringSuggestion.repository_id == repo_id,+ RefactoringSuggestion.refactoring_type != "performance_fix",+ )+ )+ ).scalars()+ )+++async def test_ranking_first_composes_the_same_opportunities_in_the_same_order(+ client: AsyncClient, app, monkeypatch: pytest.MonkeyPatch+) -> None:+ repo_id = await _seed_plans(client, app)+ before = opportunity.compose_opportunities(await _plan_rows(app, repo_id), governed=set())+ calls = _capture(monkeypatch)+ async with app.state.session_factory() as session:+ await crud.finalize_refactoring_opportunities(session, repo_id)+ await session.commit()++ ((kwargs, composed),) = calls+ assert kwargs["governed"] == set()+ # No findings are seeded, so the rows alone decide ids and order.+ assert [item.opportunity_id for item in composed] == [item.opportunity_id for item in before]+ assert [item.steps for item in composed] == [item.steps for item in before]+++async def test_a_withheld_plan_is_neither_annotated_nor_composed_nor_governed(+ client: AsyncClient, app, monkeypatch: pytest.MonkeyPatch+) -> None:+ repo_id = await _seed_plans(client, app)+ async with app.state.session_factory() as session:+ await crud.bulk_upsert_decisions(+ session,+ repo_id,+ [+ {+ "title": "The hub stays one module",+ "decision": "The hub stays one module",+ "rationale": "import order is load-bearing",+ "source": "session",+ "status": "proposed",+ "affected_files": ["pkg/hub.py"],+ "evidence_file": "pkg/hub.py",+ "confidence": 0.9,+ "verification": "exact",+ "source_quote": "The hub stays one module",+ }+ ],+ )+ record = (await session.execute(select(DecisionRecord))).scalar_one()+ await accept_decision(session, record, accepter="tester")+ await session.commit()+ calls = _capture(monkeypatch)+ async with app.state.session_factory() as session:+ await crud.finalize_refactoring_opportunities(session, repo_id)+ await session.commit()++ rows = {row.public_id: row for row in await _plan_rows(app, repo_id)}+ withheld = [row for row in rows.values() if row.source_biomarker == "dry_violation"]+ assert withheld and all(row.rank_json is None for row in withheld)+ ((kwargs, composed),) = calls+ governed = kwargs["governed"]+ # The shown structural plan on the governed file is governed; the withheld+ # clone plan on the same file is not, and is in no opportunity.+ assert governed == {+ public_id+ for public_id, row in rows.items()+ if row.file_path == "pkg/hub.py" and row.rank_json is not None+ }+ assert governed and not governed & {row.public_id for row in withheld}+ composed_ids = {+ item.plan_id for opp in composed for item in (*opp.steps, *opp.evidence)+ }+ assert not composed_ids & {row.public_id for row in withheld}diff --git a/tests/unit/server/test_refactoring_plan_rank.py b/tests/unit/server/test_refactoring_plan_rank.pyindex 71bd42b67..9fcec7796 100644--- a/tests/unit/server/test_refactoring_plan_rank.py+++ b/tests/unit/server/test_refactoring_plan_rank.py@@ -7,6 +7,8 @@ is cleared, and the two responses must be identical.from __future__ import annotations+import json+import pytestfrom httpx import AsyncClientfrom sqlalchemy import select, update@@ -186,6 +188,9 @@ async def test_one_plan_reads_its_stored_rank(_no_live_ranking(monkeypatch)for plan in listed:detail = (await client.get(f"/api/repos/{repo_id}/refactoring/{plan['id']}")).json()+ # Detail adds what other layers say about the target; no decision here.+ assert detail.pop("governed_by") == []+ assert all(risk["kind"] != "decision" for risk in detail.pop("risks"))assert detail == plan# Code generation reads its plan the same way.@@ -318,3 +323,67 @@ async def _ids(session, repo_id: str) -> list[str]:)).scalars())+++async def test_an_accepted_decision_governs_the_plans_on_its_file(+ client: AsyncClient, app, monkeypatch: pytest.MonkeyPatch+) -> None:+ from repowise.core.persistence.crud import bulk_upsert_decisions+ from repowise.core.persistence.crud.authority import accept_decision+ from repowise.core.persistence.models import DecisionRecord, RefactoringOpportunity++ repo_id = await _seed_ranked(client, app)+ async with app.state.session_factory() as session:+ await bulk_upsert_decisions(+ session,+ repo_id,+ [+ {+ "title": "Keep the parser in one function",+ "decision": "Keep the parser in one function",+ "rationale": "profiling showed the call overhead",+ "source": "session",+ "status": "proposed",+ "affected_files": ["pkg/leaf.py"],+ "evidence_file": "pkg/leaf.py",+ "confidence": 0.9,+ "verification": "exact",+ "source_quote": "Keep the parser in one function",+ }+ ],+ )+ record = (+ await session.execute(+ select(DecisionRecord).where(DecisionRecord.repository_id == repo_id)+ )+ ).scalar_one()+ await accept_decision(session, record, accepter="tester")+ await crud.finalize_refactoring_opportunities(session, repo_id)+ await session.commit()+ steps = [+ step+ for row in (+ await session.execute(+ select(RefactoringOpportunity).where(+ RefactoringOpportunity.repository_id == repo_id+ )+ )+ ).scalars()+ for step in json.loads(row.details_json or "{}").get("steps", [])+ ]++ _no_live_ranking(monkeypatch)+ listed = (await client.get(f"/api/repos/{repo_id}/refactoring/targets")).json()["plans"]+ for plan in listed:+ assert "governed_by" not in plan and "risks" not in plan+ detail = (await client.get(f"/api/repos/{repo_id}/refactoring/{plan['id']}")).json()+ governed = plan["file_path"] == "pkg/leaf.py"+ assert detail["governed_by"] == ([record.id] if governed else [])+ decisions = [r for r in detail["risks"] if r["kind"] == "decision"]+ assert [r["ref"] for r in decisions] == ([record.id] if governed else [])+ leaf = [step for step in steps if step["file_path"] == "pkg/leaf.py"]+ assert leaf and all(+ step["applicability"]["classification"] == "judgment"+ and "governed_by_decision" in step["applicability"]["reasons"]+ for step in leaf+ )