Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(health): mark Extract Method spans that await as async helpers (#3254)
Raghav Chamadiya800bd0c44645
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.mdindex 70d87e159..f4968e499 100644--- a/docs/layers/REFACTORING.md+++ b/docs/layers/REFACTORING.md@@ -166,6 +166,12 @@ Most plans answer a health finding, so per-path marker rules indocstring. When the best span misses one of these, only a span that does notoverlap it is offered, never a slightly smaller copy of it. Estimated gainnever exceeds the share of decision points removed.+- An Extract Method span that awaits (Python `await`, `async with`, `async for`;+ TypeScript and JavaScript `await`, `for await`; Rust `.await`; C++ `co_await`)+ carries `needs_async: true`: the helper is async and its call is awaited. An+ await inside a nested function, closure or Rust `async` block does not count.+ When the function holding the span is not declared async (a C++ coroutine), the+ step is a judgment call with reason `async_helper_unexpressible`.- Move Method never targets a class the method only instantiates, or an ancestor ofits own class.- Split File works on any language with call resolution and suggests a split onlydiff --git a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.pyindex baeeb6d8f..79870bc46 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py@@ -568,6 +568,10 @@ def _render_unattached_md(plans: list[dict]) -> None:click.echo(line)+# An Extract Method span that awaits lifts into an async helper.+_ASYNC_NOTE = "async helper, call awaited"++def _plan_detail_console(p: dict) -> list[str]:"""The type-specific detail for one step, as console lines.@@ -615,7 +619,10 @@ def _plan_detail_console(p: dict) -> list[str]:f" [dim]extract lines {span.get('start')}-{span.get('end')} "f"({ev.get('slice_nloc')} lines, -{ev.get('ccn_removed')} CCN)[/dim]")- out.append(f" [dim]in:[/dim] {params} [dim]out:[/dim] {returns}")+ out.append(+ f" [dim]in:[/dim] {params} [dim]out:[/dim] {returns}"+ + (f" [dim]{_ASYNC_NOTE}[/dim]" if pl.get("needs_async") else "")+ )elif kind == "move_method":to_file = pl.get("to_file")dest = f"{pl.get('to_class')}" + (f" [dim]({to_file})[/dim]" if to_file else "")@@ -687,6 +694,7 @@ def _plan_detail_md(p: dict) -> list[str]:f" - extract lines {span.get('start')}-{span.get('end')} "f"({ev.get('slice_nloc')} lines, -{ev.get('ccn_removed')} CCN) · "f"in: {params} · out: {returns}"+ + (f" · {_ASYNC_NOTE}" if pl.get("needs_async") else ""))elif kind == "move_method":dest = pl.get("to_class")diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.pyindex e8a3ac860..c6c0184fe 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py@@ -247,6 +247,17 @@ class LanguageNodeMap:# segment. The slicer treats them as jumps for the same reason. A user# macro of the same name that does not exit only hides a span.yield_kinds: frozenset[str] = frozenset()+ # * ``await_kinds`` -- tokens that suspend the function (Python ``await`` /+ # ``async with`` / ``async for``, TS/JS ``await`` / ``for await``, Rust+ # ``.await``, C++ ``co_await``). Matched on the anonymous keyword token,+ # which every form carries. A span holding one lifts into a helper that+ # must itself be async, with its call site awaited.+ # * ``await_scope_kinds`` -- nodes that own the awaits inside them (Rust+ # ``async { }``): awaiting there suspends the block's future, not the+ # function, so the await scan stops at them. Nested functions and+ # lambdas (async closures among them) are skipped already.+ await_kinds: frozenset[str] = frozenset()+ await_scope_kinds: frozenset[str] = frozenset()exit_macro_kinds: frozenset[str] = frozenset()exit_macro_names: frozenset[str] = frozenset()# * ``statement_wrapper_kinds`` -- statement node(s) that merely wrap the@@ -363,6 +374,9 @@ _PY = LanguageNodeMap(continue_kinds=frozenset({"continue_statement"}),with_kinds=frozenset({"with_statement"}),yield_kinds=frozenset({"yield"}),+ # ``async`` marks ``async with`` / ``async for`` (and the comprehension+ # form); a nested ``async def`` is a scope the slicer never enters.+ await_kinds=frozenset({"await", "async"}),decorator_kinds=frozenset({"decorator"}),decorated_definition_kinds=frozenset({"decorated_definition"}),)@@ -421,6 +435,7 @@ _TS = LanguageNodeMap(break_kinds=frozenset({"break_statement"}),continue_kinds=frozenset({"continue_statement"}),yield_kinds=frozenset({"yield_expression"}),+ await_kinds=frozenset({"await"}),)_JS = _TS # identical control-flow nodes; tree-sitter-javascript shares shape.@@ -595,6 +610,8 @@ _RUST = LanguageNodeMap(exit_macro_names=frozenset({"bail", "ensure", "try"}),break_kinds=frozenset({"break_expression"}),continue_kinds=frozenset({"continue_expression"}),+ await_kinds=frozenset({"await"}),+ await_scope_kinds=frozenset({"async_block"}),# Rust parses every statement-position control-flow expression inside an# ``expression_statement``; the CFG builder unwraps it to classify the real# node, and the slicer uses this as the expression-oriented marker for@@ -755,10 +772,15 @@ _CPP = LanguageNodeMap(local_decl_kinds=frozenset({"declaration"}),if_kinds=frozenset({"if_statement"}),block_kinds=frozenset({"compound_statement"}),- return_kinds=frozenset({"return_statement"}),+ # ``co_return`` / ``co_yield`` leave a coroutine like ``return`` / ``yield``.+ return_kinds=frozenset({"return_statement", "co_return_statement"}),raise_kinds=frozenset({"throw_statement"}),break_kinds=frozenset({"break_statement"}),continue_kinds=frozenset({"continue_statement"}),+ yield_kinds=frozenset({"co_yield_statement"}),+ # A coroutine carries no ``async`` token, so a span holding one is never+ # offered as a mechanical extraction.+ await_kinds=frozenset({"co_await"}),)_C = LanguageNodeMap(diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py b/packages/core/src/repowise/core/analysis/health/dataflow/slice.pyindex 51a344ed8..e9e4c2b58 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py@@ -69,7 +69,9 @@ class Extraction:variable(s). ``slice_nloc`` is the span's code lines, counted with thewalker's NLOC rule (blank, comment-only and docstring lines excluded, as inthe function's own ``nloc``), and ``ccn_removed`` the decision points it- carries (the complexity the residual method sheds).+ carries (the complexity the residual method sheds). ``needs_async`` is+ True when the span suspends (an ``await_kinds`` token outside any nested+ scope): the helper must be async and its call site awaited."""start_line: int@@ -78,6 +80,7 @@ class Extraction:returns: tuple[str, ...]slice_nloc: intccn_removed: int+ needs_async: bool = Falsedef find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[Extraction]:@@ -159,12 +162,14 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[# candidate span would put the O(n^2 * subtree) cost straight back.nested_prefix = [0]code_prefix = [0]+ await_prefix = [0]for st in stmts:- d, jmp = _span_metrics(- [st], decision_kinds, jump_kinds, scope_kinds, _exit_macros(lmap)+ d, jmp, awaits = _span_metrics(+ [st], decision_kinds, jump_kinds, scope_kinds, _exit_macros(lmap), _awaits(lmap))dec_prefix.append(dec_prefix[-1] + d)jump_prefix.append(jump_prefix[-1] + (1 if jmp else 0))+ await_prefix.append(await_prefix[-1] + (1 if awaits else 0))nested_prefix.append(nested_prefix[-1] + (1 if _holds_a_named_nested_function([st], lmap) else 0))@@ -217,6 +222,7 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[returns=returns,slice_nloc=slice_nloc,ccn_removed=decisions,+ needs_async=await_prefix[j + 1] > await_prefix[i],))return _sorted(out)@@ -837,6 +843,11 @@ def _exit_macros(lmap: LanguageNodeMap) -> tuple[frozenset[str], frozenset[str]]return lmap.exit_macro_kinds, lmap.exit_macro_names+def _awaits(lmap: LanguageNodeMap) -> tuple[frozenset[str], frozenset[str]]:+ """The await tokens, and the nodes that own the awaits inside them."""+ return lmap.await_kinds, lmap.await_scope_kinds++def _is_jump(node: Node,jump_kinds: frozenset[str],@@ -859,22 +870,29 @@ def _span_metrics(decision_kinds: frozenset[str],jump_kinds: frozenset[str],scope_kinds: frozenset[str],- exit_macros: tuple[frozenset[str], frozenset[str]] = (frozenset(), frozenset()),-) -> tuple[int, bool]:- """Decision-point count and jump presence within *span* (nested scopes are- not descended into). A macro named in *exit_macros* counts as a jump."""+ exit_macros: tuple[frozenset[str], frozenset[str]],+ awaits: tuple[frozenset[str], frozenset[str]],+) -> tuple[int, bool, bool]:+ """Decision-point count, jump presence and await presence within *span*+ (nested scopes are not descended into). A macro named in *exit_macros*+ counts as a jump; an await under one of *awaits*' scope kinds (``async``+ blocks) does not suspend the function, so it does not count."""+ await_kinds, await_scope_kinds = awaitsdecisions = 0has_jump = False+ has_await = Falsefor root in span:- stack: list[Node] = [root]+ stack: list[tuple[Node, bool]] = [(root, True)]while stack:- node = stack.pop()+ node, counts_await = stack.pop()t = node.typehas_jump = has_jump or _is_jump(node, jump_kinds, exit_macros)+ has_await = has_await or (counts_await and t in await_kinds)if t in decision_kinds:decisions += 1+ counts_await = counts_await and t not in await_scope_kindsfor child in node.children:if child.type in scope_kinds:continue- stack.append(child)- return decisions, has_jump+ stack.append((child, counts_await))+ return decisions, has_jump, has_awaitdiff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.pyindex cbdcac93e..ea120f74e 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py@@ -49,6 +49,10 @@ Plan shape (open dict, no migration):``_suggested_name``). ``None`` when the span has no single informative OUTvalue: a name derived from the enclosing function described the contextrather than the span, and collided with every sibling plan in the file.+- ``plan.needs_async`` -- the span awaits, so the helper is async and its call+ is awaited. An awaiting plan also carries ``async_host``: False when the+ enclosing function is not declared async, which makes the step a judgment+ call (``preconditions``) rather than a mechanical one.- ``evidence`` = ``{"slice_nloc": int, "ccn_removed": int}`` -- the size andcomplexity (code lines, decision points) the residual method sheds.- ``blast_radius`` = ``{"scope": "local"}`` -- extraction is local (a new@@ -72,6 +76,7 @@ from ..complexity.cyclomatic import _is_boolean_operatorfrom ..complexity.languages import get_language_mapfrom ..complexity.nloc import is_string_stmtfrom ..dataflow import find_extractions+from ..perf.dialects import PERF_DIALECTSfrom ..scoring import severity_deductionfrom .models import RefactoringContext, RefactoringSuggestionfrom .naming import join_identifier, split_words@@ -174,6 +179,7 @@ class ExtractMethodDetector(RefactoringDetector):"params": list(best.params),"returns": list(best.returns),"suggested_name": self._suggested_name(analysis, best, ctx.language),+ **_async_fields(analysis, best, lmap, ctx.language),},evidence={"slice_nloc": best.slice_nloc,@@ -301,6 +307,29 @@ def recovered_share(return min(1.0, ccn_share)+def _async_fields(+ analysis: FunctionAnalysis,+ extraction: Extraction,+ lmap: LanguageNodeMap,+ language: str | None,+) -> dict[str, bool]:+ """``needs_async`` always; ``async_host`` only for an awaiting span, False+ when the function holding it is not declared async (a C++ coroutine),+ where no async helper can be written in its place."""+ if not extraction.needs_async:+ return {"needs_async": False}+ return {"needs_async": True, "async_host": host_is_async(analysis.fn_node, lmap, language)}+++def host_is_async(fn_node: Any, lmap: LanguageNodeMap, language: str | None) -> bool:+ """Whether *fn_node* is declared async, by the perf pass's own test: a+ dedicated async node kind, else the language's perf dialect."""+ if fn_node.type in lmap.async_function_kinds:+ return True+ dialect = PERF_DIALECTS.get(language or "")+ return dialect is not None and dialect.is_async_fn(fn_node)++def _worth_extracting(analysis: FunctionAnalysis, extraction: Extraction, markers: set[str]) -> bool:diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.pyindex ba7dcd550..882cded95 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py@@ -351,7 +351,9 @@ _TYPE_INSTRUCTIONS: dict[str, str] = {"which it can. When 'suggested_name' is null no name was anchored in the plan, ""so choose one that describes what the lifted code computes. Pass the plan's 'params' as its arguments ""and return the plan's 'returns' value(s), and replace the original lines "- "with a call to it. Preserve behaviour exactly; change nothing outside the "+ "with a call to it. When the plan's 'needs_async' is true the span awaits: "+ "declare the helper async and await the call that replaces the lines. "+ "Preserve behaviour exactly; change nothing outside the ""span and the single call site."),"split_file": (diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/models.py b/packages/core/src/repowise/core/analysis/health/refactoring/models.pyindex 155a8ab0c..575d0f9c0 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/models.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/models.py@@ -46,10 +46,12 @@ For Extract Helper:For Extract Method:- ``plan`` = ``{"span": {"start": int, "end": int}, "params": [str, ...],- "returns": [str, ...], "suggested_name": str | None}`` — the lines to lift,- the inferred signature, and a deterministic starting name (from the slice's- single informative OUT value, else absent). It is an editable starting point- and is not unique within a file.+ "returns": [str, ...], "suggested_name": str | None, "needs_async": bool}``+ — the lines to lift, the inferred signature, a deterministic starting name+ (from the slice's single informative OUT value, else absent; an editable+ starting point, not unique within a file), and whether the span awaits, so+ the helper is async and its call awaited. An awaiting plan adds+ ``"async_host": bool``, False when the enclosing function is not async.- ``evidence`` = ``{"slice_nloc": int, "ccn_removed": int}`` — the size andcomplexity (code lines, decision points) the residual method sheds.- ``blast_radius`` = ``{"scope": "local"}`` — the one type whose blast radius isdiff --git a/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.py b/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.pyindex 125850cd7..cb71211a6 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.py@@ -32,6 +32,7 @@ Applicability = Literal["mechanical", "judgment"]# for the two mechanical codes, "what was proved?".MECHANICAL_REASONS = ("dataflow_proved_local_extraction",)JUDGMENT_REASONS = (+ "async_helper_unexpressible","build_constraints_unknown","call_site_bindings_unproven","changes_symbol_home",@@ -142,8 +143,12 @@ def _extract_method_reasons(suggestion: RefactoringSuggestion, facts: dict[str,R1's dataflow gate proves the span behaviour-preserving before it is everoffered, and the blast radius is categorically local, so the only thing left- to check is that the detector itself was sure.+ to check is that the detector itself was sure, and that an awaiting span+ has an async function to land in."""+ plan = suggestion.plan or {}+ if plan.get("needs_async") and plan.get("async_host") is False:+ return ["async_helper_unexpressible"]if not facts["local_scope"]:return ["changes_symbol_home"]if suggestion.confidence != "high":diff --git a/packages/ui/__tests__/refactoring/extract-method-types.test.ts b/packages/ui/__tests__/refactoring/extract-method-types.test.tsindex 22a31d599..2f70da2f7 100644--- a/packages/ui/__tests__/refactoring/extract-method-types.test.ts+++ b/packages/ui/__tests__/refactoring/extract-method-types.test.ts@@ -55,6 +55,20 @@ describe("extract_method plan accessors", () => {expect(em.suggested_name).toBeNull();});+ it("reads needs_async, false for a plan stored before it existed", () => {+ expect(extractMethodPlan(extractMethodPlanFixture()).needs_async).toBe(false);+ const awaiting = extractMethodPlanFixture({+ plan: { span: { start: 30, end: 48 }, params: [], returns: [], needs_async: true },+ });+ expect(extractMethodPlan(awaiting).needs_async).toBe(true);+ expect(extractMethodPlan(awaiting).async_host).toBeNull();+ const blocked = extractMethodPlanFixture({+ plan: { span: { start: 30, end: 48 }, params: [], returns: [], needs_async: true, async_host: false },+ });+ expect(extractMethodPlan(blocked).async_host).toBe(false);+ expect(planSynopsis(awaiting)).toBe("Extract 19 lines into an async helper");+ });+it("returns a null span when the plan omits it", () => {const em = extractMethodPlan(extractMethodPlanFixture({ plan: { params: [], returns: [] } }));expect(em.span).toBeNull();diff --git a/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts b/packages/ui/src/health/ai-prompts/refactoring-plan-steps.tsindex 3a6299419..7bd4d8f3b 100644--- a/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts+++ b/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts@@ -72,6 +72,7 @@ function extractMethodSteps(plan: RefactoringPlan): string {"",`- **Parameters (in):** ${params}`,`- **Returns (out):** ${returns}`,+ ...(em.needs_async ? ["- **Async:** the span awaits, so declare the helper async and await its call"] : []),"","Move exactly those lines into the new helper in the same scope, pass the parameters above, return the value(s) above, and replace the original lines with a single call to it. Preserve behavior exactly: change nothing outside the span and that one call site.",].join("\n");diff --git a/packages/ui/src/refactoring/plan-detail.tsx b/packages/ui/src/refactoring/plan-detail.tsxindex b331ccfba..29acc87ac 100644--- a/packages/ui/src/refactoring/plan-detail.tsx+++ b/packages/ui/src/refactoring/plan-detail.tsx@@ -429,7 +429,7 @@ export function PlanDetail({ plan, fileHref, hideIntro = false }: PlanDetailPropconst lines = em.span ? em.span.end - em.span.start + 1 : 0;const ccn = Number(plan.evidence?.ccn_removed ?? 0);const helperName = em.suggested_name ?? "helper";- const sig = `${helperName}(${em.params.join(", ")})${+ const sig = `${em.needs_async ? "async " : ""}${helperName}(${em.params.join(", ")})${em.returns.length ? ` -> ${em.returns.join(", ")}` : ""}`;return (@@ -437,7 +437,8 @@ export function PlanDetail({ plan, fileHref, hideIntro = false }: PlanDetailProp{hideIntro ? null : (<p className="text-xs text-[var(--color-text-tertiary)]">Lift {lines} line{lines === 1 ? "" : "s"} out of{" "}- <span className="font-mono">{plan.target_symbol}</span> into a focused helper+ <span className="font-mono">{plan.target_symbol}</span> into a focused{" "}+ {em.needs_async ? "async helper whose call is awaited" : "helper"}{ccn ? `, shedding ${ccn} decision point${ccn === 1 ? "" : "s"}` : ""}.</p>)}@@ -483,6 +484,12 @@ export function PlanDetail({ plan, fileHref, hideIntro = false }: PlanDetailProp</span></span></div>+ {em.async_host === false ? (+ <p className="mt-2 text-2xs text-[var(--color-text-tertiary)]">+ Judgment call: the span awaits, but the function holding it is not declared+ async, so an async helper cannot be written in its place.+ </p>+ ) : null}</div></div>);diff --git a/packages/ui/src/refactoring/types.ts b/packages/ui/src/refactoring/types.tsindex f1bab601a..769f415c5 100644--- a/packages/ui/src/refactoring/types.ts+++ b/packages/ui/src/refactoring/types.ts@@ -156,6 +156,11 @@ export interface ExtractMethodPlan {params: string[];returns: string[];suggested_name: string | null;+ /** The span awaits: the helper is async and its call site awaited. */+ needs_async: boolean;+ /** For an awaiting span: false when the enclosing function is not async, so+ * the step is a judgment call. Null when the plan does not say. */+ async_host: boolean | null;}export function extractMethodPlan(plan: RefactoringPlan): ExtractMethodPlan {@@ -170,6 +175,8 @@ export function extractMethodPlan(plan: RefactoringPlan): ExtractMethodPlan {params: Array.isArray(p.params) ? (p.params as string[]) : [],returns: Array.isArray(p.returns) ? (p.returns as string[]) : [],suggested_name: typeof p.suggested_name === "string" ? p.suggested_name : null,+ needs_async: p.needs_async === true,+ async_host: typeof p.async_host === "boolean" ? p.async_host : null,};}@@ -286,7 +293,8 @@ export function planSynopsis(plan: RefactoringPlan): string {case "extract_method": {const em = extractMethodPlan(plan);const lines = em.span ? em.span.end - em.span.start + 1 : 0;- return lines ? `Extract ${lines} line${lines === 1 ? "" : "s"} into a helper` : "Extract a helper method";+ const helper = em.needs_async ? "an async helper" : "a helper";+ return lines ? `Extract ${lines} line${lines === 1 ? "" : "s"} into ${helper}` : "Extract a helper method";}case "move_method": {const mv = moveTarget(plan);diff --git a/tests/unit/health/test_extract_method_async.py b/tests/unit/health/test_extract_method_async.pynew file mode 100644index 000000000..2e8277ab2--- /dev/null+++ b/tests/unit/health/test_extract_method_async.py@@ -0,0 +1,339 @@+"""Extract Method models ``await``: an awaiting span becomes an async helper.++A span lifted out of an async function that awaits inside it only works as a+helper declared async whose call site is awaited. The slicer marks such spans+``needs_async`` from the language's ``await_kinds`` during its one metrics+pass; the plan carries the flag, and a span whose enclosing function is not+async (a C++ coroutine) is a judgment call rather than a mechanical step.+"""++from __future__ import annotations++import textwrap+from dataclasses import dataclass++import pytest++from repowise.core.analysis.health.complexity.languages import get_language_map+from repowise.core.analysis.health.dataflow import (+ analyze_file,+ find_extractions,+)+from repowise.core.analysis.health.refactoring.extract_method import (+ ExtractMethodDetector,+ host_is_async,+)+from repowise.core.analysis.health.refactoring.models import (+ RefactoringContext,+ RefactoringSuggestion,+)+from repowise.core.analysis.health.refactoring.preconditions import classify_step+++@dataclass+class _Finding:+ biomarker_type: str+ function_name: str+ line_start: int+ health_impact: float+++def _functions(language: str, ext: str, src: str):+ from repowise.core.ingestion.parser import _get_language++ if _get_language(language) is None:+ pytest.skip(f"tree-sitter language pack missing for {language}")+ res = analyze_file(f"m.{ext}", language, textwrap.dedent(src).encode(), flagged_only=False)+ if res.stats.functions_seen == 0:+ pytest.skip(f"tree-sitter language pack missing for {language}")+ return res.functions+++def _flags(language: str, ext: str, src: str) -> dict[tuple[int, int], bool]:+ """``needs_async`` per candidate span of the file's first function."""+ fn = _functions(language, ext, src)[0]+ return {+ (x.start_line, x.end_line): x.needs_async+ for x in find_extractions(fn, get_language_map(language))+ }+++def _plans(language: str, ext: str, src: str):+ fns = _functions(language, ext, src)+ ctx = RefactoringContext(+ file_path=f"m.{ext}",+ language=language,+ nloc=100,+ findings=[_Finding("complex_method", f.name, f.start_line, 1.5) for f in fns],+ function_analyses=fns,+ )+ return ExtractMethodDetector().detect(ctx)+++# The two halves of one async function: lines 3-10 await, lines 11-18 do not.+_PY = """+async def load(session, rows, limit):+ total = 0+ for r in rows:+ if r.kind == "a":+ total += await session.count(r)+ elif r.kind == "b":+ total -= 1+ else:+ total += 2+ seen = 0+ for r in rows:+ if r.size > limit:+ seen += 1+ elif r.size < 0:+ seen -= 1+ else:+ seen += 2+ return total + seen+"""+++def _spans_within(flags: dict[tuple[int, int], bool], lo: int, hi: int) -> set[bool]:+ return {flag for (s, e), flag in flags.items() if lo <= s and e <= hi}+++def test_python_awaiting_span_needs_async_and_a_plain_one_does_not():+ flags = _flags("python", "py", _PY)+ assert _spans_within(flags, 3, 10) == {True}+ assert _spans_within(flags, 11, 18) == {False}+++ "replacement",+ [+ "async with session.begin():\n total += 1",+ "async for x in session.stream(r):\n total += x",+ ],+)+def test_python_async_with_and_async_for_need_async(replacement: str):+ src = _PY.replace("total += await session.count(r)", replacement)+ flags = _flags("python", "py", src)+ assert _spans_within(flags, 3, 11) == {True}+ assert _spans_within(flags, 12, 19) == {False}+++_TS = """+async function load(session: S, rows: R[], limit: number): Promise<number> {+ let total = 0;+ for (const r of rows) {+ if (r.kind === "a") {+ total += await session.count(r);+ } else {+ total -= 1;+ }+ }+ let seen = 0;+ for (const r of rows) {+ if (r.size > limit) {+ seen += 1;+ } else {+ seen -= 1;+ }+ }+ return total + seen;+}+"""+++def test_typescript_await_marks_only_the_awaiting_span():+ flags = _flags("typescript", "ts", _TS)+ assert _spans_within(flags, 3, 10) == {True}+ assert _spans_within(flags, 11, 18) == {False}+++def test_typescript_for_await_needs_async():+ src = _TS.replace(+ " for (const r of rows) {\n if (r.kind",+ " for await (const r of session.stream()) {\n if (r.kind",+ ).replace("total += await session.count(r);", "total += r.n;")+ assert "for await" in src+ flags = _flags("typescript", "ts", src)+ assert _spans_within(flags, 3, 10) == {True}+++def test_typescript_await_inside_an_async_arrow_does_not_count():+ src = _TS.replace(+ "total += await session.count(r);",+ "total += 1;\n const later = async () => { await session.flush(); };",+ )+ assert set(_flags("typescript", "ts", src).values()) == {False}+++_RUST = """+async fn load(session: &S, rows: &[R], limit: i64) -> i64 {+ let mut total = 0;+ for r in rows {+ if r.kind == 1 {+ total += session.count(r).await;+ } else {+ total -= 1;+ }+ }+ let mut seen = 0;+ for r in rows {+ if r.size > limit {+ seen += 1;+ } else {+ seen -= 1;+ }+ }+ total + seen+}+"""+++def test_rust_dot_await_marks_only_the_awaiting_span():+ flags = _flags("rust", "rs", _RUST)+ assert _spans_within(flags, 3, 10) == {True}+ assert _spans_within(flags, 11, 18) == {False}+++# The shape of ``attention.py::_health_items``: an async function whose second+# half aggregates rows read by awaiting ``session.execute`` inside a loop header.+_HEALTH_ITEMS = """+async def _health_items(session, repo_id, scoped, paths):+ rows = (await session.execute(select_rows(scoped))).all()+ total = await session.scalar(count_rows(scoped)) or 0+ if not rows:+ return [], int(total), ""++ lead_biomarker = {}+ history_lead = {}+ for path, biomarker in (+ await session.execute(select_leads(scoped, paths))+ ).all():+ if category(biomarker) == HISTORY:+ history_lead.setdefault(path, biomarker)+ else:+ lead_biomarker.setdefault(path, biomarker)+ for path, biomarker in history_lead.items():+ lead_biomarker.setdefault(path, biomarker)++ items = [+ {+ "id": f"health-{row.file_path}",+ "severity": severity(max(1.0, 10.0 - float(row.impact or 0.0))),+ "subtype": lead_biomarker.get(row.file_path),+ "weight": float(row.impact or 0.0),+ }+ for row in rows+ ]+ return items, int(total), ""+"""+++def test_health_items_plan_is_an_async_helper_and_stays_mechanical():+ plans = _plans("python", "py", _HEALTH_ITEMS)+ assert plans, "the _health_items shape should still be offered a plan"+ plan = plans[0]+ assert plan.plan["needs_async"] is True+ assert plan.plan["async_host"] is True+ assert "async_helper_unexpressible" not in classify_step(plan).reasons+++_CPP = """+task<int> load(S& session, std::vector<R>& rows, int limit) {+ int total = 0;+ for (auto& r : rows) {+ if (r.kind == 1) {+ total += co_await session.count(r);+ } else {+ total -= 1;+ }+ }+ int seen = 0;+ for (auto& r : rows) {+ if (r.size > limit) {+ seen += 1;+ } else {+ seen -= 1;+ }+ }+ co_return total + seen;+}+"""+++def test_cpp_co_await_needs_async_in_a_host_that_cannot_say_so():+ fn = _functions("cpp", "cpp", _CPP)[0]+ lmap = get_language_map("cpp")+ flags = {(x.start_line, x.end_line): x.needs_async for x in find_extractions(fn, lmap)}+ assert _spans_within(flags, 3, 10) == {True}+ assert _spans_within(flags, 11, 18) == {False}+ assert host_is_async(fn.fn_node, lmap, "cpp") is False+++ ("language", "ext", "src", "expected"),+ [+ ("python", "py", "async def f():\n pass\n", True),+ ("python", "py", "def f():\n pass\n", False),+ ("python", "py", "@retry(3)\nasync def f():\n pass\n", True),+ ("python", "py", "class C:\n async def f(self):\n pass\n", True),+ ("python", "py", "class C:\n def f(self):\n pass\n", False),+ ("typescript", "ts", "async function f() { return 1; }", True),+ ("typescript", "ts", "function f() { return 1; }", False),+ ("typescript", "ts", "class C { async f() { return 1; } }", True),+ ("typescript", "ts", "class C { f() { return 1; } }", False),+ ("rust", "rs", "async fn f() -> i32 { 1 }", True),+ ("rust", "rs", "fn f() -> i32 { let b = async { 1 }; 1 }", False),+ ("rust", "rs", "impl S { pub async unsafe fn f(&self) -> i32 { 1 } }", True),+ ("rust", "rs", "impl S { pub unsafe fn f(&self) -> i32 { 1 } }", False),+ ],+)+def test_host_is_async_reads_the_declaration_not_the_body(language, ext, src, expected):+ fn = _functions(language, ext, src)[0]+ assert host_is_async(fn.fn_node, get_language_map(language), language) is expected++[email protected]("host", ["async fn load", "fn load"])+def test_rust_await_inside_an_async_block_does_not_suspend_the_host(host: str):+ src = _RUST.replace(+ "total += session.count(r).await;",+ "total += 1;\n let f = async { session.flush().await };",+ ).replace("async fn load", host)+ assert set(_flags("rust", "rs", src).values()) == {False}+++def test_cpp_spans_holding_co_yield_or_co_return_are_refused():+ src = _CPP.replace("total -= 1;", "co_yield total;")+ fn = _functions("cpp", "cpp", src)[0]+ spans = [(x.start_line, x.end_line) for x in find_extractions(fn, get_language_map("cpp"))]+ assert spans, "the plain half should still be offered"+ assert not any(s <= 8 <= e for s, e in spans) # co_yield+ assert not any(s <= 19 <= e for s, e in spans) # co_return+++def _step(plan: dict) -> RefactoringSuggestion:+ return RefactoringSuggestion(+ refactoring_type="extract_method",+ file_path="m.cpp",+ target_symbol="load",+ line_start=1,+ line_end=12,+ plan=plan,+ evidence={"slice_nloc": 8, "ccn_removed": 2},+ impact_delta=0.5,+ effort_bucket="S",+ blast_radius={"scope": "local"},+ confidence="high",+ source_biomarker="complex_method",+ )+++def test_an_awaiting_span_with_no_async_host_is_a_judgment_call():+ base = {"span": {"start": 3, "end": 9}, "params": [], "returns": []}+ blocked = classify_step(_step({**base, "needs_async": True, "async_host": False}))+ assert blocked.classification == "judgment"+ assert blocked.reasons == ("async_helper_unexpressible",)+ for plan in (+ {**base, "needs_async": True, "async_host": True},+ {**base, "needs_async": False},+ base, # stored before the field existed+ ):+ assert classify_step(_step(plan)).classification == "mechanical"diff --git a/tests/unit/health/test_refactoring_extract_method.py b/tests/unit/health/test_refactoring_extract_method.pyindex fe522badb..0451b0f6c 100644--- a/tests/unit/health/test_refactoring_extract_method.py+++ b/tests/unit/health/test_refactoring_extract_method.py@@ -227,8 +227,13 @@ def _find_extractions_reference(analysis, lmap):):continuespan = stmts[i : j + 1]- decisions, has_jump = _span_metrics(- span, decision_kinds, jump_kinds, scope_kinds, _exit_macros(lmap)+ decisions, has_jump, has_await = _span_metrics(+ span,+ decision_kinds,+ jump_kinds,+ scope_kinds,+ _exit_macros(lmap),+ (lmap.await_kinds, lmap.await_scope_kinds),)if has_jump or decisions < _MIN_CCN_REMOVED:continue@@ -254,6 +259,7 @@ def _find_extractions_reference(analysis, lmap):returns=returns,slice_nloc=slice_nloc,ccn_removed=decisions,+ needs_async=has_await,))return _sorted(out)@@ -569,7 +575,8 @@ def test_detector_emits_suggestion_for_flagged_function():assert 0 < share < 1assert s.impact_delta == round(1.5 * share, 3)# Plan shape is the locked schema.- assert set(s.plan) == {"span", "params", "returns", "suggested_name"}+ assert set(s.plan) == {"span", "params", "returns", "suggested_name", "needs_async"}+ assert s.plan["needs_async"] is Falseassert set(s.plan["span"]) == {"start", "end"}assert set(s.evidence) == {"slice_nloc", "ccn_removed"}# A categorical claim, not a count: extraction is local, so there is nothing