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): compose per-file opportunities from plans (#1988)
Raghav Chamadiyaa44af9bb45c0
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/base.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/base.pyindex de46f0ed7..be5b36d35 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/base.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/base.py@@ -157,6 +157,37 @@ class BaseDefUseDialect:override for their function/lambda node kinds."""return False+ # Boundary kinds that additionally bind their own name in the ENCLOSING+ # scope. Empty by default, and deliberately not inferred from "the node has+ # a name field": in JS a named function *expression* has one and binds it+ # only inside itself, so inferring would inject a definition of a name the+ # enclosing scope never gets, which is worse than the omission this exists+ # to fix. Each dialect names its own binders.+ enclosing_binder_kinds: frozenset[str] = frozenset()++ def boundary_def(self, node: Node, defs: list[Occurrence]) -> None:+ """Record the name a nested scope binds in the *enclosing* scope.++ A nested function is two things at once: a scope whose reads belong to+ it and not to us, and, in some languages, a plain local binding of its+ own name right here. Skipping the whole node handles the first and used+ to lose the second, so a span calling a sibling closure saw no+ definition of it, the name never entered the extraction's IN set, and+ the lifted helper called something that was not passed to it. Measured+ on this repo's own ranked head: the Python function+ ``ingestion/dynamic_hints/cpp.py::extract`` offered a span calling a+ local ``_emit`` with ``_emit`` absent from its parameters.++ An anonymous scope - a lambda, a closure literal - binds nothing here,+ and neither does a construct whose name is scoped to itself; both are+ left alone via :data:`enclosing_binder_kinds`.+ """+ if node.type not in self.enclosing_binder_kinds:+ return+ name = node.child_by_field_name("name")+ if name is not None and name.type in self.identifier_kinds:+ defs.append(self._occ(name))+# -- defaults a subclass may override -------------------------------------def parameter_defs(self, fn_node: Node) -> tuple[Occurrence, ...]:diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/cpp.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/cpp.pyindex a5f6f6edf..b1e6857dd 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/cpp.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/cpp.py@@ -220,6 +220,7 @@ class CppDefUseDialect(BaseDefUseDialect):uses.append(self._occ(node))returnif self._is_scope_boundary(node):+ self.boundary_def(node, defs)returnfor child in node.named_children:self._process(child, defs, uses)diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/go.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/go.pyindex 9959d6ec2..b430d761e 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/go.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/go.py@@ -138,6 +138,7 @@ class GoDefUseDialect(BaseDefUseDialect):uses.append(self._occ(node))returnif self._is_scope_boundary(node):+ self.boundary_def(node, defs)returnfor child in node.named_children:self._process(child, defs, uses)diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.pyindex 4cae89d91..da17423e7 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py@@ -181,6 +181,7 @@ class JavaDefUseDialect(BaseDefUseDialect):uses.append(self._occ(node))returnif self._is_scope_boundary(node):+ self.boundary_def(node, defs)returnfor child in node.named_children:self._process(child, defs, uses)diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.pyindex 09a3e44b6..4f35a53d8 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.py@@ -47,6 +47,9 @@ class PythonDefUseDialect(BaseDefUseDialect):member_access_kinds = frozenset({"attribute"})keyword_kinds = frozenset({"keyword_argument"})+ # A nested ``def`` is visible in the enclosing scope from its statement on.+ enclosing_binder_kinds = frozenset({"function_definition", "async_function_definition"})+def _is_scope_boundary(self, node: Node) -> bool:return node.type in _SCOPE_BOUNDARIES@@ -142,6 +145,7 @@ class PythonDefUseDialect(BaseDefUseDialect):uses.append(self._occ(node))returnif self._is_scope_boundary(node):+ self.boundary_def(node, defs)returnfor child in node.named_children:self._process(child, defs, uses)diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/rust.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/rust.pyindex d6b1fe156..6c1c1c3f6 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/rust.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/rust.py@@ -98,6 +98,9 @@ class RustDefUseDialect(BaseDefUseDialect):# Python receivers are plain identifiers, so only Rust needs the addition).identifier_kinds = frozenset({"identifier", "self"})+ # A nested ``fn`` item is visible in the enclosing block, like Python.+ enclosing_binder_kinds = frozenset({"function_item"})+def _is_scope_boundary(self, node: Node) -> bool:return node.type in _SCOPE_BOUNDARIES@@ -210,6 +213,7 @@ class RustDefUseDialect(BaseDefUseDialect):uses.append(self._occ(node))returnif self._is_scope_boundary(node):+ self.boundary_def(node, defs)returnfor child in node.named_children:self._process(child, defs, uses)diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/ts_js.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/ts_js.pyindex 01371152e..71058f788 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/ts_js.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/ts_js.py@@ -66,6 +66,14 @@ class TsJsDefUseDialect(BaseDefUseDialect):# a write-target position, so counting it as an identifier only adds reads.identifier_kinds = frozenset({"identifier", "shorthand_property_identifier"})+ # Only the *statement* forms bind in the enclosing scope, and they hoist.+ # A named function expression binds its name inside its own body only, so+ # recording it here would shadow an unrelated enclosing variable of the+ # same name - the ``var fib = function fib(n) {...}`` idiom exactly.+ enclosing_binder_kinds = frozenset(+ {"function_declaration", "generator_function_declaration"}+ )+def _is_scope_boundary(self, node: Node) -> bool:return node.type in _SCOPE_BOUNDARIES@@ -151,6 +159,7 @@ class TsJsDefUseDialect(BaseDefUseDialect):uses.append(self._occ(node))returnif self._is_scope_boundary(node):+ self.boundary_def(node, defs)returnfor child in node.named_children:self._process(child, defs, uses)diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py b/packages/core/src/repowise/core/analysis/health/dataflow/slice.pyindex a6341d402..4431e94e5 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py@@ -94,6 +94,7 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[body_container = _unwrap_container(body, lmap.block_kinds)def_lines, use_lines = _var_lines(analysis.def_use)+ hoisted = _hoisted_bindings(def_lines, use_lines)decision_kinds = (lmap.branch_kinds| lmap.loop_kinds@@ -127,10 +128,17 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[if n >= _MIN_STMTS:dec_prefix = [0]jump_prefix = [0]+ # Named-nested-function count rides the same prefix sums, for the+ # same reason: the check is a subtree walk, and asking it per+ # candidate span would put the O(n^2 * subtree) cost straight back.+ nested_prefix = [0]for st in stmts:d, jmp = _span_metrics([st], decision_kinds, jump_kinds, scope_kinds)dec_prefix.append(dec_prefix[-1] + d)jump_prefix.append(jump_prefix[-1] + (1 if jmp else 0))+ nested_prefix.append(+ nested_prefix[-1] + (1 if _holds_a_named_nested_function([st], lmap) else 0)+ )for i in range(n):for j in range(i, n):evaluated += 1@@ -163,6 +171,10 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[continueif not _outs_definitely_assigned(span, returns, def_lines, lmap):continue+ if any(s <= first_def <= e and first_use < s for first_def, first_use in hoisted):+ continue+ if nested_prefix[j + 1] > nested_prefix[i]:+ continueif loop is not None and not _loop_carry_free(span, loop, s, e, def_lines, use_lines, lmap):@@ -243,6 +255,70 @@ def _infer_in_out(return tuple(params), tuple(returns)+def _holds_a_named_nested_function(span: list[Node], lmap: LanguageNodeMap) -> bool:+ """True when the span contains a nested function that binds its own name.++ Def/use is computed per function and deliberately does not descend into a+ nested scope, so a sibling closure's call to such a helper is invisible+ here. Lifting the declaration out of the scope moves the binding away from+ those callers, and nothing in the facts would show it.++ A named nested function exists to be called from elsewhere in its scope, so+ the safe answer is to refuse rather than to guess at its callers. An+ anonymous lambda bound to a local is a value and stays governed by the+ ordinary IN/OUT rules. Measured on this repo's ranked head:+ ``vscode/src/features/changeIntel.ts::registerChangeIntel`` offered its whole+ ``render`` declaration while a sibling closure called it.+ """+ kinds = lmap.function_kinds+ if not kinds:+ return False+ for st in span:+ stack = [st]+ while stack:+ node = stack.pop()+ if node.type in kinds and node.child_by_field_name("name") is not None:+ return True+ stack.extend(node.children)+ return False+++def _hoisted_bindings(+ def_lines: dict[str, list[int]],+ use_lines: dict[str, list[int]],+) -> list[tuple[int, int]]:+ """First-definition lines of names the function reads before defining them.++ A read before the only definition of a name can only work by hoisting: a+ JS/TS ``function foo()`` declaration is visible from the top of its scope,+ so code above it calls it. A span holding that definition cannot be lifted -+ an OUT cannot express it, because the value has to exist *before* the span+ runs, not after - so :func:`find_extractions` refuses any span containing+ one of these lines.++ Returns ``(first_def, first_use)`` pairs. A span refuses when its range holds+ a ``first_def`` whose ``first_use`` sits *above* the span: the earlier read+ has no earlier definition to answer it, so the span holds the only one.+ A read that sits inside the span, before the definition, is a different+ shape and is left to the loop-carried gate.++ Computed once per function because the shape is rare (usually no name+ qualifies at all), and asking per candidate span meant walking every+ variable thousands of times. Both lists are sorted by :func:`_var_lines`,+ so the first entry of each is the earliest.++ Measured on this repo's ranked head:+ ``vscode/src/features/changeIntel.ts::registerChangeIntel`` offered its whole+ ``render`` declaration as a span while ``render(partners)`` sat above it.+ """+ hoisted: list[tuple[int, int]] = []+ for var, defs in def_lines.items():+ uses = use_lines.get(var)+ if defs and uses and uses[0] < defs[0]:+ hoisted.append((defs[0], uses[0]))+ return sorted(hoisted)++def _outs_definitely_assigned(span: list[Node],returns: tuple[str, ...],@@ -385,19 +461,32 @@ def _loop_carry_free() -> bool:"""True when a span nested in *loop* carries no state between iterations.- Two shapes are refused. A variable the span writes that is also read- earlier in the same loop is loop-carried: the helper would see this- iteration's value where the loop sees the previous one. And a call on a- name the loop header reads mutates the state the loop iterates over- (``entries.remove(entry)`` inside ``for entry in entries``), which an- IN/OUT signature cannot express at all.+ Two shapes are refused. A variable the span writes that the loop also reads+ without the span having written it first is loop-carried: that read takes+ the previous iteration's value, and lifting the write into a helper whose+ result is discarded silently drops it.++ The read does not have to sit above the span. ``clojure.py::_spec_namespaces``+ reads ``expect_ns`` and then writes it, both inside one candidate span, in a+ ``while`` loop: textually the read precedes the write, so nothing follows+ the span to make the variable an OUT, and the state machine breaks on the+ next iteration. Testing only for reads above the span missed it, so the test+ is "read with no in-span write before it", which subsumes the old one.++ Also refused: a call on a name the loop header reads, which mutates the+ state the loop iterates over (``entries.remove(entry)`` inside+ ``for entry in entries``), and which an IN/OUT signature cannot express."""loop_start = loop.start_point[0] + 1for var, lines in def_lines.items():- if not any(s <= ln <= e for ln in lines):+ in_span_writes = [ln for ln in lines if s <= ln <= e]+ if not in_span_writes:continue- if any(loop_start <= ln < s for ln in use_lines.get(var, [])):- return False+ for read in use_lines.get(var, []):+ if not loop_start <= read <= e:+ continue+ if not any(write < read for write in in_span_writes):+ return Falsecarried = _loop_header_names(loop, lmap)if not carried:diff --git a/packages/core/src/repowise/core/analysis/health/models.py b/packages/core/src/repowise/core/analysis/health/models.pyindex 722a92415..dfe5ed855 100644--- a/packages/core/src/repowise/core/analysis/health/models.py+++ b/packages/core/src/repowise/core/analysis/health/models.py@@ -7,6 +7,7 @@ counterparts in ``persistence/models.py`` (``HealthFinding``,from __future__ import annotations+from collections.abc import Iterable, Sequencefrom dataclasses import dataclass, fieldfrom datetime import datetimefrom enum import StrEnum@@ -39,6 +40,41 @@ class HealthFindingData:dimension: str = "defect"+def primary_finding(findings: Sequence[Any]) -> Any | None:+ """The one finding that best names why a file is unhealthy.++ The strongest **discrete** finding wins. A continuous biomarker fires on+ every file carrying its input signal, so on a repo with coverage data+ ``coverage_gradient`` takes the max-impact tiebreak nearly everywhere: it+ led 22 of the top 50 worst files with "N% of lines uncovered", which is true+ and says nothing about why this file rather than any other. It still leads+ when it is a file's only finding.++ Extracted because the rule was written out four times - the MCP file leads,+ the REST work queue, the code-health serializers and the CLI table - and+ only the MCP copy remembered the continuous exclusion. The MCP copy and the+ refactoring composition layer read this one; the other three still hold+ their own, and adopting it would change what they lead with, which is a+ surface decision rather than a refactor. See the plan's Backlog.+ """+ from .biomarkers.registry import continuous_biomarkers++ if not findings:+ return None+ continuous = continuous_biomarkers()+ discrete = [item for item in findings if item.biomarker_type not in continuous]+ return max(discrete or findings, key=lambda item: float(item.health_impact or 0.0))+++def primary_biomarker_by_file(findings: Iterable[Any]) -> dict[str, str]:+ """Each file's dominant cause, keyed by path. See :func:`primary_finding`."""+ by_file: dict[str, list[Any]] = {}+ for finding in findings:+ by_file.setdefault(finding.file_path, []).append(finding)+ leads = {path: primary_finding(items) for path, items in by_file.items()}+ return {path: lead.biomarker_type for path, lead in leads.items() if lead is not None}++@dataclassclass HealthFileMetricData:"""Per-file aggregate. Persisted as a ``HealthFileMetric`` row."""diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py b/packages/core/src/repowise/core/analysis/health/refactoring/__init__.pyindex 7d4708b5d..e82d5de4f 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py@@ -34,7 +34,15 @@ from .models import (RefactoringContext,RefactoringSuggestion,)+from .opportunity import (+ OpportunityEvidence,+ OpportunityStep,+ RefactoringOpportunity,+ compose_opportunities,+ opportunity_status,+)from .performance_fix import PerformancePlanPolicy, performance_fix_suggestions+from .preconditions import StepApplicability, classify_stepfrom .rank import rank_suggestionsfrom .registry import (RefactoringDetector,@@ -47,15 +55,22 @@ from .registry import (__all__ = ["CONFIDENCE_LEVELS","REFACTORING_MODEL_VERSION",+ "OpportunityEvidence",+ "OpportunityStep","PerformancePlanPolicy","RefactoringContext","RefactoringDetector",+ "RefactoringOpportunity","RefactoringSuggestion",+ "StepApplicability","assign_public_ids","build_file_scc_index",+ "classify_step",+ "compose_opportunities","detect_refactorings","effort_bucket","model_state",+ "opportunity_status","performance_fix_suggestions","rank_suggestions","refactoring_kernel",diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.pyindex d663ceeee..507467855 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py@@ -56,8 +56,10 @@ _MIN_HELPER_LINES = 8# Co-change count at/above which duplication counts as actively maintained# (mirrors ``dry_violation._ACTIVE_CO_CHANGE``) — the strong, high-confidence-# smell rather than a dormant clone.-_ACTIVE_CO_CHANGE = 3+# smell rather than a dormant clone. Public because the opportunity composer+# gates the same threshold when it decides whether a clone instructs a change+# or only evidences one.+ACTIVE_CO_CHANGE = 3# Slack (lines) for treating two clone regions on this file's side as the# same block — matches the duplication merger's one-line window slack.@@ -511,7 +513,7 @@ class ExtractHelperDetector(RefactoringDetector):impact_delta=round(float(impact), 3),effort_bucket=effort_bucket(duplicated_lines),blast_radius=blast_radius,- confidence="high" if block.co_change >= _ACTIVE_CO_CHANGE else "medium",+ confidence="high" if block.co_change >= ACTIVE_CO_CHANGE else "medium",source_biomarker=_SOURCE_BIOMARKER,)diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/models.py b/packages/core/src/repowise/core/analysis/health/refactoring/models.pyindex da90817df..548d61030 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/models.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/models.py@@ -102,8 +102,18 @@ from __future__ import annotationsfrom dataclasses import dataclass, fieldfrom typing import Any-# Confidence buckets a detector may assign. Ordered low -> high; the surface-# layers may filter on a ``min_confidence`` config (default: medium).+# Confidence buckets, ordered low -> high; the surface layers filter on a+# ``min_confidence`` config (default: medium).+#+# ``low`` is a floor value, not an emitted label. Censused over this repo's own+# plan set: 835 high, 1,175 medium, **0 low** - no detector has ever produced+# one, because a detector that cannot justify ``medium`` suppresses the plan+# instead ("no suggestion, never a wrong one"). Both obvious fixes were+# rejected on that evidence: emitting a real ``low`` tier would resurrect+# exactly the spans the R1 gates suppress, and deleting the level would break+# ``min_confidence: low``, which is the documented way to ask for no filtering+# at all. So the level stays, and it means "no floor" rather than "a weak+# plan". Read a detector's confidence as medium-or-high.CONFIDENCE_LEVELS = ("low", "medium", "high")diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.pynew file mode 100644index 000000000..aa5a5fa1b--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity.py@@ -0,0 +1,464 @@+"""One file's refactoring, composed from that file's plans.++A detector output answers "here is a duplicated block" or "here is a liftable+span". Neither is the unit a person or an agent works in. The unit is a file:+what is wrong with it, what to do about it, in what order, and how much of that+can be handed off. This module folds the plans for one file into exactly that,+once, deterministically.++Three rules make the fold, and each lives with its owner. Membership and order+are here. Whether a step is safe to automate is :mod:`.preconditions`. What the+whole set is worth is :mod:`.opportunity_rank`. Identity reuses the plan kernels+in :mod:`.identity` rather than minting a second scheme, so an opportunity is+named by the work it contains and changes its name only when that work changes.++Two decisions are worth stating because they are not obvious:++**Order is structural first, then extractions.** A structural step relocates+symbols; a local extraction does not. Extracting first and splitting second+hands the split a symbol its grouping never saw, so the group it lands in is one+nobody computed. Doing it the other way round costs nothing: a lifted span+travels with its function.++**A low-signal clone is evidence, not a step.** Duplication is an observation.+Acting on it means creating a shared function and rewriting every call site,+which is only worth instructing when the sites really do move together - both+across files *and* co-changed. The rest still appears, attached to the file's+opportunity as the supporting evidence it always was, never as an instruction.+Nothing is deleted: the plans remain plans, addressable by id.++``performance_fix`` is excluded. Those rows belong to the performance layer,+which composes and ranks its own opportunities and owns their lifecycle; folding+them in here would publish the same work twice under two ids.+"""++from __future__ import annotations++from collections.abc import Iterable, Mapping, Sequence+from dataclasses import dataclass+from typing import Any++from .extract_helper import ACTIVE_CO_CHANGE+from .identity import REFACTORING_MODEL_VERSION, assign_public_ids, stable_id+from .models import RefactoringSuggestion+from .opportunity_rank import (+ opportunity_benefit,+ opportunity_risk,+ rank_factors,+ rank_score,+ rank_sort_key,+ step_cost,+ weakest_confidence,+ why_ranked,+)+from .preconditions import StepApplicability, classify_step+from .recommendations import affected_files, rehydrate_suggestion++# Opportunity ids share the plan id's version and digest, and differ in the+# prefix alone, so a reader can tell the two units apart without a lookup and+# ``identity.model_state`` still reads the version straight off the string.+_PLAN_PREFIX = "refac"+_OPPORTUNITY_PREFIX = "refop"++# Owned by the performance layer end to end - see the module docstring.+EXCLUDED_TYPES = frozenset({"performance_fix"})++# Execution order. Lower runs first. Structural steps relocate symbols, so they+# precede the local extractions that would otherwise be re-grouped by them;+# within the structural block the widest change goes first, so a later step+# never has to be redone against a file an earlier one just moved.+STEP_ORDER: dict[str, int] = {+ "break_cycle": 0,+ "split_file": 1,+ "extract_class": 2,+ "move_method": 3,+ "extract_method": 4,+ "extract_helper": 5,+}+_UNORDERED = len(STEP_ORDER)++# Steps that move a symbol out of the file it is declared in. Anything ordered+# after one of these has to be located again before it can be applied: its+# ``file_path`` and span describe where the symbol was, not where the earlier+# step just put it. Line drift within one file is not in this set - an executor+# finds a symbol by name - but a wrong *file* sends them looking in the wrong+# place entirely.+_RELOCATING_TYPES = frozenset({"split_file", "extract_class", "move_method"})++_EFFORT_ORDER = ("S", "M", "L", "XL")++# Evidence restates the plan's own signals; these three are read-model+# additions the plan layer already publishes elsewhere.+_EVIDENCE_OMIT = frozenset({"provenance", "rank_factors", "rank_score"})+++@dataclass(frozen=True, slots=True)+class OpportunityStep:+ """One plan, positioned in an execution order and classified for handoff.++ Carries the plan's identity and the facts a queue needs to render a row. The+ payload itself is not copied: the plan is addressable by ``plan_id``, and+ duplicating it here is how two representations of one plan start disagreeing.+ """++ plan_id: str+ refactoring_type: str+ target_symbol: str+ file_path: str+ line_start: int | None+ line_end: int | None+ effort_bucket: str+ confidence: str+ impact_delta: float+ source_biomarker: str+ applicability: StepApplicability+ # The earlier step in this opportunity that moves this step's symbol to+ # another file, so this one's location must be re-derived before it is+ # applied. ``None`` when nothing ahead of it relocates anything.+ relocated_by: str | None++ def as_dict(self) -> dict[str, Any]:+ return {+ "plan_id": self.plan_id,+ "refactoring_type": self.refactoring_type,+ "target_symbol": self.target_symbol,+ "file_path": self.file_path,+ "line_start": self.line_start,+ "line_end": self.line_end,+ "effort_bucket": self.effort_bucket,+ "confidence": self.confidence,+ "impact_delta": round(self.impact_delta, 3),+ "source_biomarker": self.source_biomarker,+ "relocated_by": self.relocated_by,+ "applicability": self.applicability.as_dict(),+ }+++@dataclass(frozen=True, slots=True)+class OpportunityEvidence:+ """An observation supporting the diagnosis without instructing a change."""++ plan_id: str+ refactoring_type: str+ target_symbol: str+ source_biomarker: str+ summary: dict[str, Any]++ def as_dict(self) -> dict[str, Any]:+ return {+ "plan_id": self.plan_id,+ "refactoring_type": self.refactoring_type,+ "target_symbol": self.target_symbol,+ "source_biomarker": self.source_biomarker,+ "summary": dict(self.summary),+ }+++@dataclass(frozen=True, slots=True)+class RefactoringOpportunity:+ """Everything one file needs done, ordered, with what backs it."""++ opportunity_id: str+ refactoring_model_version: int+ file_path: str+ lead_biomarker: str | None+ lead_refactoring_type: str+ # ``None`` when the file's dominant finding was not supplied - unknown,+ # never a quiet ``False``.+ addresses_primary_problem: bool | None+ steps: tuple[OpportunityStep, ...]+ evidence: tuple[OpportunityEvidence, ...]+ recoverable_health: float+ mechanical_steps: int+ judgment_steps: int+ affected_files: tuple[str, ...]+ effort_bucket: str+ confidence: str+ rank_score: float+ rank_factors: dict[str, float]+ why_ranked: tuple[dict[str, Any], ...]++ @property+ def step_count(self) -> int:+ return len(self.steps)++ def as_dict(self) -> dict[str, Any]:+ return {+ "opportunity_id": self.opportunity_id,+ "refactoring_model_version": self.refactoring_model_version,+ "file_path": self.file_path,+ "lead_biomarker": self.lead_biomarker,+ "lead_refactoring_type": self.lead_refactoring_type,+ "addresses_primary_problem": self.addresses_primary_problem,+ "steps": [step.as_dict() for step in self.steps],+ "evidence": [item.as_dict() for item in self.evidence],+ "recoverable_health": round(self.recoverable_health, 3),+ "step_count": self.step_count,+ "mechanical_steps": self.mechanical_steps,+ "judgment_steps": self.judgment_steps,+ "affected_files": list(self.affected_files),+ "effort_bucket": self.effort_bucket,+ "confidence": self.confidence,+ "rank_score": self.rank_score,+ "rank_factors": dict(self.rank_factors),+ "why_ranked": [dict(entry) for entry in self.why_ranked],+ }+++def is_standalone_clone(suggestion: RefactoringSuggestion) -> bool:+ """Whether a clone group earns a step rather than an evidence slot.++ Cross-file *and* co-change-backed: the sites sit in different files and git+ says they really are edited together. An intra-file repetition is a local+ tidy-up, and a cross-file pair nobody has ever changed twice is a coincidence+ of shape. Neither is worth instructing a rewrite of N call sites over.+ """+ evidence = suggestion.evidence or {}+ cross_file = not evidence.get("is_intra_file", False)+ co_change = evidence.get("co_change_count") or 0+ return cross_file and co_change >= ACTIVE_CO_CHANGE+++def _is_step(suggestion: RefactoringSuggestion) -> bool:+ if suggestion.refactoring_type == "extract_helper":+ return is_standalone_clone(suggestion)+ return True+++def _member_sort_key(item: tuple[RefactoringSuggestion, str]) -> tuple[int, int, str, str]:+ suggestion, plan_id = item+ return (+ STEP_ORDER.get(suggestion.refactoring_type, _UNORDERED),+ suggestion.line_start or 0,+ suggestion.target_symbol,+ plan_id,+ )+++def _lead(+ steps: Sequence[OpportunityStep], primary_biomarker: str | None+) -> tuple[str | None, str, bool | None]:+ """The file's lead diagnosis, and whether a step actually addresses it.++ *primary_biomarker* is the file's dominant health finding, which the plans+ cannot supply: a file's worst problem is routinely one no detector answers+ (a coverage gap, churn) and asking the plans would only ever return a+ biomarker some plan already addresses, making the answer vacuously yes.+ When it is not supplied the question is unanswered, not answered ``False``.++ With no biomarker in play at all - the file's whole opportunity is+ structural, and structural detectors attribute to none - the first step is+ both the diagnosis and the answer to it.+ """+ if primary_biomarker is None:+ addressed = next((step for step in steps if step.source_biomarker), None)+ lead_type = (addressed or steps[0]).refactoring_type+ return (addressed.source_biomarker if addressed else None), lead_type, None+ addressing = next(+ (step for step in steps if step.source_biomarker == primary_biomarker), None+ )+ return primary_biomarker, (addressing or steps[0]).refactoring_type, addressing is not None+++def _aggregate_effort(steps: Sequence[OpportunityStep]) -> str:+ """The set's effort: the largest single step, not the sum of the labels.++ Buckets are size classes, not durations, so adding them would produce a+ label no detector could emit. Total work enters the ranking through+ ``step_cost`` instead, where it belongs.+ """+ present = [step.effort_bucket for step in steps if step.effort_bucket in _EFFORT_ORDER]+ return max(present, key=_EFFORT_ORDER.index) if present else "M"+++def opportunity_kernel(step_plan_ids: Sequence[str], file_path: str) -> tuple[Any, ...]:+ """Identity over the member plan ids, never a parallel scheme.++ The steps are what the opportunity instructs, so they are what names it, and+ each plan id is already the versioned digest of that plan's own kernel.+ Evidence is deliberately outside: a clone appearing or vanishing as a+ supporting observation must not rename the ordered work an agent is holding+ an id for.+ """+ return ("refactoring_opportunity", file_path, tuple(step_plan_ids))+++def opportunity_public_id(step_plan_ids: Sequence[str], file_path: str) -> str:+ return stable_id(opportunity_kernel(step_plan_ids, file_path)).replace(+ _PLAN_PREFIX, _OPPORTUNITY_PREFIX, 1+ )+++def _step_of(+ suggestion: RefactoringSuggestion, plan_id: str, relocated_by: str | None+) -> OpportunityStep:+ return OpportunityStep(+ plan_id=plan_id,+ refactoring_type=suggestion.refactoring_type,+ target_symbol=suggestion.target_symbol,+ file_path=suggestion.file_path,+ line_start=suggestion.line_start,+ line_end=suggestion.line_end,+ effort_bucket=suggestion.effort_bucket,+ confidence=suggestion.confidence,+ impact_delta=float(suggestion.impact_delta or 0.0),+ source_biomarker=suggestion.source_biomarker,+ relocated_by=relocated_by,+ applicability=classify_step(suggestion),+ )+++def _evidence_of(suggestion: RefactoringSuggestion, plan_id: str) -> OpportunityEvidence:+ return OpportunityEvidence(+ plan_id=plan_id,+ refactoring_type=suggestion.refactoring_type,+ target_symbol=suggestion.target_symbol,+ source_biomarker=suggestion.source_biomarker,+ summary={+ key: value+ for key, value in (suggestion.evidence or {}).items()+ if key not in _EVIDENCE_OMIT+ },+ )+++def _sequence(+ step_rows: Sequence[tuple[RefactoringSuggestion, str]],+) -> list[OpportunityStep]:+ """Build the steps in execution order, marking the ones a move displaces.++ Each marked step names the *most recent* relocation ahead of it, because+ that is the one whose result a reader has to look at to find the symbol+ again. It is deliberately coarse: it marks every later step, not only the+ ones whose own symbol moved, since which group a symbol landed in is not+ knowable from the plan payload and over-warning is the safe direction.+ """+ steps: list[OpportunityStep] = []+ relocated_by: str | None = None+ for suggestion, plan_id in step_rows:+ steps.append(_step_of(suggestion, plan_id, relocated_by))+ if suggestion.refactoring_type in _RELOCATING_TYPES:+ relocated_by = plan_id+ return steps+++def _compose_one(+ file_path: str,+ members: Sequence[tuple[RefactoringSuggestion, str]],+ primary_biomarker: str | None,+) -> RefactoringOpportunity | None:+ ordered = sorted(members, key=_member_sort_key)+ step_rows = [row for row in ordered if _is_step(row[0])]+ if not step_rows:+ # Observations with nothing to instruct. The plans still stand on their+ # own; there is simply no composed refactoring to publish for this file.+ return None++ steps = tuple(_sequence(step_rows))+ evidence = tuple(+ _evidence_of(suggestion, plan_id)+ for suggestion, plan_id in ordered+ if not _is_step(suggestion)+ )++ step_suggestions = [suggestion for suggestion, _ in step_rows]+ touched = sorted({path for item in step_suggestions for path in affected_files(item)})+ biomarker, lead_type, addresses = _lead(steps, primary_biomarker)+ mechanical = sum(1 for step in steps if step.applicability.mechanical)+ factors = rank_factors(+ benefit=opportunity_benefit(step_suggestions),+ addresses_primary_problem=addresses is True,+ mechanical_share=mechanical / len(steps),+ cost=step_cost(step_suggestions),+ risk=opportunity_risk(step_suggestions, surface=max(0, len(touched) - 1)),+ )+ return RefactoringOpportunity(+ opportunity_id=opportunity_public_id([step.plan_id for step in steps], file_path),+ refactoring_model_version=REFACTORING_MODEL_VERSION,+ file_path=file_path,+ lead_biomarker=biomarker,+ lead_refactoring_type=lead_type,+ addresses_primary_problem=addresses,+ steps=steps,+ evidence=evidence,+ recoverable_health=sum(step.impact_delta for step in steps),+ mechanical_steps=mechanical,+ judgment_steps=len(steps) - mechanical,+ affected_files=tuple(touched),+ effort_bucket=_aggregate_effort(steps),+ confidence=weakest_confidence(step_suggestions),+ rank_score=rank_score(factors),+ rank_factors=factors,+ why_ranked=tuple(why_ranked(factors)),+ )+++def compose_opportunities(+ rows: Iterable[Any],+ *,+ primary_biomarker_by_file: Mapping[str, str] | None = None,+) -> list[RefactoringOpportunity]:+ """Fold plans into one ranked opportunity per file.++ Accepts anything :func:`.recommendations.rehydrate_suggestion` accepts -+ detector dataclasses, dicts, ORM rows - so the same composition runs beside+ the analyzer and over rows read back out of storage, and cannot drift+ between the two. Pure: no I/O, no graph, no clock.++ *primary_biomarker_by_file* is the health layer's per-file dominant cause+ (:func:`..models.primary_biomarker_by_file`). Supplying it is what makes+ ``addresses_primary_problem`` a real question; omitting it leaves the answer+ explicitly unknown rather than assumed.+ """+ leads = primary_biomarker_by_file or {}+ suggestions = [+ suggestion+ for suggestion in (rehydrate_suggestion(row) for row in rows)+ if suggestion.refactoring_type not in EXCLUDED_TYPES+ ]+ plan_ids = assign_public_ids(suggestions)+ by_file: dict[str, list[tuple[RefactoringSuggestion, str]]] = {}+ for suggestion, plan_id in zip(suggestions, plan_ids, strict=True):+ by_file.setdefault(suggestion.file_path, []).append((suggestion, plan_id))++ composed = [+ opportunity+ for file_path in sorted(by_file)+ if (+ opportunity := _compose_one(file_path, by_file[file_path], leads.get(file_path))+ )+ is not None+ ]+ composed.sort(key=rank_sort_key)+ return composed+++def opportunity_status(+ opportunity: RefactoringOpportunity, plan_status: Mapping[str, str]+) -> str:+ """Lifecycle rolled up from the member steps.++ Resolved only when every step is; one step a person marked a false positive+ does not resolve the work the others still describe. An unknown plan id+ reads as ``open``, because a step nobody has triaged is outstanding.+ """+ states = {plan_status.get(step.plan_id, "open") for step in opportunity.steps}+ if states <= {"resolved", "false_positive"}:+ return "resolved"+ if states <= {"acknowledged", "resolved", "false_positive"}:+ return "acknowledged"+ return "open"+++__all__ = [+ "EXCLUDED_TYPES",+ "STEP_ORDER",+ "OpportunityEvidence",+ "OpportunityStep",+ "RefactoringOpportunity",+ "compose_opportunities",+ "is_standalone_clone",+ "opportunity_kernel",+ "opportunity_public_id",+ "opportunity_status",+]diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/opportunity_rank.py b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity_rank.pynew file mode 100644index 000000000..5f7963e3f--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/refactoring/opportunity_rank.py@@ -0,0 +1,152 @@+"""How much a composed opportunity is worth, and in what order they land.++Plan-level rank (:mod:`.recommendations`) answers "which single detector output+is worth the most". This module answers a different question over a different+unit: given everything one file needs done, how does that file compare to the+next one. The two are kept apart because merging them is what let a file's+popularity stand in for a plan's value, and because a surface still needs the+plan order for compatibility.++Four things move an opportunity up, and they are the four the product promised:++- it addresses the file's own primary diagnosed problem, rather than something+ incidental that happens to live there;+- it recovers real health, summed over its steps, or carries a detector-native+ structural gain where no health deduction exists;+- a larger share of its steps is mechanical, so more of it can be handed off;+- it costs less and risks less - with the blast radius charged exactly once,+ over the union of what the steps touch, never per step.++The arithmetic that both ranks share - the benefit-over-cost shape and the+surface/confidence risk - lives in :mod:`.recommendations` with the plan rank;+what differs, and belongs here, is what counts as benefit and what counts as+uplift for a whole step set.++Nothing here is a health score, and no value it produces is blended into one.+It is an ordering key whose weights are frozen policy. The performance layer's+``perf/opportunity_rank.py`` is the same role for a different domain and shares+no code with this one.+"""++from __future__ import annotations++from collections.abc import Sequence+from typing import Any++from .models import CONFIDENCE_LEVELS, RefactoringSuggestion+from .recommendations import EFFORT_COST, detector_native_benefit, priority_score+from .recommendations import surface_confidence_risk as _surface_confidence_risk++# Weight of the two qualities that separate opportunities of equal size: doing+# the thing the file is actually sick with, and being handed off rather than+# reasoned about. Deliberately of the same order as each other, and both+# smaller than the benefit they multiply.+PRIMARY_PROBLEM_WEIGHT = 0.5+MECHANICAL_SHARE_WEIGHT = 0.5++# Worst first, off the package's one confidence vocabulary rather than a+# second hand-written tuple that could drift from it.+_WORST_FIRST = tuple(reversed(CONFIDENCE_LEVELS))+++def weakest_confidence(steps: Sequence[RefactoringSuggestion]) -> str:+ """The least certain step's confidence: a set is only as sound as its worst.++ Always one of :data:`.models.CONFIDENCE_LEVELS`. A label no detector should+ emit - a legacy row, a corrupted string - is reported as the weakest known+ level rather than passed through: the risk table has no entry for it, and+ its fallback sits *below* ``low``, so letting it through would have made+ adding an uninterpretable step reduce an opportunity's risk.+ """+ weakest = _WORST_FIRST[0]+ if not steps:+ return weakest+ return max(+ (step.confidence if step.confidence in _WORST_FIRST else weakest for step in steps),+ key=_WORST_FIRST.index,+ )+++def rank_factors(+ *,+ benefit: float,+ addresses_primary_problem: bool,+ mechanical_share: float,+ cost: float,+ risk: float,+) -> dict[str, float]:+ """The published components of the score, each rounded once, here."""+ return {+ "benefit": round(benefit, 4),+ "primary_problem": round(PRIMARY_PROBLEM_WEIGHT if addresses_primary_problem else 0.0, 4),+ "mechanical_share": round(MECHANICAL_SHARE_WEIGHT * mechanical_share, 4),+ "cost": round(cost, 4),+ "risk": round(risk, 4),+ }+++def rank_score(factors: dict[str, float]) -> float:+ """Benefit scaled by what makes it attractive, divided by what it costs.++ Benefit multiplies rather than offsets, exactly as at plan level: a step set+ with no evidence of a gain scores zero and cannot be lifted above one that+ recovers health by being mechanical or by sitting on a popular file.+ """+ return round(+ priority_score(+ benefit=factors["benefit"],+ uplift=factors["primary_problem"] + factors["mechanical_share"],+ cost=factors["cost"],+ risk=factors["risk"],+ ),+ 4,+ )+++def step_cost(steps: Sequence[RefactoringSuggestion]) -> float:+ """Total work. Doing five things is more work than doing one."""+ return sum(EFFORT_COST.get(step.effort_bucket, 3.0) for step in steps)+++def opportunity_risk(steps: Sequence[RefactoringSuggestion], *, surface: int) -> float:+ """Blast radius once, over the union *surface*, plus the weakest confidence.++ *surface* is the count of files the whole set touches beyond the host, which+ the composer already computed as a union. Charging it per step would bill a+ file once for every plan that mentions it, which is the double-count R1+ removed one layer down.+ """+ return _surface_confidence_risk(surface, weakest_confidence(steps))+++def opportunity_benefit(steps: Sequence[RefactoringSuggestion]) -> float:+ """Recoverable health across the set, or the detector-native gain instead."""+ return sum(detector_native_benefit(step) for step in steps)+++def why_ranked(factors: dict[str, float], *, limit: int = 3) -> list[dict[str, Any]]:+ """The factors that actually moved this one, largest first. Structured."""+ ordered = sorted(+ ((name, value) for name, value in factors.items() if value),+ key=lambda item: (-abs(item[1]), item[0]),+ )+ return [{"factor": name, "value": value} for name, value in ordered[:limit]]+++def rank_sort_key(opportunity: Any) -> tuple[float, str, str]:+ """A total order. The id tail is what stops ties floating between runs."""+ return (-opportunity.rank_score, opportunity.file_path, opportunity.opportunity_id)+++__all__ = [+ "MECHANICAL_SHARE_WEIGHT",+ "PRIMARY_PROBLEM_WEIGHT",+ "opportunity_benefit",+ "opportunity_risk",+ "rank_factors",+ "rank_score",+ "rank_sort_key",+ "step_cost",+ "weakest_confidence",+ "why_ranked",+]diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.py b/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.pynew file mode 100644index 000000000..125850cd7--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.py@@ -0,0 +1,216 @@+"""Applicability facts for one refactoring step, and what they license.++Two questions, one owner. *What do we know* about a plan's surroundings, and+*is that enough to call the step mechanical* rather than a judgment call a+person has to make.++Both answers come only from facts the layer already records: the plan payload,+its evidence, its blast radius, and the detector's own confidence. Nothing here+queries a graph, reads source, or derives a signal a detector did not already+publish, so the classification is identical whether it runs beside the analyzer+or over rows read back out of storage months later.++Unknown is a first-class answer. ``mechanical`` means every proof obligation the+step needs is *held*, not merely *unrefuted*: a fact we cannot see refuses the+promotion, exactly as the Extract Method gate refuses a statement kind it cannot+classify. That keeps the layer's contract - no suggestion, never a wrong one -+true of the classification as well as of the plans.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Literal++from .models import RefactoringSuggestion+from .recommendations import affected_files, blast_size++Applicability = Literal["mechanical", "judgment"]++# Reason codes are a closed vocabulary so a surface can label them and a test+# can pin them. They read as the answer to "why is this not mechanical?", or,+# for the two mechanical codes, "what was proved?".+MECHANICAL_REASONS = ("dataflow_proved_local_extraction",)+JUDGMENT_REASONS = (+ "build_constraints_unknown",+ "call_site_bindings_unproven",+ "changes_symbol_home",+ "detector_confidence_below_high",+ "inverts_imports_across_files",+ "no_named_target",+ "reshapes_class_surface",+ "rewrites_dependent_imports",+ "unclassified_refactoring_type",+)++# 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"+++@dataclass(frozen=True, slots=True)+class StepApplicability:+ """What is known about a step, and whether that licenses automation."""++ classification: Applicability+ reasons: tuple[str, ...]+ facts: dict[str, Any]+ unknowns: tuple[str, ...]++ @property+ def mechanical(self) -> bool:+ return self.classification == "mechanical"++ def as_dict(self) -> dict[str, Any]:+ return {+ "classification": self.classification,+ "reasons": list(self.reasons),+ "facts": dict(self.facts),+ "unknowns": list(self.unknowns),+ }+++def _int_or_none(value: Any) -> int | None:+ return int(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else None+++def _named_groups(plan: dict[str, Any]) -> bool | None:+ """Whether every proposed group names the file it lands in.++ ``None`` when the plan proposes no groups at all: absence of groups is not+ evidence that the naming succeeded, and R1 made an unnameable group emit+ ``null`` rather than invent a filename.+ """+ groups = [group for group in (plan.get("groups") or []) if isinstance(group, dict)]+ if not groups:+ return None+ return all(group.get("suggested_file") for group in groups)+++# Which facts each refactoring type can even have. A key absent here is not+# unknown, it is meaningless: asking whether an Extract Method needs a+# re-export shim has no answer, and reporting one as ``None`` would read as a+# measurement that failed. Only the keys a type can carry are published, so+# ``unknowns`` names facts that genuinely could not be established.+_BASE_FACT_KEYS = ("affected_file_count", "cross_file", "blast_size", "confidence")+_TYPE_FACT_KEYS: dict[str, tuple[str, ...]] = {+ "extract_method": ("local_scope",),+ "split_file": ("shim_required", "groups_named", "dependents", "framework_registration"),+ "extract_class": ("dependents", "framework_registration"),+ "move_method": ("callers", "framework_registration"),+ "break_cycle": ("framework_registration",),+ "extract_helper": ("co_change_count",),+}+++def step_facts(suggestion: RefactoringSuggestion) -> tuple[dict[str, Any], tuple[str, ...]]:+ """Applicability facts for *suggestion*, plus the names of the missing ones.++ A key is present with ``None`` when the fact is one this step's type does+ carry but this row does not, so a reader can tell "no dependents" from "we+ never counted". The ``unknowns`` tuple names exactly those keys.+ """+ plan = suggestion.plan or {}+ evidence = suggestion.evidence or {}+ blast = suggestion.blast_radius or {}+ files = affected_files(suggestion)++ available: dict[str, Any] = {+ "affected_file_count": len(files),+ "cross_file": len(files) > 1,+ "blast_size": blast_size(suggestion),+ "confidence": suggestion.confidence,+ "local_scope": blast.get("scope") == _LOCAL_SCOPE,+ "dependents": _int_or_none(blast.get("dependent_count", blast.get("dependents_count"))),+ "callers": _int_or_none(blast.get("callers")),+ "co_change_count": _int_or_none(evidence.get("co_change_count")),+ "shim_required": plan.get("shim_required") if "shim_required" in plan else None,+ "groups_named": _named_groups(plan),+ # No graph is in scope here, so whether a framework registers the symbols+ # a step moves is never known. It is reported rather than omitted because+ # it is the fact that keeps every symbol-moving step a judgment call.+ "framework_registration": None,+ }+ keys = _BASE_FACT_KEYS + _TYPE_FACT_KEYS.get(suggestion.refactoring_type, ())+ facts = {key: available[key] for key in keys}+ unknowns = tuple(sorted(key for key, value in facts.items() if value is None))+ return facts, unknowns+++def _extract_method_reasons(suggestion: RefactoringSuggestion, facts: dict[str, Any]) -> list[str]:+ """A lifted span adds a private helper and moves no public symbol.++ R1's dataflow gate proves the span behaviour-preserving before it is ever+ offered, and the blast radius is categorically local, so the only thing left+ to check is that the detector itself was sure.+ """+ if not facts["local_scope"]:+ return ["changes_symbol_home"]+ if suggestion.confidence != "high":+ return ["detector_confidence_below_high"]+ return ["dataflow_proved_local_extraction"]+++def _split_file_reasons(_suggestion: RefactoringSuggestion, facts: dict[str, Any]) -> list[str]:+ """No split is mechanical, and the same-package case is why.++ The promising case was Go: package members keep their qualified name+ whichever file declares them, so a same-package split rewrites no import+ and no registry keyed on the module path can notice. That argument covers+ import identity and nothing else. Which *file* a Go symbol sits in also+ decides whether it compiles at all - a ``_linux.go`` / ``_amd64.go``+ basename, or a ``//go:build`` line - and neither fact reaches this layer:+ the plan payload carries group membership and a shim flag, not the source.+ Moving a constrained symbol into an unconstrained file compiles it+ everywhere, which is a behaviour change presented as safe to automate.++ So the same-package case reports what it could not establish instead of+ claiming a proof. Restoring it needs a build-constraint fact from+ ingestion; see the plan's Backlog.+ """+ if facts["shim_required"] is not False:+ return ["rewrites_dependent_imports", "changes_symbol_home"]+ if facts["groups_named"] is not True:+ return ["no_named_target"]+ return ["build_constraints_unknown"]+++_JUDGMENT_BY_TYPE: dict[str, tuple[str, ...]] = {+ # A shared helper replaces N call sites whose bindings the detector compares+ # by token shape, never by resolved meaning.+ "extract_helper": ("call_site_bindings_unproven",),+ "move_method": ("changes_symbol_home",),+ "extract_class": ("reshapes_class_surface", "changes_symbol_home"),+ "break_cycle": ("inverts_imports_across_files",),+}+++def classify_step(suggestion: RefactoringSuggestion) -> StepApplicability:+ """Whether *suggestion* is safe to automate, and the facts behind that."""+ facts, unknowns = step_facts(suggestion)+ kind = suggestion.refactoring_type+ if kind == "extract_method":+ reasons = _extract_method_reasons(suggestion, facts)+ elif kind == "split_file":+ reasons = _split_file_reasons(suggestion, facts)+ else:+ reasons = list(_JUDGMENT_BY_TYPE.get(kind, ("unclassified_refactoring_type",)))+ # ``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)+ return StepApplicability(+ classification="mechanical" if mechanical else "judgment",+ reasons=tuple(reasons),+ facts=facts,+ unknowns=unknowns,+ )+++__all__ = [+ "JUDGMENT_REASONS",+ "MECHANICAL_REASONS",+ "Applicability",+ "StepApplicability",+ "classify_step",+ "step_facts",+]diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.pyindex 7338ddbe3..cbdfd8a62 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py@@ -26,8 +26,10 @@ ValidationBasis = Literal["measured", "inferred", "mixed", "unknown"]ValidationVia = Literal["coverage", "call-graph", "import-graph", "mixed"]DEFAULT_TEST_LIMIT = 12-_EFFORT_COST = {"S": 1.0, "M": 2.0, "L": 3.0, "XL": 5.0}-_CONFIDENCE_RISK = {"high": 0.0, "medium": 0.5, "low": 1.25}+# Public because the opportunity rank charges the same work and the same+# uncertainty over a whole step set. Two tables would be two policies.+EFFORT_COST = {"S": 1.0, "M": 2.0, "L": 3.0, "XL": 5.0}+CONFIDENCE_RISK = {"high": 0.0, "medium": 0.5, "low": 1.25}_WEAK_PROVENANCE = {"name-fallback", "global_unique", "unknown"}@@ -166,6 +168,28 @@ def enrich_blast_radius(suggestion: RefactoringSuggestion, centrality: Mapping[ssuggestion.blast_radius = blast+def surface_confidence_risk(surface: int, confidence: str) -> float:+ """Risk from change surface and detector certainty, charged once.++ Both the plan rank and the opportunity rank ask this, over their own+ surface: one plan's blast radius, or the union across a step set. Two+ copies would be two policies about the same two inputs.+ """+ return math.log1p(max(0, surface)) + CONFIDENCE_RISK.get(confidence, 0.75)+++def priority_score(*, benefit: float, uplift: float, cost: float, risk: float) -> float:+ """Benefit scaled by what makes it attractive, over what it costs.++ Benefit multiplies rather than offsets, so something with no evidence of a+ gain scores zero and cannot be lifted above something that recovers health+ by being popular, cheap or easy. What counts as benefit and what counts as+ uplift differ between a plan and a composed opportunity, and are decided by+ their own owners; this shape is the part they share.+ """+ return benefit * (1.0 + uplift) / (1.0 + cost + risk)++def _performance_benefit(evidence: Mapping[str, Any]) -> float:factors = evidence.get("rank_factors")if isinstance(factors, Mapping):@@ -476,7 +500,7 @@ def _priority_components(leverage = 0.5 * math.log1p(weighted_deficit) + math.log1p(max(0, dependents)) + entry_bonussurface = max(blast_size(suggestion), max(0, len(affected_files(suggestion)) - 1))# Blast radius is charged once, in ``risk``. Cost is the work itself.- cost = _EFFORT_COST.get(suggestion.effort_bucket, 3.0)+ cost = EFFORT_COST.get(suggestion.effort_bucket, 3.0)provenance = str((suggestion.evidence or {}).get("provenance") or "")weak_graph = 1.0 if provenance in _WEAK_PROVENANCE else 0.0validation_risk = {@@ -485,17 +509,12 @@ def _priority_components("inferred": 0.75,"unknown": 1.5,}[validation.basis]- risk = (- math.log1p(surface)- + _CONFIDENCE_RISK.get(suggestion.confidence, 0.75)- + weak_graph- + validation_risk- )+ risk = surface_confidence_risk(surface, suggestion.confidence) + weak_graph + validation_risk# Benefit multiplies rather than offsets: leverage (the host file's# deficit and dependents) scales a real gain, and scales nothing when# there is none. A plan with no evidence of benefit scores 0 and cannot# outrank one that recovers health, however popular its file.- priority = benefit * (1.0 + leverage) / (1.0 + cost + risk)+ priority = priority_score(benefit=benefit, uplift=leverage, cost=cost, risk=risk)return (round(benefit, 4),round(leverage, 4),@@ -653,7 +672,9 @@ def serialize_recommendations(__all__ = [+ "CONFIDENCE_RISK","DEFAULT_TEST_LIMIT",+ "EFFORT_COST","Recommendation","RecommendationView","ValidationPlan",@@ -668,6 +689,8 @@ __all__ = ["detector_native_benefit","enrich_blast_radius","hydrate_recommendations",+ "priority_score","rehydrate_suggestion","serialize_recommendations",+ "surface_confidence_risk",]diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pyindex 1cb824927..cd8920eca 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -11,7 +11,6 @@ from typing import Anyfrom sqlalchemy import select-from repowise.core.analysis.health.biomarkers import continuous_biomarkersfrom repowise.core.analysis.health.churn_complexity import churn_complexity_pointsfrom repowise.core.analysis.health.complexity.languages import LANGUAGE_MAPSfrom repowise.core.analysis.health.coverage import decay_since, measurement_ref@@ -19,6 +18,7 @@ from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracfrom repowise.core.analysis.health.finding_identity import finding_public_idfrom repowise.core.analysis.health.grading import HEALTHY_MIN, band_forfrom repowise.core.analysis.health.grading import distribution as health_distribution+from repowise.core.analysis.health.models import primary_findingfrom repowise.core.analysis.health.perf.coverage import PerfCoverage, coverage_for_metricsfrom repowise.core.analysis.health.perf.opportunity_rank import observation_rankfrom repowise.core.analysis.health.refactoring.recommendations import (@@ -527,16 +527,18 @@ def _leads_by_file(findings: list[Any]) -> dict[str, dict[str, Any]]:"N% of lines uncovered", which is true and tells a reader nothing about whythis file rather than any other. The gradient still counts in``total_deduction`` and still leads when it is a file's only finding — it- just stops crowding out a nameable cause.+ just stops crowding out a nameable cause. That selection rule now lives in+ ``analysis.health.models.primary_finding``, so this and the composition+ layer cannot drift about which finding a file leads with."""- continuous = continuous_biomarkers()by_file: dict[str, list[Any]] = {}for f in findings:by_file.setdefault(f.file_path, []).append(f)leads: dict[str, dict[str, Any]] = {}for path, fs in by_file.items():- discrete = [f for f in fs if f.biomarker_type not in continuous]- primary = max(discrete or fs, key=lambda x: x.health_impact)+ primary = primary_finding(fs)+ if primary is None:+ continueleads[path] = {"primary_biomarker": primary.biomarker_type,"primary_reason": primary.reason,diff --git a/tests/fixtures/refactoring_corpus/cases.py b/tests/fixtures/refactoring_corpus/cases.pyindex f7f6e0bec..211a6a46b 100644--- a/tests/fixtures/refactoring_corpus/cases.py+++ b/tests/fixtures/refactoring_corpus/cases.py@@ -193,3 +193,78 @@ def try_except_assigned(rows, limit):record(limit)record(row)return rate+++def calls_a_sibling_closure(rows, prefix):+ """A span that calls a closure declared beside it must pass it in.++ The nested ``def`` is a scope whose reads are its own, and at the same time+ a plain local binding right here. Losing the binding let a span be offered+ whose lifted body called ``emit`` without receiving it, which is how the+ ranked head came to carry a plan that does not run.+ """+ seen = []++ def emit(value):+ seen.append(f"{prefix}:{value}")++ # Pinned by name in test_refactoring_corpus_golden rather than by a+ # sound: marker - the comment attaches to the span it precedes here, so+ # the marker's line arithmetic would not line up.+ for row in rows:+ if isinstance(row, str):+ emit(row.strip())+ elif isinstance(row, (int, float)):+ emit(round(float(row), 2))+ else:+ emit(str(row))+ record(row)+ return seen+++def read_then_write_in_span(block, limit):+ """A loop variable read above its write, both inside one candidate span.++ Nothing after the span reads ``expect``, so it is not an OUT; the read at+ the top of the span takes the previous iteration's value. Lifting the pair+ into a helper drops the write and breaks the state machine.+ """+ names = []+ expect = True+ depth = 0+ i = 0+ while i < limit:+ ch = block[i]+ if ch == "(":+ depth += 1+ expect = True+ elif ch == ")":+ depth -= 1+ else:+ # unsound: the write below is read again on the next iteration+ symbol = str(ch)+ if expect and depth >= 1:+ names.append(symbol)+ record(symbol)+ expect = depth == 1+ i += 1+ return names+++def holds_a_nested_helper(rows, limit):+ """A span containing a named nested function may not be lifted.++ Def/use never descends into a nested scope, so a sibling closure calling+ ``scale`` is invisible here. Moving the declaration out of this scope would+ move the binding away from those callers with nothing in the facts to show+ it, so the span is refused rather than guessed at.+ """+ total = 0+ # unsound: the span below holds a named nested function+ def scale(value):+ return value * limit++ for row in rows:+ total += scale(row)+ record(row)+ return totaldiff --git a/tests/fixtures/refactoring_corpus/golden_extractions.json b/tests/fixtures/refactoring_corpus/golden_extractions.jsonindex f3d91db4a..683502412 100644--- a/tests/fixtures/refactoring_corpus/golden_extractions.json+++ b/tests/fixtures/refactoring_corpus/golden_extractions.json@@ -1,5 +1,51 @@{"python": {+ "calls_a_sibling_closure": [+ {+ "ccn_removed": 3,+ "end_line": 221,+ "params": [+ "emit",+ "rows"+ ],+ "returns": [],+ "slice_nloc": 11,+ "start_line": 211+ },+ {+ "ccn_removed": 3,+ "end_line": 221,+ "params": [+ "emit",+ "rows"+ ],+ "returns": [],+ "slice_nloc": 10,+ "start_line": 212+ },+ {+ "ccn_removed": 3,+ "end_line": 221,+ "params": [+ "emit",+ "rows"+ ],+ "returns": [],+ "slice_nloc": 9,+ "start_line": 213+ },+ {+ "ccn_removed": 2,+ "end_line": 221,+ "params": [+ "emit",+ "row"+ ],+ "returns": [],+ "slice_nloc": 7,+ "start_line": 215+ }+ ],"changed_accumulator": [{"ccn_removed": 2,@@ -472,6 +518,7 @@"start_line": 166}],+ "holds_a_nested_helper": [],"if_without_else": [{"ccn_removed": 2,@@ -628,51 +675,74 @@],"slice_nloc": 12,"start_line": 94- },+ }+ ],+ "loop_rebinds_iterable": [],+ "read_then_write_in_span": [{- "ccn_removed": 1,- "end_line": 105,+ "ccn_removed": 5,+ "end_line": 250,"params": [- "carry",- "limit",- "row"+ "block",+ "limit"],"returns": [- "carry"+ "names"],- "slice_nloc": 10,- "start_line": 96+ "slice_nloc": 25,+ "start_line": 226},{- "ccn_removed": 1,- "end_line": 104,+ "ccn_removed": 5,+ "end_line": 250,"params": [- "carry",- "limit",- "row"+ "block",+ "limit"],"returns": [- "carry"+ "names"],- "slice_nloc": 9,- "start_line": 96+ "slice_nloc": 19,+ "start_line": 232},{- "ccn_removed": 1,- "end_line": 103,+ "ccn_removed": 5,+ "end_line": 250,"params": [- "carry",+ "block","limit",- "row"+ "names"],- "returns": [- "carry"+ "returns": [],+ "slice_nloc": 18,+ "start_line": 233+ },+ {+ "ccn_removed": 5,+ "end_line": 250,+ "params": [+ "block",+ "limit",+ "names"],- "slice_nloc": 8,- "start_line": 96+ "returns": [],+ "slice_nloc": 17,+ "start_line": 234+ },+ {+ "ccn_removed": 5,+ "end_line": 250,+ "params": [+ "block",+ "depth",+ "limit",+ "names"+ ],+ "returns": [],+ "slice_nloc": 16,+ "start_line": 235}],- "loop_rebinds_iterable": [],"record": [],"try_except_assigned": [{diff --git a/tests/fixtures/refactoring_corpus/golden_opportunities.json b/tests/fixtures/refactoring_corpus/golden_opportunities.jsonnew file mode 100644index 000000000..1c3c2eb61--- /dev/null+++ b/tests/fixtures/refactoring_corpus/golden_opportunities.json@@ -0,0 +1,355 @@+{+ "gopkg": [+ {+ "addresses_primary_problem": false,+ "affected_files": [+ "inventory.go"+ ],+ "confidence": "high",+ "effort_bucket": "L",+ "evidence": [],+ "file_path": "inventory.go",+ "judgment_steps": 1,+ "lead_biomarker": "dry_violation",+ "lead_refactoring_type": "split_file",+ "mechanical_steps": 0,+ "opportunity_id": "refop2_f8df0afac1fe67c55d05",+ "rank_factors": {+ "benefit": 1.6931,+ "cost": 3.0,+ "mechanical_share": 0.0,+ "primary_problem": 0.0,+ "risk": 0.0+ },+ "rank_score": 0.4233,+ "recoverable_health": 0.0,+ "refactoring_model_version": 2,+ "step_count": 1,+ "steps": [+ {+ "applicability": {+ "classification": "judgment",+ "facts": {+ "affected_file_count": 1,+ "blast_size": 0,+ "confidence": "high",+ "cross_file": false,+ "dependents": 0,+ "framework_registration": null,+ "groups_named": false,+ "shim_required": false+ },+ "reasons": [+ "no_named_target"+ ],+ "unknowns": [+ "framework_registration"+ ]+ },+ "confidence": "high",+ "effort_bucket": "L",+ "file_path": "inventory.go",+ "impact_delta": 0.0,+ "plan_id": "refac2_396717806264bd16aab8",+ "refactoring_type": "split_file",+ "relocated_by": null,+ "source_biomarker": "",+ "target_symbol": "inventory.go -> 2 files"+ }+ ],+ "why_ranked": [+ {+ "factor": "cost",+ "value": 3.0+ },+ {+ "factor": "benefit",+ "value": 1.6931+ }+ ]+ }+ ],+ "orm": [],+ "tsapp": [+ {+ "addresses_primary_problem": true,+ "affected_files": [+ "account.ts"+ ],+ "confidence": "high",+ "effort_bucket": "S",+ "evidence": [],+ "file_path": "account.ts",+ "judgment_steps": 0,+ "lead_biomarker": "complex_method",+ "lead_refactoring_type": "extract_method",+ "mechanical_steps": 1,+ "opportunity_id": "refop2_d82fe75fc83659cefa14",+ "rank_factors": {+ "benefit": 1.452,+ "cost": 1.0,+ "mechanical_share": 0.5,+ "primary_problem": 0.5,+ "risk": 0.0+ },+ "rank_score": 1.452,+ "recoverable_health": 1.452,+ "refactoring_model_version": 2,+ "step_count": 1,+ "steps": [+ {+ "applicability": {+ "classification": "mechanical",+ "facts": {+ "affected_file_count": 1,+ "blast_size": 0,+ "confidence": "high",+ "cross_file": false,+ "local_scope": true+ },+ "reasons": [+ "dataflow_proved_local_extraction"+ ],+ "unknowns": []+ },+ "confidence": "high",+ "effort_bucket": "S",+ "file_path": "account.ts",+ "impact_delta": 1.452,+ "plan_id": "refac2_a5f94bcfa0d5e0e24f37",+ "refactoring_type": "extract_method",+ "relocated_by": null,+ "source_biomarker": "complex_method",+ "target_symbol": "parseAccount"+ }+ ],+ "why_ranked": [+ {+ "factor": "benefit",+ "value": 1.452+ },+ {+ "factor": "cost",+ "value": 1.0+ },+ {+ "factor": "mechanical_share",+ "value": 0.5+ }+ ]+ },+ {+ "addresses_primary_problem": true,+ "affected_files": [+ "workspace.ts"+ ],+ "confidence": "high",+ "effort_bucket": "S",+ "evidence": [],+ "file_path": "workspace.ts",+ "judgment_steps": 0,+ "lead_biomarker": "complex_method",+ "lead_refactoring_type": "extract_method",+ "mechanical_steps": 1,+ "opportunity_id": "refop2_443f00cfefc5d4f86685",+ "rank_factors": {+ "benefit": 1.452,+ "cost": 1.0,+ "mechanical_share": 0.5,+ "primary_problem": 0.5,+ "risk": 0.0+ },+ "rank_score": 1.452,+ "recoverable_health": 1.452,+ "refactoring_model_version": 2,+ "step_count": 1,+ "steps": [+ {+ "applicability": {+ "classification": "mechanical",+ "facts": {+ "affected_file_count": 1,+ "blast_size": 0,+ "confidence": "high",+ "cross_file": false,+ "local_scope": true+ },+ "reasons": [+ "dataflow_proved_local_extraction"+ ],+ "unknowns": []+ },+ "confidence": "high",+ "effort_bucket": "S",+ "file_path": "workspace.ts",+ "impact_delta": 1.452,+ "plan_id": "refac2_b21dea1501a82eec255a",+ "refactoring_type": "extract_method",+ "relocated_by": null,+ "source_biomarker": "complex_method",+ "target_symbol": "parseWorkspace"+ }+ ],+ "why_ranked": [+ {+ "factor": "benefit",+ "value": 1.452+ },+ {+ "factor": "cost",+ "value": 1.0+ },+ {+ "factor": "mechanical_share",+ "value": 0.5+ }+ ]+ }+ ],+ "web": [+ {+ "addresses_primary_problem": false,+ "affected_files": [+ "handlers.py"+ ],+ "confidence": "high",+ "effort_bucket": "S",+ "evidence": [+ {+ "plan_id": "refac2_aa609dc289a6e9572306",+ "refactoring_type": "extract_helper",+ "source_biomarker": "dry_violation",+ "summary": {+ "co_change_count": 0,+ "duplicated_lines": 21,+ "is_intra_file": true,+ "occurrence_count": 3,+ "token_count": 14000+ },+ "target_symbol": "handlers.py:25-45"+ },+ {+ "plan_id": "refac2_8ea65569516929f43f5b",+ "refactoring_type": "extract_helper",+ "source_biomarker": "dry_violation",+ "summary": {+ "co_change_count": 0,+ "duplicated_lines": 21,+ "is_intra_file": true,+ "occurrence_count": 2,+ "token_count": 7050+ },+ "target_symbol": "handlers.py:87-107"+ }+ ],+ "file_path": "handlers.py",+ "judgment_steps": 0,+ "lead_biomarker": "dry_violation",+ "lead_refactoring_type": "extract_method",+ "mechanical_steps": 3,+ "opportunity_id": "refop2_1a90a90d31e0cde5d50b",+ "rank_factors": {+ "benefit": 0.75,+ "cost": 3.0,+ "mechanical_share": 0.5,+ "primary_problem": 0.0,+ "risk": 0.0+ },+ "rank_score": 0.2812,+ "recoverable_health": 0.75,+ "refactoring_model_version": 2,+ "step_count": 3,+ "steps": [+ {+ "applicability": {+ "classification": "mechanical",+ "facts": {+ "affected_file_count": 1,+ "blast_size": 0,+ "confidence": "high",+ "cross_file": false,+ "local_scope": true+ },+ "reasons": [+ "dataflow_proved_local_extraction"+ ],+ "unknowns": []+ },+ "confidence": "high",+ "effort_bucket": "S",+ "file_path": "handlers.py",+ "impact_delta": 0.25,+ "plan_id": "refac2_cdc5177783ea57d763e5",+ "refactoring_type": "extract_method",+ "relocated_by": null,+ "source_biomarker": "complex_method",+ "target_symbol": "read_account"+ },+ {+ "applicability": {+ "classification": "mechanical",+ "facts": {+ "affected_file_count": 1,+ "blast_size": 0,+ "confidence": "high",+ "cross_file": false,+ "local_scope": true+ },+ "reasons": [+ "dataflow_proved_local_extraction"+ ],+ "unknowns": []+ },+ "confidence": "high",+ "effort_bucket": "S",+ "file_path": "handlers.py",+ "impact_delta": 0.25,+ "plan_id": "refac2_48c888afc5af0d975522",+ "refactoring_type": "extract_method",+ "relocated_by": null,+ "source_biomarker": "complex_method",+ "target_symbol": "read_workspace"+ },+ {+ "applicability": {+ "classification": "mechanical",+ "facts": {+ "affected_file_count": 1,+ "blast_size": 0,+ "confidence": "high",+ "cross_file": false,+ "local_scope": true+ },+ "reasons": [+ "dataflow_proved_local_extraction"+ ],+ "unknowns": []+ },+ "confidence": "high",+ "effort_bucket": "S",+ "file_path": "handlers.py",+ "impact_delta": 0.25,+ "plan_id": "refac2_4ecbf32a9c6419829a56",+ "refactoring_type": "extract_method",+ "relocated_by": null,+ "source_biomarker": "complex_method",+ "target_symbol": "read_project"+ }+ ],+ "why_ranked": [+ {+ "factor": "cost",+ "value": 3.0+ },+ {+ "factor": "benefit",+ "value": 0.75+ },+ {+ "factor": "mechanical_share",+ "value": 0.5+ }+ ]+ }+ ]+}diff --git a/tests/fixtures/refactoring_corpus/trees/gopkg/inventory.go b/tests/fixtures/refactoring_corpus/trees/gopkg/inventory.gonew file mode 100644index 000000000..74cd7af9d--- /dev/null+++ b/tests/fixtures/refactoring_corpus/trees/gopkg/inventory.go@@ -0,0 +1,362 @@+// Archetype: a Go file that has grown two independent responsibilities.+//+// Splitting it into sibling files in the same package rewrites no import in any+// caller, because Go package members keep their qualified name whichever file+// declares them. That is the one structural refactoring this layer can call+// mechanical, and this fixture is what pins it.++package inventory++import (+ "errors"+ "fmt"+ "sort"+ "strings"+)++var ErrNotFound = errors.New("not found")++type Stock struct {+ SKU string+ OnHand int+ Reserved int+ Bin string+}++func NewStock(sku string, onHand int, bin string) *Stock {+ return &Stock{SKU: sku, OnHand: onHand, Bin: strings.ToUpper(bin)}+}++func (s *Stock) Available() int {+ if s.Reserved > s.OnHand {+ return 0+ }+ return s.OnHand - s.Reserved+}++func (s *Stock) Reserve(units int) error {+ if units <= 0 {+ return fmt.Errorf("reserve %d: %w", units, errors.ErrUnsupported)+ }+ if units > s.Available() {+ return fmt.Errorf("reserve %d of %s: %w", units, s.SKU, ErrNotFound)+ }+ s.Reserved += units+ return nil+}++func (s *Stock) Release(units int) {+ if units <= 0 {+ return+ }+ if units > s.Reserved {+ s.Reserved = 0+ return+ }+ s.Reserved -= units+}++func (s *Stock) Receive(units int) {+ if units > 0 {+ s.OnHand += units+ }+}++func StockBySKU(items []*Stock) map[string]*Stock {+ out := make(map[string]*Stock, len(items))+ for _, item := range items {+ if item == nil || item.SKU == "" {+ continue+ }+ out[item.SKU] = item+ }+ return out+}++func TotalAvailable(items []*Stock) int {+ total := 0+ for _, item := range items {+ if item == nil {+ continue+ }+ total += item.Available()+ }+ return total+}++func LowStock(items []*Stock, threshold int) []*Stock {+ var low []*Stock+ for _, item := range items {+ if item == nil {+ continue+ }+ if item.Available() < threshold {+ low = append(low, item)+ }+ }+ sort.Slice(low, func(i, j int) bool { return low[i].SKU < low[j].SKU })+ return low+}++func RebinStock(items []*Stock, from string, to string) int {+ moved := 0+ for _, item := range items {+ if item == nil {+ continue+ }+ if item.Bin == strings.ToUpper(from) {+ item.Bin = strings.ToUpper(to)+ moved+++ }+ }+ return moved+}++type Supplier struct {+ Code string+ Name string+ Country string+ LeadDays int+}++func NewSupplier(code string, name string, country string) *Supplier {+ return &Supplier{Code: strings.ToUpper(code), Name: name, Country: strings.ToUpper(country)}+}++func (s *Supplier) Label() string {+ if s.Name == "" {+ return s.Code+ }+ return fmt.Sprintf("%s (%s)", s.Name, s.Code)+}++func (s *Supplier) Domestic(home string) bool {+ return s.Country == strings.ToUpper(home)+}++func (s *Supplier) Slower(other *Supplier) bool {+ if other == nil {+ return false+ }+ return s.LeadDays > other.LeadDays+}++func SupplierByCode(suppliers []*Supplier) map[string]*Supplier {+ out := make(map[string]*Supplier, len(suppliers))+ for _, supplier := range suppliers {+ if supplier == nil || supplier.Code == "" {+ continue+ }+ out[supplier.Code] = supplier+ }+ return out+}++func FastestSupplier(suppliers []*Supplier) *Supplier {+ var best *Supplier+ for _, supplier := range suppliers {+ if supplier == nil {+ continue+ }+ if best == nil || supplier.Slower(best) == false && best.Slower(supplier) {+ best = supplier+ }+ }+ return best+}++func DomesticSuppliers(suppliers []*Supplier, home string) []*Supplier {+ var out []*Supplier+ for _, supplier := range suppliers {+ if supplier == nil {+ continue+ }+ if supplier.Domestic(home) {+ out = append(out, supplier)+ }+ }+ sort.Slice(out, func(i, j int) bool { return out[i].Code < out[j].Code })+ return out+}++func SupplierLabels(suppliers []*Supplier) []string {+ labels := make([]string, 0, len(suppliers))+ for _, supplier := range suppliers {+ if supplier == nil {+ continue+ }+ labels = append(labels, supplier.Label())+ }+ sort.Strings(labels)+ return labels+}++func RenameSupplier(suppliers []*Supplier, code string, name string) error {+ for _, supplier := range suppliers {+ if supplier == nil {+ continue+ }+ if supplier.Code == strings.ToUpper(code) {+ supplier.Name = name+ return nil+ }+ }+ return fmt.Errorf("rename %s: %w", code, ErrNotFound)+}++type PurchaseOrder struct {+ Ref string+ Supplier string+ Lines []OrderLine+ State string+}++type OrderLine struct {+ SKU string+ Units int+ Price float64+}++func NewPurchaseOrder(ref string, supplier string) *PurchaseOrder {+ return &PurchaseOrder{Ref: strings.ToUpper(ref), Supplier: strings.ToUpper(supplier), State: "draft"}+}++func (o *PurchaseOrder) AddLine(sku string, units int, price float64) error {+ if units <= 0 {+ return fmt.Errorf("add %s: units must be positive", sku)+ }+ if price < 0 {+ return fmt.Errorf("add %s: price must not be negative", sku)+ }+ for index := range o.Lines {+ if o.Lines[index].SKU == sku {+ o.Lines[index].Units += units+ return nil+ }+ }+ o.Lines = append(o.Lines, OrderLine{SKU: sku, Units: units, Price: price})+ return nil+}++func (o *PurchaseOrder) Value() float64 {+ total := 0.0+ for _, line := range o.Lines {+ total += float64(line.Units) * line.Price+ }+ return total+}++func (o *PurchaseOrder) Submit() error {+ if o.State != "draft" {+ return fmt.Errorf("submit %s: state is %s", o.Ref, o.State)+ }+ if len(o.Lines) == 0 {+ return fmt.Errorf("submit %s: no lines", o.Ref)+ }+ o.State = "submitted"+ return nil+}++func (o *PurchaseOrder) Cancel(reason string) error {+ if o.State == "received" {+ return fmt.Errorf("cancel %s: already received", o.Ref)+ }+ if strings.TrimSpace(reason) == "" {+ return fmt.Errorf("cancel %s: reason required", o.Ref)+ }+ o.State = "cancelled"+ return nil+}++func OrdersBySupplier(orders []*PurchaseOrder) map[string][]*PurchaseOrder {+ out := make(map[string][]*PurchaseOrder)+ for _, order := range orders {+ if order == nil || order.Supplier == "" {+ continue+ }+ out[order.Supplier] = append(out[order.Supplier], order)+ }+ for supplier := range out {+ group := out[supplier]+ sort.Slice(group, func(i, j int) bool { return group[i].Ref < group[j].Ref })+ }+ return out+}++func OpenOrders(orders []*PurchaseOrder) []*PurchaseOrder {+ var open []*PurchaseOrder+ for _, order := range orders {+ if order == nil {+ continue+ }+ if order.State == "draft" || order.State == "submitted" {+ open = append(open, order)+ }+ }+ sort.Slice(open, func(i, j int) bool { return open[i].Ref < open[j].Ref })+ return open+}++func OrderBacklogValue(orders []*PurchaseOrder) float64 {+ total := 0.0+ for _, order := range OpenOrders(orders) {+ total += order.Value()+ }+ return total+}++func FindOrder(orders []*PurchaseOrder, ref string) (*PurchaseOrder, error) {+ for _, order := range orders {+ if order == nil {+ continue+ }+ if order.Ref == strings.ToUpper(ref) {+ return order, nil+ }+ }+ return nil, fmt.Errorf("order %s: %w", ref, ErrNotFound)+}++func OrderRefs(orders []*PurchaseOrder) []string {+ refs := make([]string, 0, len(orders))+ for _, order := range orders {+ if order == nil {+ continue+ }+ refs = append(refs, order.Ref)+ }+ sort.Strings(refs)+ return refs+}++func ReceiveOrder(order *PurchaseOrder, stock []*Stock) (int, error) {+ if order == nil {+ return 0, fmt.Errorf("receive: %w", ErrNotFound)+ }+ if order.State != "submitted" {+ return 0, fmt.Errorf("receive %s: state is %s", order.Ref, order.State)+ }+ index := StockBySKU(stock)+ received := 0+ for _, line := range order.Lines {+ item, ok := index[line.SKU]+ if !ok {+ continue+ }+ item.Receive(line.Units)+ received += line.Units+ }+ order.State = "received"+ return received, nil+}++func OrderSummary(order *PurchaseOrder) string {+ if order == nil {+ return ""+ }+ units := 0+ for _, line := range order.Lines {+ units += line.Units+ }+ return fmt.Sprintf("%s %s units=%d value=%.2f", order.Ref, order.State, units, order.Value())+}diff --git a/tests/fixtures/refactoring_corpus/trees/orm/models.py b/tests/fixtures/refactoring_corpus/trees/orm/models.pynew file mode 100644index 000000000..01b0b2792--- /dev/null+++ b/tests/fixtures/refactoring_corpus/trees/orm/models.py@@ -0,0 +1,53 @@+# Archetype: declarative ORM model file.+#+# Every class here is a run of near-identical column declarations. A clone+# detector sees the repetition; a helper function cannot express it, because a+# declarative attribute is evaluated in the class body and bound to the class.+# The correct composed answer for this file is therefore no clone *step* - at+# most supporting evidence - which is what the composition corpus pins.++from sqlalchemy import ForeignKey, String+from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column+++class Base(DeclarativeBase):+ pass+++class Account(Base):+ __tablename__ = "accounts"++ id: Mapped[str] = mapped_column(String(36), primary_key=True)+ created_at: Mapped[str] = mapped_column(String(32), nullable=False)+ updated_at: Mapped[str] = mapped_column(String(32), nullable=False)+ display_name: Mapped[str] = mapped_column(String(200), nullable=False)+ email: Mapped[str] = mapped_column(String(320), nullable=False, index=True)+ status: Mapped[str] = mapped_column(String(32), nullable=False, default="open")+ region: Mapped[str] = mapped_column(String(32), nullable=False, default="eu")+ tier: Mapped[str] = mapped_column(String(32), nullable=False, default="free")+++class Workspace(Base):+ __tablename__ = "workspaces"++ id: Mapped[str] = mapped_column(String(36), primary_key=True)+ created_at: Mapped[str] = mapped_column(String(32), nullable=False)+ updated_at: Mapped[str] = mapped_column(String(32), nullable=False)+ display_name: Mapped[str] = mapped_column(String(200), nullable=False)+ slug: Mapped[str] = mapped_column(String(200), nullable=False, index=True)+ status: Mapped[str] = mapped_column(String(32), nullable=False, default="open")+ region: Mapped[str] = mapped_column(String(32), nullable=False, default="eu")+ tier: Mapped[str] = mapped_column(String(32), nullable=False, default="free")+++class Project(Base):+ __tablename__ = "projects"++ id: Mapped[str] = mapped_column(String(36), primary_key=True)+ created_at: Mapped[str] = mapped_column(String(32), nullable=False)+ updated_at: Mapped[str] = mapped_column(String(32), nullable=False)+ display_name: Mapped[str] = mapped_column(String(200), nullable=False)+ workspace_id: Mapped[str] = mapped_column(ForeignKey("workspaces.id"), index=True)+ status: Mapped[str] = mapped_column(String(32), nullable=False, default="open")+ region: Mapped[str] = mapped_column(String(32), nullable=False, default="eu")+ tier: Mapped[str] = mapped_column(String(32), nullable=False, default="free")diff --git a/tests/fixtures/refactoring_corpus/trees/tsapp/account.ts b/tests/fixtures/refactoring_corpus/trees/tsapp/account.tsnew file mode 100644index 000000000..4201b0d53--- /dev/null+++ b/tests/fixtures/refactoring_corpus/trees/tsapp/account.ts@@ -0,0 +1,73 @@+// Supporting module for the barrel archetype, and a second archetype of its+// own: a long branch-heavy function that the Extract Method gate can reason+// about, so the tree exercises composition on TypeScript rather than only on+// Python.++export interface Account {+ id: string;+ displayName: string;+ email: string;+ status: string;+ balanceCents: number;+ tags: string[];+}++export function parseAccount(raw: Record<string, unknown>): Account {+ const id = typeof raw.id === "string" ? raw.id.trim() : "";+ if (!id) {+ throw new Error("account requires an id");+ }+ let displayName = "";+ if (typeof raw.displayName === "string") {+ displayName = raw.displayName.trim();+ } else if (typeof raw.name === "string") {+ displayName = raw.name.trim();+ } else {+ displayName = id;+ }+ let email = "";+ if (typeof raw.email === "string" && raw.email.includes("@")) {+ email = raw.email.trim().toLowerCase();+ } else {+ email = "";+ }+ let status = "open";+ if (typeof raw.status === "string" && raw.status.length > 0) {+ status = raw.status.trim().toLowerCase();+ }+ let balanceCents = 0;+ if (typeof raw.balanceCents === "number" && Number.isFinite(raw.balanceCents)) {+ balanceCents = Math.round(raw.balanceCents);+ } else if (typeof raw.balance === "number" && Number.isFinite(raw.balance)) {+ balanceCents = Math.round(raw.balance * 100);+ } else {+ balanceCents = 0;+ }+ const tags: string[] = [];+ if (Array.isArray(raw.tags)) {+ for (const tag of raw.tags) {+ if (typeof tag === "string" && tag.trim().length > 0) {+ tags.push(tag.trim().toLowerCase());+ }+ }+ }+ tags.sort();+ return { id, displayName, email, status, balanceCents, tags };+}++export function formatAccount(account: Account): string {+ const parts: string[] = [];+ parts.push(`id=${account.id}`);+ if (account.displayName) {+ parts.push(`name=${account.displayName}`);+ }+ if (account.email) {+ parts.push(`email=${account.email}`);+ }+ parts.push(`status=${account.status}`);+ parts.push(`balance=${(account.balanceCents / 100).toFixed(2)}`);+ if (account.tags.length > 0) {+ parts.push(`tags=${account.tags.join("|")}`);+ }+ return parts.join(" ");+}diff --git a/tests/fixtures/refactoring_corpus/trees/tsapp/index.ts b/tests/fixtures/refactoring_corpus/trees/tsapp/index.tsnew file mode 100644index 000000000..714d9fc8e--- /dev/null+++ b/tests/fixtures/refactoring_corpus/trees/tsapp/index.ts@@ -0,0 +1,13 @@+// Archetype: a TypeScript re-export barrel.+//+// Every line is structurally identical to its neighbours, so a clone detector+// reads the file as wall-to-wall duplication. There is nothing to extract: the+// repetition *is* the module's content. The correct composed answer is silence,+// or at most evidence, never a step instructing a shared helper.++export { parseAccount } from "./account";+export { formatAccount } from "./account";+export { parseWorkspace } from "./workspace";+export { formatWorkspace } from "./workspace";+export type { Account } from "./account";+export type { Workspace } from "./workspace";diff --git a/tests/fixtures/refactoring_corpus/trees/tsapp/workspace.ts b/tests/fixtures/refactoring_corpus/trees/tsapp/workspace.tsnew file mode 100644index 000000000..308380850--- /dev/null+++ b/tests/fixtures/refactoring_corpus/trees/tsapp/workspace.ts@@ -0,0 +1,73 @@+// Supporting module for the barrel archetype, and deliberately a near-duplicate+// of account.ts: a real cross-file clone with no co-change history behind it,+// which is the shape the composer demotes to evidence rather than instructing a+// shared helper over.++export interface Workspace {+ id: string;+ displayName: string;+ email: string;+ status: string;+ seatCount: number;+ tags: string[];+}++export function parseWorkspace(raw: Record<string, unknown>): Workspace {+ const id = typeof raw.id === "string" ? raw.id.trim() : "";+ if (!id) {+ throw new Error("workspace requires an id");+ }+ let displayName = "";+ if (typeof raw.displayName === "string") {+ displayName = raw.displayName.trim();+ } else if (typeof raw.name === "string") {+ displayName = raw.name.trim();+ } else {+ displayName = id;+ }+ let email = "";+ if (typeof raw.email === "string" && raw.email.includes("@")) {+ email = raw.email.trim().toLowerCase();+ } else {+ email = "";+ }+ let status = "open";+ if (typeof raw.status === "string" && raw.status.length > 0) {+ status = raw.status.trim().toLowerCase();+ }+ let seatCount = 0;+ if (typeof raw.seatCount === "number" && Number.isFinite(raw.seatCount)) {+ seatCount = Math.round(raw.seatCount);+ } else if (typeof raw.seats === "number" && Number.isFinite(raw.seats)) {+ seatCount = Math.round(raw.seats * 100);+ } else {+ seatCount = 0;+ }+ const tags: string[] = [];+ if (Array.isArray(raw.tags)) {+ for (const tag of raw.tags) {+ if (typeof tag === "string" && tag.trim().length > 0) {+ tags.push(tag.trim().toLowerCase());+ }+ }+ }+ tags.sort();+ return { id, displayName, email, status, seatCount, tags };+}++export function formatWorkspace(workspace: Workspace): string {+ const parts: string[] = [];+ parts.push(`id=${workspace.id}`);+ if (workspace.displayName) {+ parts.push(`name=${workspace.displayName}`);+ }+ if (workspace.email) {+ parts.push(`email=${workspace.email}`);+ }+ parts.push(`status=${workspace.status}`);+ parts.push(`seats=${(workspace.seatCount / 100).toFixed(2)}`);+ if (workspace.tags.length > 0) {+ parts.push(`tags=${workspace.tags.join("|")}`);+ }+ return parts.join(" ");+}diff --git a/tests/fixtures/refactoring_corpus/trees/web/handlers.py b/tests/fixtures/refactoring_corpus/trees/web/handlers.pynew file mode 100644index 000000000..6bfd24638--- /dev/null+++ b/tests/fixtures/refactoring_corpus/trees/web/handlers.py@@ -0,0 +1,205 @@+# Archetype: a framework-registered router module.+#+# Every function here is reachable only because a decorator registered it with+# a router. Nothing in the call graph calls them, and moving one to another+# module changes the import path the registry was populated from. The correct+# composed answer is that any step which *moves* one of these is a judgment+# call, never mechanical: the layer cannot see the registration, and says so.+#+# A lifted span is the exception and is allowed to be mechanical - it adds a+# private helper beside the handler and moves no registered symbol.++from fastapi import APIRouter, HTTPException++router = APIRouter()++_ACCOUNTS: dict[str, dict[str, object]] = {}+_WORKSPACES: dict[str, dict[str, object]] = {}+_PROJECTS: dict[str, dict[str, object]] = {}++[email protected]("/accounts/{account_id}")+def read_account(account_id: str, expand: str = "") -> dict[str, object]:+ record = _ACCOUNTS.get(account_id)+ if record is None:+ raise HTTPException(status_code=404, detail="no such account")+ normalized: dict[str, object] = {}+ for key, value in record.items():+ if key.startswith("_"):+ continue+ if isinstance(value, str):+ normalized[key] = value.strip()+ elif isinstance(value, bool):+ normalized[key] = value+ elif isinstance(value, (int, float)):+ normalized[key] = round(float(value), 2)+ elif isinstance(value, list):+ normalized[key] = sorted(str(item) for item in value)+ else:+ normalized[key] = str(value)+ if expand:+ wanted = {part.strip() for part in expand.split(",") if part.strip()}+ for name in sorted(wanted):+ if name not in normalized:+ normalized[name] = None+ normalized["links"] = {"self": f"/accounts/{account_id}"}+ return normalized++[email protected]("/accounts/{account_id}/close")+def close_account(account_id: str, reason: str = "", force: bool = False) -> dict[str, object]:+ record = _ACCOUNTS.get(account_id)+ if record is None:+ raise HTTPException(status_code=404, detail="no such account")+ if record.get("status") == "closed" and not force:+ raise HTTPException(status_code=409, detail="already closed")+ cleaned = reason.strip()+ if not cleaned and not force:+ raise HTTPException(status_code=422, detail="reason required")+ audit: list[str] = []+ for key, value in sorted(record.items()):+ if key.startswith("_"):+ continue+ if isinstance(value, str) and not value:+ continue+ audit.append(f"{key}={value}")+ record["status"] = "closed"+ record["close_reason"] = cleaned+ record["_audit"] = audit+ return {"account_id": account_id, "status": "closed", "audit_entries": len(audit)}++[email protected]("/accounts")+def list_accounts(status: str = "", limit: int = 50) -> dict[str, object]:+ rows: list[dict[str, object]] = []+ for key, record in sorted(_ACCOUNTS.items()):+ if status and record.get("status") != status:+ continue+ rows.append({"id": key, "status": record.get("status", "open")})+ if len(rows) >= max(1, limit):+ break+ return {"items": rows, "count": len(rows), "truncated": len(rows) >= max(1, limit)}+[email protected]("/workspaces/{workspace_id}")+def read_workspace(workspace_id: str, expand: str = "") -> dict[str, object]:+ record = _WORKSPACES.get(workspace_id)+ if record is None:+ raise HTTPException(status_code=404, detail="no such workspace")+ normalized: dict[str, object] = {}+ for key, value in record.items():+ if key.startswith("_"):+ continue+ if isinstance(value, str):+ normalized[key] = value.strip()+ elif isinstance(value, bool):+ normalized[key] = value+ elif isinstance(value, (int, float)):+ normalized[key] = round(float(value), 2)+ elif isinstance(value, list):+ normalized[key] = sorted(str(item) for item in value)+ else:+ normalized[key] = str(value)+ if expand:+ wanted = {part.strip() for part in expand.split(",") if part.strip()}+ for name in sorted(wanted):+ if name not in normalized:+ normalized[name] = None+ normalized["links"] = {"self": f"/workspaces/{workspace_id}"}+ return normalized++[email protected]("/workspaces/{workspace_id}/close")+def close_workspace(workspace_id: str, reason: str = "", force: bool = False) -> dict[str, object]:+ record = _WORKSPACES.get(workspace_id)+ if record is None:+ raise HTTPException(status_code=404, detail="no such workspace")+ if record.get("status") == "closed" and not force:+ raise HTTPException(status_code=409, detail="already closed")+ cleaned = reason.strip()+ if not cleaned and not force:+ raise HTTPException(status_code=422, detail="reason required")+ audit: list[str] = []+ for key, value in sorted(record.items()):+ if key.startswith("_"):+ continue+ if isinstance(value, str) and not value:+ continue+ audit.append(f"{key}={value}")+ record["status"] = "closed"+ record["close_reason"] = cleaned+ record["_audit"] = audit+ return {"workspace_id": workspace_id, "status": "closed", "audit_entries": len(audit)}++[email protected]("/workspaces")+def list_workspaces(status: str = "", limit: int = 50) -> dict[str, object]:+ rows: list[dict[str, object]] = []+ for key, record in sorted(_WORKSPACES.items()):+ if status and record.get("status") != status:+ continue+ rows.append({"id": key, "status": record.get("status", "open")})+ if len(rows) >= max(1, limit):+ break+ return {"items": rows, "count": len(rows), "truncated": len(rows) >= max(1, limit)}+[email protected]("/projects/{project_id}")+def read_project(project_id: str, expand: str = "") -> dict[str, object]:+ record = _PROJECTS.get(project_id)+ if record is None:+ raise HTTPException(status_code=404, detail="no such project")+ normalized: dict[str, object] = {}+ for key, value in record.items():+ if key.startswith("_"):+ continue+ if isinstance(value, str):+ normalized[key] = value.strip()+ elif isinstance(value, bool):+ normalized[key] = value+ elif isinstance(value, (int, float)):+ normalized[key] = round(float(value), 2)+ elif isinstance(value, list):+ normalized[key] = sorted(str(item) for item in value)+ else:+ normalized[key] = str(value)+ if expand:+ wanted = {part.strip() for part in expand.split(",") if part.strip()}+ for name in sorted(wanted):+ if name not in normalized:+ normalized[name] = None+ normalized["links"] = {"self": f"/projects/{project_id}"}+ return normalized++[email protected]("/projects/{project_id}/close")+def close_project(project_id: str, reason: str = "", force: bool = False) -> dict[str, object]:+ record = _PROJECTS.get(project_id)+ if record is None:+ raise HTTPException(status_code=404, detail="no such project")+ if record.get("status") == "closed" and not force:+ raise HTTPException(status_code=409, detail="already closed")+ cleaned = reason.strip()+ if not cleaned and not force:+ raise HTTPException(status_code=422, detail="reason required")+ audit: list[str] = []+ for key, value in sorted(record.items()):+ if key.startswith("_"):+ continue+ if isinstance(value, str) and not value:+ continue+ audit.append(f"{key}={value}")+ record["status"] = "closed"+ record["close_reason"] = cleaned+ record["_audit"] = audit+ return {"project_id": project_id, "status": "closed", "audit_entries": len(audit)}++[email protected]("/projects")+def list_projects(status: str = "", limit: int = 50) -> dict[str, object]:+ rows: list[dict[str, object]] = []+ for key, record in sorted(_PROJECTS.items()):+ if status and record.get("status") != status:+ continue+ rows.append({"id": key, "status": record.get("status", "open")})+ if len(rows) >= max(1, limit):+ break+ return {"items": rows, "count": len(rows), "truncated": len(rows) >= max(1, limit)}diff --git a/tests/unit/health/refactoring_tree_fixture.py b/tests/unit/health/refactoring_tree_fixture.pynew file mode 100644index 000000000..0b6d6a7c1--- /dev/null+++ b/tests/unit/health/refactoring_tree_fixture.py@@ -0,0 +1,154 @@+"""Loader for the checked-in opportunity-composition corpus.++The corpus is a small source tree under+``tests/fixtures/refactoring_corpus/trees``, one directory per archetype, run+through the real analyzer and the real composer. No repository download, no+index, no network, and no hand-written plan payloads: what the golden pins is+what the shipped pipeline produces.++The tree is deliberately not Repowise code. Repowise is the dogfood repo, never+the tuning target, so an archetype has to hold on source the layer has never+been fitted to.++``MANIFEST`` states each archetype's expected answer in prose next to the+directory it lives in, and ``UNCOVERED`` declares the archetypes nobody has+written yet, so a gap reads as a gap rather than as a clean run.++Regenerate the golden with ``REPOWISE_REWRITE_REFACTORING_GOLDEN=1``; never+hand-edit it.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++from .refactoring_corpus_fixture import ( # noqa: F401 (shared regenerate switch)+ CORPUS_DIR,+ REWRITE_ENV,+ load_golden,+ rewrite_requested,+ write_golden,+)++TREES_DIR = CORPUS_DIR / "trees"++# archetype directory -> what the layer is expected to conclude about it.+MANIFEST: dict[str, str] = {+ "orm": (+ "Declarative ORM columns repeat by construction and cannot be lifted into "+ "a function. The gates drop the repetition before it reaches a plan, so "+ "the archetype's answer is silence."+ ),+ "web": (+ "Handlers exist only because a decorator registered them. A lifted span "+ "beside one is mechanical - it moves nothing the router holds - while the "+ "duplication across the three read handlers stays evidence, because "+ "nothing here proves the sites move together."+ ),+ "gopkg": (+ "Three responsibilities in one Go file, over the split threshold. A split "+ "is offered and is a judgment call: the groups cannot be named, and no "+ "split can prove the file carries no build constraint."+ ),+ "tsapp": (+ "A re-export barrel is duplication that is the module's content, and its "+ "two parser modules are a real cross-file clone with no co-change history "+ "behind it. Neither earns a step; the branch-heavy parsers do."+ ),+}++# Archetypes and paths the corpus does not cover, declared rather than silently+# missing, so a run over four trees is never read as coverage of eleven language+# tags or of every classification branch.+UNCOVERED: tuple[str, ...] = (+ "A mechanical structural step of any kind. Extraction is the only mechanical "+ "class: a split cannot prove the source file carries no build constraint "+ "(a Go ``_linux.go`` basename or a ``//go:build`` line), and that fact does "+ "not reach this layer. ``gopkg`` also fails the naming test independently, "+ "because split_file groups by call edges and Go receiver typing does not "+ "resolve method calls.",+ "Any co-change-backed clone. A fixture tree has no git history, so "+ "``co_change_count`` is 0 everywhere and every clone demotes to evidence. "+ "The promotion side of the rule is only observable on a real repository.",+ "Java: an interface-implementing class where Extract Class would break the "+ "declared contract.",+ "C#: partial-class fragments, where a split's symbols already span files.",+ "Rust: a trait impl block, where moving a method changes which trait it "+ "satisfies.",+ "C++: a header/implementation pair, where a split has to move two files in "+ "step.",+ "Generated and vendored paths, where the correct answer is silence "+ "regardless of shape.",+)+++def analyze_tree(root: Path) -> Any:+ """Run the shipped ingestion + health pass over *root*. No DB, no git."""+ from repowise.core.analysis.health import HealthAnalyzer+ from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder++ traverser = FileTraverser(root)+ parser = ASTParser()+ graph_builder = GraphBuilder(root)+ parsed_files = []+ for info in traverser.traverse():+ try:+ parsed = parser.parse_file(info, Path(info.abs_path).read_bytes())+ except Exception:+ # A grammar this build lacks is a skipped file, not a failed run.+ continue+ graph_builder.add_file(parsed)+ parsed_files.append(parsed)+ graph_builder.build()+ analyzer = HealthAnalyzer(+ graph_builder.graph(),+ git_meta_map={},+ parsed_files=parsed_files,+ repo_root=root,+ )+ return analyzer.analyze(None)+++def compose_tree(root: Path) -> list[dict[str, Any]]:+ """The composed opportunities for one archetype tree, golden-ready."""+ from repowise.core.analysis.health.models import primary_biomarker_by_file+ from repowise.core.analysis.health.refactoring import compose_opportunities++ report = analyze_tree(root)+ opportunities = compose_opportunities(+ getattr(report, "refactoring_suggestions", None) or [],+ primary_biomarker_by_file=primary_biomarker_by_file(report.findings),+ )+ return [_stable(item.as_dict()) for item in opportunities]+++def plans_for_tree(root: Path) -> list[dict[str, Any]]:+ """The raw plans behind one tree, for the demotion assertions."""+ report = analyze_tree(root)+ return [+ {+ "refactoring_type": item.refactoring_type,+ "file_path": item.file_path,+ "evidence": dict(item.evidence or {}),+ }+ for item in (getattr(report, "refactoring_suggestions", None) or [])+ ]+++def _stable(payload: dict[str, Any]) -> dict[str, Any]:+ """Drop the fields that are a function of the checkout, not the archetype.++ Absolute paths and line numbers move when the fixture is edited for reasons+ the golden is not about; the ids, order, membership, classification and+ ranking are what it exists to pin.+ """+ payload = dict(payload)+ for step in payload.get("steps", []):+ step.pop("line_start", None)+ step.pop("line_end", None)+ return payload+++def archetype_roots() -> list[tuple[str, Path]]:+ return [(name, TREES_DIR / name) for name in sorted(MANIFEST) if (TREES_DIR / name).is_dir()]diff --git a/tests/unit/health/test_dataflow_langs.py b/tests/unit/health/test_dataflow_langs.pyindex fb24c8763..75ed2d42b 100644--- a/tests/unit/health/test_dataflow_langs.py+++ b/tests/unit/health/test_dataflow_langs.py@@ -1244,3 +1244,147 @@ def test_cpp_extraction_never_spans_a_jump():assert {"break_statement", "continue_statement"} <= lmap.break_kinds | lmap.continue_kindsassert "return_statement" in lmap.return_kindsassert "throw_statement" in lmap.raise_kinds+++# ---------------------------------------------------------------------------+# Nested scopes that bind a name in the enclosing scope (and the ones that do not)+# ---------------------------------------------------------------------------+++def _defs(analysis) -> set[tuple[str, int]]:+ return {+ (definition.var, definition.line)+ for block in analysis.def_use.blocks.values()+ for definition in block.defs+ }+++def test_python_nested_def_binds_its_name_in_the_enclosing_scope() -> None:+ """Without this a span calling a sibling closure omitted it from its IN set."""+ (analysis,) = [+ item+ for item in _analyses(+ "python",+ """+ def outer(rows):+ def helper(value):+ return value + 1+ total = 0+ for row in rows:+ total += helper(row)+ return total+ """,+ )+ if item.name == "outer"+ ]+ assert ("helper", 3) in _defs(analysis)+++def test_a_named_function_expression_binds_nothing_outside_itself() -> None:+ """JS scopes a function expression's own name to its body.++ Recording it as an enclosing definition would shadow an unrelated variable+ of the same name - the ``var fib = function fib(n) {...}`` idiom - and the+ slicer would then believe the span had already redefined it and drop it+ from the IN set.+ """+ (analysis,) = [+ item+ for item in _analyses(+ "typescript",+ """+ function outer(rows) {+ let bar = 5;+ var f = function bar() { return 1; };+ console.log(bar);+ return f;+ }+ """,+ )+ if item.name == "outer"+ ]+ defined = _defs(analysis)+ assert ("bar", 3) in defined, "the real let-binding must still be a definition"+ assert ("bar", 4) not in defined, "the function expression's own name is not ours"+++def test_a_function_declaration_does_bind_in_the_enclosing_scope() -> None:+ (analysis,) = [+ item+ for item in _analyses(+ "typescript",+ """+ function outer(rows) {+ function helper(v) { return v + 1; }+ let total = 0;+ for (const row of rows) { total += helper(row); }+ return total;+ }+ """,+ )+ if item.name == "outer"+ ]+ assert ("helper", 3) in _defs(analysis)+++def test_anonymous_scope_dialects_declare_no_enclosing_binders() -> None:+ """Go, Java and C++ have no nested construct that binds a name here."""+ from repowise.core.analysis.health.dataflow.dialects import get_defuse_dialect++ for language in ("go", "java", "cpp"):+ dialect = get_defuse_dialect(language)+ if dialect is None:+ continue+ assert not dialect.enclosing_binder_kinds, language+++def test_every_declared_binder_is_actually_a_scope_boundary() -> None:+ """A binder kind the walk never reaches would be silently dead."""+ from repowise.core.analysis.health.dataflow.dialects import get_defuse_dialect++ for language in ("python", "typescript", "go", "java", "rust", "cpp"):+ dialect = get_defuse_dialect(language)+ if dialect is None:+ continue+ for kind in dialect.enclosing_binder_kinds:+ node = type("N", (), {"type": kind})()+ assert dialect._is_scope_boundary(node), f"{language}: {kind}"+++def test_hoisted_binding_precompute_matches_the_direct_test() -> None:+ """The per-function precompute must decide exactly what a per-span scan would.++ ``_hoisted_bindings`` exists to keep the check off the candidate loop, where+ scanning every variable per span cost the analyzer real time. An optimisation+ that also changed the answer would be a silent behaviour change, so the two+ formulations are compared over every span shape the corpus produces.+ """+ from repowise.core.analysis.health.dataflow import slice as slicing+ from repowise.core.analysis.health.dataflow.dialects import get_defuse_dialect++ def directly(def_lines, use_lines, s, e) -> bool:+ for var, defs in def_lines.items():+ if not any(s <= ln <= e for ln in defs):+ continue+ if any(ln < s for ln in defs):+ continue+ if any(ln < s for ln in use_lines.get(var, [])):+ return True+ return False++ from .refactoring_corpus_fixture import CASE_FILES, source_for++ compared = 0+ for language, filename in CASE_FILES:+ if get_defuse_dialect(language) is None:+ continue+ result = analyze_file(filename, language, source_for(filename), flagged_only=False)+ for analysis in result.functions:+ def_lines, use_lines = slicing._var_lines(analysis.def_use)+ hoisted = slicing._hoisted_bindings(def_lines, use_lines)+ for low in range(analysis.start_line, analysis.end_line + 1):+ for high in range(low, analysis.end_line + 1):+ compared += 1+ precomputed = any(low <= d <= high and u < low for d, u in hoisted)+ assert precomputed == directly(def_lines, use_lines, low, high)+ assert compared, "the corpus produced no spans to compare"diff --git a/tests/unit/health/test_refactoring_corpus_golden.py b/tests/unit/health/test_refactoring_corpus_golden.pyindex 4191328b1..a40315ff7 100644--- a/tests/unit/health/test_refactoring_corpus_golden.py+++ b/tests/unit/health/test_refactoring_corpus_golden.py@@ -58,3 +58,19 @@ def test_sound_regions_are_still_offered(language: str, filename: str) -> None:assert marked, "corpus lost its sound markers"offered = offered_start_lines(language, filename)assert set(marked) <= offered, f"gate suppressed sound regions {sorted(set(marked) - offered)}"+++def test_a_span_calling_a_sibling_closure_receives_it() -> None:+ """A nested ``def`` binds a local name, and a span reading it takes it in.++ Measured on this repo's own ranked head before the fix:+ ``ingestion/dynamic_hints/cpp.py::extract`` offered a span that called a+ local ``_emit`` and did not list it, so the lifted helper would not run.+ """+ if get_defuse_dialect("python") is None:+ pytest.skip("no python dataflow dialect here")+ spans = extractions_for("python", "cases.py")["calls_a_sibling_closure"]+ calling = [span for span in spans if span["start_line"] >= 211]+ assert calling, "the archetype stopped offering a span after its closure"+ for span in calling:+ assert "emit" in span["params"], spandiff --git a/tests/unit/health/test_refactoring_opportunity.py b/tests/unit/health/test_refactoring_opportunity.pynew file mode 100644index 000000000..c7776ed01--- /dev/null+++ b/tests/unit/health/test_refactoring_opportunity.py@@ -0,0 +1,342 @@+"""Composition, ordering, demotion, identity and lifecycle for opportunities."""++from __future__ import annotations++import pytest++from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion+from repowise.core.analysis.health.refactoring.opportunity import (+ STEP_ORDER,+ compose_opportunities,+ is_standalone_clone,+ opportunity_public_id,+ opportunity_status,+)+++def plan(kind: str, symbol: str = "handle", **kwargs) -> RefactoringSuggestion:+ payload = {+ "refactoring_type": kind,+ "file_path": "svc/orders.py",+ "target_symbol": symbol,+ "line_start": 10,+ "line_end": 40,+ "plan": {},+ "evidence": {},+ "impact_delta": 1.0,+ "effort_bucket": "S",+ "blast_radius": {"scope": "local"},+ "confidence": "high",+ "source_biomarker": "complex_method",+ }+ payload.update(kwargs)+ return RefactoringSuggestion(**payload)+++def clone(*, intra: bool, co_change: int, **kwargs) -> RefactoringSuggestion:+ kwargs.setdefault("blast_radius", {"files": ["svc/billing.py"], "file_count": 1})+ return plan(+ "extract_helper",+ f"orders.py:{co_change}-{int(intra)}",+ evidence={"is_intra_file": intra, "co_change_count": co_change},+ impact_delta=0.0,+ source_biomarker="dry_violation",+ **kwargs,+ )+++def split(**kwargs) -> RefactoringSuggestion:+ return plan(+ "split_file",+ "orders.py -> 2 files",+ plan={+ "shim_required": True,+ "groups": [+ {"symbols": ["handle"], "suggested_file": "svc/orders_handle.py"},+ {"symbols": ["render"], "suggested_file": "svc/orders_render.py"},+ ],+ },+ evidence={"group_count": 2},+ impact_delta=0.0,+ blast_radius={"dependent_count": 3, "dependent_files": ["svc/api.py"]},+ source_biomarker="",+ **kwargs,+ )+++# --------------------------------------------------------------------------+# membership+# --------------------------------------------------------------------------+++def test_one_opportunity_per_file() -> None:+ rows = [plan("extract_method"), plan("extract_method", "render"), split()]+ opportunities = compose_opportunities(rows)+ assert len(opportunities) == 1+ assert opportunities[0].step_count == 3+++def test_files_are_not_merged() -> None:+ rows = [plan("extract_method"), plan("extract_method", file_path="svc/billing.py")]+ assert {item.file_path for item in compose_opportunities(rows)} == {+ "svc/orders.py",+ "svc/billing.py",+ }+++def test_performance_plans_are_left_to_their_own_layer() -> None:+ rows = [plan("performance_fix", plan={"opportunity_id": "perf2_abc"})]+ assert compose_opportunities(rows) == []+++# --------------------------------------------------------------------------+# clone demotion+# --------------------------------------------------------------------------+++ ("intra", "co_change", "standalone"),+ [+ (False, 3, True), # cross-file and co-changed: worth instructing+ (False, 2, False), # cross-file, but nobody edits them together+ (True, 9, False), # co-changed, but it is one file's own repetition+ (True, 0, False),+ ],+)+def test_only_cross_file_co_changed_clones_earn_a_step(+ intra: bool, co_change: int, standalone: bool+) -> None:+ assert is_standalone_clone(clone(intra=intra, co_change=co_change)) is standalone+++def test_demoted_clones_become_evidence_on_the_file_opportunity() -> None:+ rows = [plan("extract_method"), clone(intra=True, co_change=0)]+ opportunity = compose_opportunities(rows)[0]+ assert opportunity.step_count == 1+ assert [item.refactoring_type for item in opportunity.evidence] == ["extract_helper"]+ assert opportunity.evidence[0].summary["is_intra_file"] is True+++def test_a_file_with_only_demoted_clones_publishes_nothing() -> None:+ assert compose_opportunities([clone(intra=True, co_change=0)]) == []+++def test_a_high_signal_clone_is_a_step_not_evidence() -> None:+ opportunity = compose_opportunities([clone(intra=False, co_change=7)])[0]+ assert opportunity.step_count == 1+ assert opportunity.evidence == ()+++# --------------------------------------------------------------------------+# ordering+# --------------------------------------------------------------------------+++def test_structural_steps_precede_extractions() -> None:+ rows = [plan("extract_method"), clone(intra=False, co_change=5), split()]+ steps = compose_opportunities(rows)[0].steps+ assert [step.refactoring_type for step in steps] == [+ "split_file",+ "extract_method",+ "extract_helper",+ ]+++def test_step_order_covers_every_composed_type() -> None:+ from repowise.core.analysis.health.refactoring import registered_detectors+ from repowise.core.analysis.health.refactoring.opportunity import EXCLUDED_TYPES++ names = {detector.name for detector in registered_detectors()} - EXCLUDED_TYPES+ assert names <= set(STEP_ORDER), f"unordered detector types: {sorted(names - set(STEP_ORDER))}"+++def test_same_type_steps_order_by_position_then_symbol() -> None:+ rows = [+ plan("extract_method", "z", line_start=90),+ plan("extract_method", "a", line_start=10),+ ]+ steps = compose_opportunities(rows)[0].steps+ assert [step.target_symbol for step in steps] == ["a", "z"]+++def test_steps_after_a_relocation_say_they_must_be_located_again() -> None:+ steps = compose_opportunities([plan("extract_method"), split()])[0].steps+ assert steps[0].refactoring_type == "split_file"+ assert steps[0].relocated_by is None+ assert steps[1].relocated_by == steps[0].plan_id+++def test_no_relocation_leaves_every_step_addressable_as_written() -> None:+ steps = compose_opportunities([plan("extract_method"), plan("extract_method", "x")])[0].steps+ assert all(step.relocated_by is None for step in steps)+++# --------------------------------------------------------------------------+# lead diagnosis+# --------------------------------------------------------------------------+++def test_the_lead_is_the_files_own_primary_problem() -> None:+ opportunity = compose_opportunities(+ [plan("extract_method")], primary_biomarker_by_file={"svc/orders.py": "complex_method"}+ )[0]+ assert opportunity.lead_biomarker == "complex_method"+ assert opportunity.addresses_primary_problem is True+++def test_a_problem_no_detector_answers_is_reported_as_unaddressed() -> None:+ opportunity = compose_opportunities(+ [plan("extract_method")], primary_biomarker_by_file={"svc/orders.py": "churn_risk"}+ )[0]+ assert opportunity.lead_biomarker == "churn_risk"+ assert opportunity.addresses_primary_problem is False+++def test_without_the_files_findings_the_question_is_unknown_not_no() -> None:+ opportunity = compose_opportunities([plan("extract_method")])[0]+ assert opportunity.addresses_primary_problem is None+ assert opportunity.rank_factors["primary_problem"] == 0.0+++def test_a_purely_structural_file_leads_with_its_structure() -> None:+ opportunity = compose_opportunities([split()])[0]+ assert opportunity.lead_biomarker is None+ assert opportunity.lead_refactoring_type == "split_file"+++# --------------------------------------------------------------------------+# rollups+# --------------------------------------------------------------------------+++def test_blast_radius_is_charged_once_over_the_union() -> None:+ shared = {"files": ["svc/billing.py"], "file_count": 1}+ one = compose_opportunities([clone(intra=False, co_change=4, blast_radius=shared)])[0]+ two = compose_opportunities(+ [+ clone(intra=False, co_change=4, blast_radius=shared),+ clone(intra=False, co_change=5, blast_radius=shared),+ ]+ )[0]+ assert one.affected_files == two.affected_files == ("svc/billing.py", "svc/orders.py")+ assert one.rank_factors["risk"] == two.rank_factors["risk"]+++def test_effort_is_the_largest_step_not_the_sum() -> None:+ rows = [plan("extract_method", effort_bucket="S"), plan("extract_method", "x", effort_bucket="L")]+ assert compose_opportunities(rows)[0].effort_bucket == "L"+++def test_confidence_is_the_weakest_step() -> None:+ rows = [plan("extract_method"), plan("extract_method", "x", confidence="medium")]+ assert compose_opportunities(rows)[0].confidence == "medium"+++def test_mechanical_and_judgment_steps_are_counted_separately() -> None:+ opportunity = compose_opportunities([plan("extract_method"), split()])[0]+ assert (opportunity.mechanical_steps, opportunity.judgment_steps) == (1, 1)+ assert opportunity.step_count == 2+++# --------------------------------------------------------------------------+# ranking+# --------------------------------------------------------------------------+++def test_a_step_set_with_no_benefit_cannot_outrank_one_that_recovers_health() -> None:+ barren = compose_opportunities([clone(intra=False, co_change=4)])[0]+ real = compose_opportunities([plan("extract_method", file_path="svc/billing.py")])[0]+ assert barren.rank_score == 0.0+ assert real.rank_score > barren.rank_score+++def test_addressing_the_primary_problem_ranks_above_not_addressing_it() -> None:+ rows = [plan("extract_method"), plan("extract_method", file_path="svc/billing.py")]+ ranked = compose_opportunities(+ rows,+ primary_biomarker_by_file={+ "svc/orders.py": "complex_method",+ "svc/billing.py": "churn_risk",+ },+ )+ assert [item.file_path for item in ranked] == ["svc/orders.py", "svc/billing.py"]+++def test_order_is_total_and_repeatable() -> None:+ rows = [plan("extract_method", file_path=f"svc/m{index}.py") for index in range(6)]+ first = [item.opportunity_id for item in compose_opportunities(rows)]+ assert first == [item.opportunity_id for item in compose_opportunities(list(reversed(rows)))]+++def test_why_ranked_names_the_factors_that_moved_it() -> None:+ opportunity = compose_opportunities([plan("extract_method")])[0]+ named = {entry["factor"] for entry in opportunity.why_ranked}+ assert named <= set(opportunity.rank_factors)+ assert "benefit" in named+++# --------------------------------------------------------------------------+# identity and lifecycle+# --------------------------------------------------------------------------+++def test_the_id_is_built_over_the_member_plan_ids() -> None:+ opportunity = compose_opportunities([plan("extract_method"), split()])[0]+ assert opportunity.opportunity_id == opportunity_public_id(+ [step.plan_id for step in opportunity.steps], "svc/orders.py"+ )+ assert opportunity.opportunity_id.startswith("refop2_")+++def test_the_id_survives_a_uniform_line_shift() -> None:+ before = compose_opportunities([plan("extract_method")])[0]+ after = compose_opportunities([plan("extract_method", line_start=210, line_end=240)])[0]+ assert before.opportunity_id == after.opportunity_id+++def test_the_id_changes_when_the_work_changes() -> None:+ one = compose_opportunities([plan("extract_method")])[0]+ two = compose_opportunities([plan("extract_method"), split()])[0]+ assert one.opportunity_id != two.opportunity_id+++def test_evidence_does_not_rename_the_work() -> None:+ bare = compose_opportunities([plan("extract_method")])[0]+ witnessed = compose_opportunities([plan("extract_method"), clone(intra=True, co_change=0)])[0]+ assert bare.opportunity_id == witnessed.opportunity_id+ assert len(witnessed.evidence) == 1+++def test_lifecycle_resolves_only_when_every_step_does() -> None:+ opportunity = compose_opportunities([plan("extract_method"), split()])[0]+ first, second = (step.plan_id for step in opportunity.steps)+ assert opportunity_status(opportunity, {}) == "open"+ assert opportunity_status(opportunity, {first: "resolved"}) == "open"+ assert opportunity_status(opportunity, {first: "resolved", second: "resolved"}) == "resolved"+ assert (+ opportunity_status(opportunity, {first: "false_positive", second: "resolved"}) == "resolved"+ )+ assert (+ opportunity_status(opportunity, {first: "acknowledged", second: "resolved"})+ == "acknowledged"+ )+++def test_an_untriaged_step_keeps_the_opportunity_open() -> None:+ opportunity = compose_opportunities([plan("extract_method"), split()])[0]+ known = opportunity.steps[0].plan_id+ assert opportunity_status(opportunity, {known: "resolved"}) == "open"+++# --------------------------------------------------------------------------+# input shapes+# --------------------------------------------------------------------------+++def test_dicts_and_dataclasses_compose_to_the_same_opportunity() -> None:+ from dataclasses import asdict++ rows = [plan("extract_method"), split()]+ from_objects = compose_opportunities(rows)[0]+ from_dicts = compose_opportunities([asdict(row) for row in rows])[0]+ assert from_objects.as_dict() == from_dicts.as_dict()diff --git a/tests/unit/health/test_refactoring_preconditions.py b/tests/unit/health/test_refactoring_preconditions.pynew file mode 100644index 000000000..2956aa753--- /dev/null+++ b/tests/unit/health/test_refactoring_preconditions.py@@ -0,0 +1,189 @@+"""What the layer claims to know about a step, and what that licenses."""++from __future__ import annotations++import pytest++from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion+from repowise.core.analysis.health.refactoring.preconditions import (+ JUDGMENT_REASONS,+ MECHANICAL_REASONS,+ classify_step,+ step_facts,+)+++def step(kind: str, **kwargs) -> RefactoringSuggestion:+ payload = {+ "refactoring_type": kind,+ "file_path": "svc/orders.py",+ "target_symbol": "handle",+ "line_start": 10,+ "line_end": 40,+ "plan": {},+ "evidence": {},+ "impact_delta": 1.0,+ "effort_bucket": "S",+ "blast_radius": {},+ "confidence": "high",+ "source_biomarker": "",+ }+ payload.update(kwargs)+ return RefactoringSuggestion(**payload)+++def go_split(**kwargs) -> RefactoringSuggestion:+ kwargs.setdefault(+ "plan",+ {+ "shim_required": False,+ "groups": [+ {"symbols": ["Stock"], "suggested_file": "inventory/stock.go"},+ {"symbols": ["Supplier"], "suggested_file": "inventory/supplier.go"},+ ],+ },+ )+ return step(+ "split_file",+ file_path="inventory/inventory.go",+ blast_radius={"dependent_count": 0, "import_rewrites": 0},+ **kwargs,+ )+++# --------------------------------------------------------------------------+# what is licensed+# --------------------------------------------------------------------------+++def test_a_proved_local_extraction_is_mechanical() -> None:+ applicability = classify_step(step("extract_method", blast_radius={"scope": "local"}))+ assert applicability.classification == "mechanical"+ assert applicability.reasons == ("dataflow_proved_local_extraction",)+++def test_an_unsure_detector_keeps_its_own_extraction_a_judgment_call() -> None:+ applicability = classify_step(+ step("extract_method", blast_radius={"scope": "local"}, confidence="medium")+ )+ assert applicability.classification == "judgment"+ assert applicability.reasons == ("detector_confidence_below_high",)+++def test_no_split_is_mechanical_even_when_no_import_moves() -> None:+ """Go keeps the qualified name, but the file still decides what compiles.++ A ``_linux.go`` basename or a ``//go:build`` line gates compilation on the+ file a symbol sits in, and neither reaches this layer, so the same-package+ case reports what it could not establish rather than claiming a proof.+ """+ applicability = classify_step(go_split())+ assert applicability.classification == "judgment"+ assert applicability.reasons == ("build_constraints_unknown",)+++def test_extraction_is_the_only_mechanical_class() -> None:+ kinds = (+ "extract_method",+ "split_file",+ "extract_helper",+ "move_method",+ "extract_class",+ "break_cycle",+ )+ mechanical = {+ kind+ for kind in kinds+ if classify_step(+ step(kind, blast_radius={"scope": "local"}, plan=go_split().plan)+ ).classification+ == "mechanical"+ }+ assert mechanical == {"extract_method"}+++def test_a_split_that_needs_a_shim_is_a_judgment_call() -> None:+ plan = dict(go_split().plan)+ plan["shim_required"] = True+ applicability = classify_step(go_split(plan=plan))+ assert applicability.classification == "judgment"+ assert "rewrites_dependent_imports" in applicability.reasons+++def test_a_split_nobody_can_name_a_target_for_is_not_mechanical() -> None:+ plan = dict(go_split().plan)+ plan["groups"] = [{"symbols": ["Stock"], "suggested_file": None}]+ applicability = classify_step(go_split(plan=plan))+ assert applicability.classification == "judgment"+ assert applicability.reasons == ("no_named_target",)+++ ("kind", "reason"),+ [+ ("extract_helper", "call_site_bindings_unproven"),+ ("move_method", "changes_symbol_home"),+ ("extract_class", "reshapes_class_surface"),+ ("break_cycle", "inverts_imports_across_files"),+ ],+)+def test_every_symbol_moving_type_stays_a_judgment_call(kind: str, reason: str) -> None:+ applicability = classify_step(step(kind))+ assert applicability.classification == "judgment"+ assert reason in applicability.reasons+++def test_an_unknown_type_defaults_to_judgment_rather_than_to_a_promise() -> None:+ applicability = classify_step(step("extract_interface"))+ assert applicability.classification == "judgment"+ assert applicability.reasons == ("unclassified_refactoring_type",)+++def test_every_reason_comes_from_the_declared_vocabulary() -> None:+ known = set(MECHANICAL_REASONS) | set(JUDGMENT_REASONS)+ kinds = (+ "extract_method",+ "split_file",+ "extract_helper",+ "move_method",+ "extract_class",+ "break_cycle",+ "made_up",+ )+ emitted = {reason for kind in kinds for reason in classify_step(step(kind)).reasons}+ assert emitted <= known+++# --------------------------------------------------------------------------+# what is known+# --------------------------------------------------------------------------+++def test_facts_are_scoped_to_what_the_type_can_carry() -> None:+ facts, _ = step_facts(step("extract_method", blast_radius={"scope": "local"}))+ assert "shim_required" not in facts, "a lifted span has no re-export shim to need"+ assert facts["local_scope"] is True+++def test_a_fact_the_type_carries_but_the_row_lacks_reads_as_unknown() -> None:+ facts, unknowns = step_facts(step("move_method"))+ assert facts["callers"] is None+ assert "callers" in unknowns+++def test_a_measured_zero_is_not_an_unknown() -> None:+ facts, unknowns = step_facts(step("move_method", blast_radius={"callers": 0}))+ assert facts["callers"] == 0+ assert "callers" not in unknowns+++def test_framework_registration_is_never_claimed_to_be_known() -> None:+ for kind in ("split_file", "move_method", "extract_class", "break_cycle"):+ facts, unknowns = step_facts(step(kind))+ assert facts["framework_registration"] is None+ assert "framework_registration" in unknowns+++def test_classification_is_a_pure_function_of_the_row() -> None:+ row = go_split()+ assert classify_step(row).as_dict() == classify_step(row).as_dict()diff --git a/tests/unit/health/test_refactoring_tree_corpus.py b/tests/unit/health/test_refactoring_tree_corpus.pynew file mode 100644index 000000000..c4b4c974d--- /dev/null+++ b/tests/unit/health/test_refactoring_tree_corpus.py@@ -0,0 +1,138 @@+"""Composition over the archetype corpus: per-language sanity, off this repo.++The golden pins the composed output for each archetype tree so a composition+change has to explain every delta. The named tests state the contract the golden+is only evidence for.+"""++from __future__ import annotations++import pytest++from .refactoring_tree_fixture import (+ MANIFEST,+ TREES_DIR,+ UNCOVERED,+ archetype_roots,+ compose_tree,+ load_golden,+ plans_for_tree,+ rewrite_requested,+ write_golden,+)++GOLDEN = "golden_opportunities.json"+++def test_corpus_composition_matches_the_golden() -> None:+ payload = {name: compose_tree(root) for name, root in archetype_roots()}+ if rewrite_requested():+ write_golden(GOLDEN, payload)+ pytest.skip("golden rewritten")+ assert payload == load_golden(GOLDEN)+++def test_every_manifest_archetype_has_a_tree() -> None:+ missing = [name for name in MANIFEST if not (TREES_DIR / name).is_dir()]+ assert not missing, f"manifest names archetypes with no tree: {missing}"+++def test_the_uncovered_archetypes_stay_declared() -> None:+ assert UNCOVERED, "an empty gap list reads as full coverage; it is not"+++# --------------------------------------------------------------------------+# per-archetype contracts+# --------------------------------------------------------------------------+++def test_declarative_orm_columns_never_instruct_a_shared_helper() -> None:+ for opportunity in compose_tree(TREES_DIR / "orm"):+ kinds = [step["refactoring_type"] for step in opportunity["steps"]]+ assert "extract_helper" not in kinds, (+ "a declarative attribute is bound in the class body; no function can hold it"+ )+++def test_a_reexport_barrel_never_instructs_a_shared_helper() -> None:+ for opportunity in compose_tree(TREES_DIR / "tsapp"):+ kinds = [step["refactoring_type"] for step in opportunity["steps"]]+ assert "extract_helper" not in kinds+++def test_the_cross_file_clone_with_no_history_is_demoted() -> None:+ """account.ts and workspace.ts are near-duplicates with no shared commits.++ Cross-file alone is not enough: without co-change the composer must keep the+ clone as evidence rather than instruct a rewrite of both call sites.+ """+ clones = [+ row for row in plans_for_tree(TREES_DIR / "tsapp") if row["refactoring_type"] == "extract_helper"+ ]+ if not clones:+ pytest.skip("no clone pair survived the detector's gates on this build")+ assert all((row["evidence"].get("co_change_count") or 0) == 0 for row in clones)+ for opportunity in compose_tree(TREES_DIR / "tsapp"):+ assert "extract_helper" not in [step["refactoring_type"] for step in opportunity["steps"]]+++def test_nothing_that_moves_a_registered_handler_is_ever_mechanical() -> None:+ """A lifted span is the one exception: it moves no symbol the router holds."""+ moved = 0+ for opportunity in compose_tree(TREES_DIR / "web"):+ for step in opportunity["steps"]:+ if step["refactoring_type"] == "extract_method":+ continue+ moved += 1+ assert step["applicability"]["classification"] == "judgment", (+ f"{step['refactoring_type']} moved a registered symbol and claimed to be safe"+ )+ assert moved == 0, "the archetype grew a symbol-moving plan; assert its reasons too"+++def test_a_lifted_span_inside_a_registered_handler_is_still_mechanical() -> None:+ kinds = {+ (step["refactoring_type"], step["applicability"]["classification"])+ for opportunity in compose_tree(TREES_DIR / "web")+ for step in opportunity["steps"]+ }+ assert ("extract_method", "mechanical") in kinds+++def test_repeated_handler_bodies_stay_evidence_without_co_change() -> None:+ """Three identical read handlers are real duplication with no history.++ The demotion rule is deliberately strict here: without co-change nothing+ proves the sites move together, so the clone evidences the diagnosis instead+ of instructing a rewrite of all three call sites.+ """+ trees = compose_tree(TREES_DIR / "web")+ assert any(opportunity["evidence"] for opportunity in trees)+ for opportunity in trees:+ assert "extract_helper" not in [step["refactoring_type"] for step in opportunity["steps"]]+++def test_a_split_offered_on_go_is_classified_not_dropped() -> None:+ """A same-package Go split is offered, and is still a judgment call.++ Two facts refuse the promotion independently: this fixture's groups cannot+ be named, and no split can prove the absence of a file-scoped build+ constraint. See ``UNCOVERED``.+ """+ splits = [+ step+ for opportunity in compose_tree(TREES_DIR / "gopkg")+ for step in opportunity["steps"]+ if step["refactoring_type"] == "split_file"+ ]+ if not splits:+ pytest.skip("no Go grammar on this build")+ for step in splits:+ assert step["applicability"]["facts"]["shim_required"] is False+ assert step["applicability"]["classification"] == "judgment"+ assert step["applicability"]["reasons"] == ["no_named_target"]+++def test_composition_is_deterministic_across_runs() -> None:+ for _, root in archetype_roots():+ assert compose_tree(root) == compose_tree(root)