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(fix-first): quote an Extract Method step's anchors instead of its lines (#3481)
Raghav Chamadiyaba6514d58c81
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.mdindex 77b35cb99..1fde1ba82 100644--- a/docs/layers/CODE_HEALTH.md+++ b/docs/layers/CODE_HEALTH.md@@ -131,7 +131,7 @@ worth doing.| `next` | Worth doing, needs judgment || `later` | Real but can wait; the reason is shown |-A `now` or `next` item shows its first step and the command that checks it without opening it, on the card, and over MCP for the lead and for each item of an `only=["fix_first"]` page. When no test reaches the code, Verify says to add a characterization test first. An Extract Method step shows the helper's header and the call that replaces the lines, ready to copy.+A `now` or `next` item shows its first step and the command that checks it without opening it, on the card, and over MCP for the lead and for each item of an `only=["fix_first"]` page. When no test reaches the code, Verify says to add a characterization test first. An Extract Method step shows the helper's header and the call that replaces the lines, ready to copy. It finds the lines by the text they start and end with, as the plan does, since line numbers move with the first edit; when that text also appears elsewhere in the file, the step says to keep the edit inside its function.Findings, performance causes, refactoring plans and Fix first items are counted thesame way everywhere: open in the inventory, in scope, eligible, due (tier `now` ordiff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex 90b5b8485..2f6ed488f 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -331,12 +331,12 @@ One ranked queue across refactoring, performance and code-shape work, the same o| `counts` | `inventory` (every unit considered), `in_scope` (less units excluded for where the code lives: `test`, `tooling`, `generated`, `vendored`, `docs_example`), `eligible` (became an item), `due` (eligible items in tier `now` or `next`), `shown` (items in this response), `excluded` (every non-zero exclusion, by reason) || `tier` | `now` (worth doing, safe to start), `next` (worth doing, needs judgment), `later` || `kind` | `refactor` (one file's composed refactoring), `perf_fix` (one intervention with its sinks), `finding` (a code-shape finding with no plan) |-| `totals` | `candidates`, `eligible`, `shown`, `excluded` counted by reason (`gated_off`: a constant flag in the same file switches the function off; `unreachable`: sure dead code, delete it), and `dormant`: distinct functions kept out as `gated_off` |-| `by_improves`, `basis`, `model_version`, `detail_call` | Rollup, basis, and the call that opens the lead in full |+| `totals` | `candidates`, `eligible`, `shown`, and `dormant`: distinct functions kept out as `gated_off`. The exclusions by reason are in `counts.excluded` (`gated_off`: a constant flag in the same file switches the function off; `unreachable`: sure dead code, delete it) |+| `by_improves`, `detail_call` | Rollup, and the call that opens the lead in full; the analysed commit and time are in `_meta.health_analysis` |Findings, performance causes and refactoring plans carry the same count object when their list is named in `only`: `top_findings_counts`, `performance_opportunities_counts`, `refactoring_plans_counts`. The CLI and dashboard report the same numbers.-Items are ordered by value first, then tier. History markers (churn, ownership, co-change, prior fixes) never create or lead an item; they ride on an item under `context`, and history-only files count under `totals.excluded.history_only`. `fix_first` always describes production code, whatever `scope` says; `limit` caps the items, never which leads.+Items are ordered by value first, then tier. History markers (churn, ownership, co-change, prior fixes) never create or lead an item; they ride on an item under `context`, and history-only files count under `counts.excluded.history_only`. `fix_first` always describes production code, whatever `scope` says; `limit` caps the items, never which leads.### Dashboard and metric rowsdiff --git a/packages/core/src/repowise/core/analysis/health/fix_first/build.py b/packages/core/src/repowise/core/analysis/health/fix_first/build.pyindex 4fe9cf4ec..0a59dcc59 100644--- a/packages/core/src/repowise/core/analysis/health/fix_first/build.py+++ b/packages/core/src/repowise/core/analysis/health/fix_first/build.py@@ -34,7 +34,7 @@ Row shapes (field names are the SQL columns):``plans``Plan rows named by a refactoring step: ``public_id``, ``evidence`` /``evidence_json`` and ``plan`` / ``plan_json`` (an extract-method ``span``,- ``params``, ``returns``, ``suggested_name``; a move's destination; a+ ``params``, ``returns``, ``suggested_name``, ``anchors``; a move's destination; asplit's named groups; a helper's ``occurrences``). A plan row that alsocarries ``refactoring_type`` ``extract_method``, ``file_path`` and``target_symbol`` can give a finding with no plan of its own its first@@ -91,6 +91,7 @@ from repowise.core.analysis.health.queue.value import (tier,worth,)+from repowise.core.analysis.health.refactoring.recipe import ELSEWHERE_NOTE, plan_anchorsfrom repowise.core.analysis.health.refactoring.render import NAME_PLACEHOLDERfrom repowise.core.analysis.health.rows import detail_map, field, json_fieldfrom repowise.core.analysis.health.scoring import biomarker_dimension@@ -106,6 +107,7 @@ from repowise.core.analysis.health.worth import (worth_size,)from repowise.core.analysis.next_call import ActionCommand+from repowise.core.ci.markdown import code as md_codefrom . import textfrom .model import (@@ -400,19 +402,7 @@ class _Files:if best is not None:start, end = _span(best)body = _plan_body(best)- into = text.signature(- body.get("suggested_name"),- list(body.get("params") or []),- list(body.get("returns") or []),- is_async=bool(body.get("needs_async", False)),- )- return FixStep(- 1,- _stage_one(f"Extract lines {start}-{end} of {tail} into {into}", tail, body),- path,- start,- **_helper_code(body),- )+ return FixStep(1, _extract_text(tail, body, start, end), path, start, **_helper_code(body))shape = self.shape(path, function)start, end = shape.get("deep_start"), shape.get("deep_end")if start and end:@@ -637,58 +627,87 @@ def _refactor_step(kind = step.get("refactoring_type") or ""path = step.get("file_path") or ""sym = text.short_symbol(step.get("target_symbol")) or text.basename(path)- start, end = _span(plan)body = _plan_body(plan)- code: dict[str, str | None] = {}- if kind == "extract_method":- code = _helper_code(body)- into = text.signature(- body.get("suggested_name"),- list(body.get("params") or []),- list(body.get("returns") or []),- is_async=bool(body.get("needs_async", False)),- )- where = f"lines {start}-{end} of {sym}" if start and end else f"part of {sym}"- line_text = _stage_one(f"Extract {where} into {into}", sym, body)- elif kind == "extract_helper":- line_text = f"Replace the duplicate in {sym} with a call to one shared helper"- elif kind == "extract_class":- groups = [g for g in body.get("groups") or [] if g.get("methods")]- members = sorted(groups, key=lambda g: len(g["methods"]))[0]["methods"] if groups else []- line_text = (- f"Move {', '.join(members[:4])}"- + (f" and {len(members) - 4} more" if len(members) > 4 else "")- + f" out of {sym} into a new class"- if members- else f"Move a cohesive group of {sym}'s methods into a new class"- )- elif kind == "split_file":- names = [g.get("name") for g in body.get("groups") or [] if g.get("name")]- line_text = (- f"Split {text.basename(path)} into {', '.join(names[:4])}"- + (f" and {len(names) - 4} more" if len(names) > 4 else "")- if names- else f"Split {text.basename(path)} along its independent groups"- )- elif kind == "break_cycle":- edge = _cut_edge(plan)- line_text = (- f"Cut the import of {text.basename(edge['to'])} in "- f"{text.basename(edge['from'])} (line {edge['line']})"- if edge- else _uncut_cycle_text(path, plan)- )- elif kind == "move_method":- dest = body.get("to_class") or text.basename(body.get("to_file") or "")- line_text = (- f"Move {sym} to {dest}" if dest else f"Move {sym} to the class it uses most"- )- else:- line_text = f"Apply the {text.humanize(kind)} step to {sym}"+ phrase = _STEP_TEXT.get(kind)+ line_text = (+ phrase(sym, path, plan, body) if phrase else f"Apply the {text.humanize(kind)} step to {sym}"+ )+ code = _helper_code(body) if kind == "extract_method" else {}mechanical = (step.get("applicability") or {}).get("classification") == "mechanical"- return FixStep(- order, line_text, path, start or step.get("line_start"), mechanical, **code, command=command+ line = _span(plan)[0] or step.get("line_start")+ return FixStep(order, line_text, path, line, mechanical, **code, command=command)+++def _first_four(names: list[str]) -> str:+ """Up to four names, then how many more."""+ more = f" and {len(names) - 4} more" if len(names) > 4 else ""+ return f"{', '.join(names[:4])}{more}"+++def _extract_class_text(sym: str, path: str, plan: Any, body: Mapping[str, Any]) -> str:+ """The smallest named group of methods leaves for a new class."""+ groups = [g for g in body.get("groups") or [] if g.get("methods")]+ if not groups:+ return f"Move a cohesive group of {sym}'s methods into a new class"+ members = sorted(groups, key=lambda g: len(g["methods"]))[0]["methods"]+ return f"Move {_first_four(members)} out of {sym} into a new class"+++def _split_file_text(sym: str, path: str, plan: Any, body: Mapping[str, Any]) -> str:+ names = [g.get("name") for g in body.get("groups") or [] if g.get("name")]+ if not names:+ return f"Split {text.basename(path)} along its independent groups"+ return f"Split {text.basename(path)} into {_first_four(names)}"+++def _break_cycle_text(sym: str, path: str, plan: Any, body: Mapping[str, Any]) -> str:+ edge = _cut_edge(plan)+ if edge is None:+ return _uncut_cycle_text(path, plan)+ return (+ f"Cut the import of {text.basename(edge['to'])} in "+ f"{text.basename(edge['from'])} (line {edge['line']})"+ )+++def _move_method_text(sym: str, path: str, plan: Any, body: Mapping[str, Any]) -> str:+ dest = body.get("to_class") or text.basename(body.get("to_file") or "")+ return f"Move {sym} to {dest}" if dest else f"Move {sym} to the class it uses most"+++def _extract_text(sym: str, body: Mapping[str, Any], start: Any, end: Any) -> str:+ """An Extract Method step: its span by the text it starts and ends with+ when the plan anchored it (line numbers move with every edit), else by+ its lines; a staged plan's step is its first stage."""+ into = text.signature(+ body.get("suggested_name"),+ list(body.get("params") or []),+ list(body.get("returns") or []),+ is_async=bool(body.get("needs_async", False)),)+ anchors = plan_anchors(body.get("anchors"))+ # Worded like the plan's own step (``recipe._extract_step``).+ if anchors is not None:+ where = f"{sym} from {md_code(anchors['first'])} to {md_code(anchors['last'])}"+ else:+ where = f"lines {start}-{end} of {sym}" if start and end else f"part of {sym}"+ line_text = _stage_one(f"Extract {where} into {into}", body)+ if anchors is not None and anchors["unique_in"] == "function":+ line_text = f"{line_text}. {ELSEWHERE_NOTE}"+ return line_text+++#: A refactoring step's sentence, by plan type, from (symbol, path, plan, plan body).+_STEP_TEXT: dict[str, Callable[[str, str, Any, Mapping[str, Any]], str]] = {+ "extract_method": lambda sym, path, plan, body: _extract_text(sym, body, *_span(plan)),+ "extract_helper": lambda sym, *_: (+ f"Replace the duplicate in {sym} with a call to one shared helper"+ ),+ "extract_class": _extract_class_text,+ "split_file": _split_file_text,+ "break_cycle": _break_cycle_text,+ "move_method": _move_method_text,+}def _stage_count(body: Mapping[str, Any]) -> int:@@ -711,9 +730,9 @@ def _has_span(stage: Any) -> bool:return type(start) is int and type(end) is int and bool(start and end)-def _stage_one(line_text: str, sym: str, body: Mapping[str, Any]) -> str:- """A staged plan's step is its first stage (the plan's top-level span),- so it says so and names what the whole plan does."""+def _stage_one(line_text: str, body: Mapping[str, Any]) -> str:+ """A staged plan's step is its first stage (the plan's top-level span):+ it says so, and the function's CCN once every stage is done."""count = _stage_count(body)if not count:return line_text@@ -723,8 +742,12 @@ def _stage_one(line_text: str, sym: str, body: Mapping[str, Any]) -> str:if isinstance(residual, dict)else (None, None))- ccn = f", CCN {before} -> {after}" if before is not None and after is not None else ""- return f"Stage 1 of {count}: {line_text} (the plan splits {sym} into {count} helpers{ccn})"+ ccn = (+ f" (CCN {before} -> {after} after all {count})"+ if before is not None and after is not None+ else ""+ )+ return f"Stage 1 of {count}: {line_text}{ccn}"def _uncut_cycle_text(path: str, plan: Any) -> str:diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recipe.py b/packages/core/src/repowise/core/analysis/health/refactoring/recipe.pyindex 02d638e29..02a896f59 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/recipe.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recipe.py@@ -178,7 +178,7 @@ def _extract_step(d: Mapping[str, Any], plan: Mapping[str, Any]) -> Step:if plan.get("suggested_name")else " (name it for what the lines do)")- anchors = _anchors(plan.get("anchors"))+ anchors = plan_anchors(plan.get("anchors"))lines = (f"the span of `{host}` that starts and ends with the lines shown "f"(lines {where['start']}-{where['end']} when planned)"@@ -209,7 +209,7 @@ def _extract_step(d: Mapping[str, Any], plan: Mapping[str, Any]) -> Step:)-def _anchors(value: Any) -> dict[str, str] | None:+def plan_anchors(value: Any) -> dict[str, str] | None:"""A span's text anchors (``refactoring.anchors``), None on an older row.``unique_in`` is ``"function"`` when the text also occurs elsewhere in thefile, so a text match must stay inside the host."""@@ -588,10 +588,7 @@ SCRIPT_RULE: dict[str, str | None] = {"reason": "make each edit directly in the file, one at a time, re-reading the span after each",}#: Said under a step whose anchors are unique only inside its function.-ELSEWHERE_NOTE = (- "This text also appears elsewhere in the file: keep the edit inside the function this "- "step names."-)+ELSEWHERE_NOTE = "Text repeats in the file: edit only inside this function."LINE_RULE: dict[str, str | None] = {"constraint": "find a span by its line numbers","reason": "they are where it was when planned and move with every edit; match its first "@@ -694,6 +691,7 @@ __all__ = ["RecipeAction","build_recipe","label",+ "plan_anchors","recipe_steps","verify_check",]diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py b/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.pyindex 874036318..d7ea536f6 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py@@ -146,9 +146,10 @@ def _fix_first_block(data: HealthData, req: HealthRequest, pager: Pager) -> dictif not req.pages_fix_first or item["id"] == lead_id or at >= FIX_FIRST_CAP:item.pop("first_step", None)item.pop("verify", None)- # Zero reasons say nothing an agent reads; ``counts.excluded`` omits them too.- totals = block["totals"]- totals["excluded"] = {reason: n for reason, n in totals["excluded"].items() if n}+ # ``counts.excluded`` carries the same reasons without the zeros, and+ # ``_meta.health_analysis`` the analysed commit and time; the model+ # version is for reading a stored queue back, not for the agent.+ del block["totals"]["excluded"], block["basis"], block["model_version"]block["counts"] = full.counts(shown=len(page.items)).as_dict()block["items_total"] = full.totals.eligibleblock["cursor"] = req.fix_first_cursordiff --git a/packages/ui/__tests__/health/refactoring-anchor-prompt.test.ts b/packages/ui/__tests__/health/refactoring-anchor-prompt.test.tsindex b95c46dde..ae0de86df 100644--- a/packages/ui/__tests__/health/refactoring-anchor-prompt.test.ts+++ b/packages/ui/__tests__/health/refactoring-anchor-prompt.test.ts@@ -58,15 +58,15 @@ describe("Extract Method anchors", () => {expect(prompt).toContain("- **Replace the span with:** `total = _sum_rows(rows)`");expect(prompt).not.toContain("Replace lines");expect(prompt).toContain(`${SCRIPT_RULE_TEXT} ${LINE_RULE_TEXT}`);- expect(prompt).not.toContain("appears elsewhere in the file");+ expect(prompt).not.toContain("Text repeats in the file");});- it("says when the anchor text also appears elsewhere in the file", () => {+ it("says when the anchor text repeats elsewhere in the file", () => {const prompt = buildRefactoringPlanPrompt({plan: plan({ anchors: { first: " a = 1", last: " b = 2", unique_in: "function" } }),});expect(prompt).toContain(- "```\n b = 2\n```\n- This text also appears elsewhere in the file: keep the edit inside the function this step names.",+ "```\n b = 2\n```\n- Text repeats in the file: edit only inside this function.",);});diff --git a/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts b/packages/ui/src/health/ai-prompts/refactoring-plan-steps.tsindex e84522f06..4babe43a6 100644--- a/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts+++ b/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts@@ -68,8 +68,7 @@ export const SCRIPT_RULE_TEXT ="Do not generate a script that rewrites the file. Make each edit directly in the file, one at a time, re-reading the span after each.";export const LINE_RULE_TEXT ="Do not find a span by its line numbers. They are where it was when planned and move with every edit; match its first and last lines.";-const ELSEWHERE_NOTE =- "This text also appears elsewhere in the file: keep the edit inside the function this step names.";+const ELSEWHERE_NOTE = "Text repeats in the file: edit only inside this function.";interface SpanAnchors {first: string;diff --git a/tests/unit/health/test_fix_first_build.py b/tests/unit/health/test_fix_first_build.pyindex a473fd7cb..51a75405e 100644--- a/tests/unit/health/test_fix_first_build.py+++ b/tests/unit/health/test_fix_first_build.py@@ -7,6 +7,7 @@ import copyimport pytestfrom repowise.core.analysis.health.fix_first import FIX_EXCLUSIONS, build_fix_first+from repowise.core.analysis.health.refactoring.recipe import ELSEWHERE_NOTEfrom tests.unit.health.fix_first_rows import (FINDINGS,METRICS,@@ -389,7 +390,7 @@ def test_a_staged_lead_plan_names_its_helpers_and_stage_one() -> None:assert core.title == "Split run into 3 helpers (+1 more step)"assert core.action.steps[0].text == ("Stage 1 of 3: Extract lines 20-35 of run into sum_rows(rows, limit) -> total "- "(the plan splits run into 3 helpers, CCN 44 -> 9)"+ "(CCN 44 -> 9 after all 3)")# Only the staged plan's step says so; the plan's next step reads as before.assert core.action.steps[1].text == (@@ -401,7 +402,9 @@ def test_a_staged_plan_without_its_complexity_figures_leaves_them_out() -> None:core = next(i for i in _build(plans=_staged_plans(2, orchestrator={})).items if i.kind == "refactor")- assert core.action.steps[0].text.endswith("(the plan splits run into 2 helpers)")+ assert core.action.steps[0].text == (+ "Stage 1 of 2: Extract lines 20-35 of run into sum_rows(rows, limit) -> total"+ )def test_a_finding_borrowing_a_staged_span_says_it_is_staged() -> None:@@ -410,7 +413,7 @@ def test_a_finding_borrowing_a_staged_span_says_it_is_staged() -> None:lone = _build(plans=plans, refactoring=[], performance=[]).leadassert lone.action.steps[0].text == ("Stage 1 of 3: Extract lines 20-35 of run into sum_rows(rows, limit) -> total "- "(the plan splits run into 3 helpers, CCN 44 -> 9)"+ "(CCN 44 -> 9 after all 3)")@@ -435,7 +438,7 @@ def test_malformed_stages_never_crash_or_say_one_helper(stages, orchestrator) ->step = core.action.steps[0].textassert "into 1 helpers" not in step and "into 1 helpers" not in core.titleif step.startswith("Stage 1 of 2"):- assert step.endswith("(the plan splits run into 2 helpers)")+ assert step.endswith("sum_rows(rows, limit) -> total")else:assert step == "Extract lines 20-35 of run into sum_rows(rows, limit) -> total"@@ -446,3 +449,60 @@ def test_an_unstaged_plan_reads_as_before() -> None:"Start breaking up run (CCN 44, 50 lines): first lift lines 20-35 into sum_rows")assert core.action.steps[0].text == "Extract lines 20-35 of run into sum_rows(rows, limit) -> total"+++def _anchored_plans(anchors: dict, staged: bool = False) -> list:+ plans = _staged_plans() if staged else copy.deepcopy(PLANS)+ plans[0]["plan"]["anchors"] = anchors+ return plans+++def test_an_anchored_step_quotes_the_text_its_span_starts_and_ends_with() -> None:+ anchors = {"first": " total = 0", "last": " return total", "unique_in": "file"}+ core = next(i for i in _build(plans=_anchored_plans(anchors)).items if i.kind == "refactor")+ step = core.action.steps[0]+ assert step.text == (+ "Extract run from ` total = 0` to ` return total` into sum_rows(rows, limit) -> total"+ )+ # The line stays as a hint; the anchors replace the line range in the text.+ assert step.line == 20 and "lines 20-35" not in step.text+++def test_a_staged_anchored_step_quotes_its_first_stage_with_the_helper_brief() -> None:+ plans = _anchored_plans({"first": "a = 1", "last": "b = `x`", "unique_in": "file"}, staged=True)+ plans[0]["plan"]["new_symbol"] = {"signature_text": "def sum_rows(rows, limit):"}+ core = next(i for i in _build(plans=plans).items if i.kind == "refactor")+ # A backtick inside an anchor widens its fence; the text keeps the helper's brief+ # because a surface that shows only the text has no header beside it.+ assert core.action.steps[0].text == (+ "Stage 1 of 3: Extract run from `a = 1` to `` b = `x` `` into "+ "sum_rows(rows, limit) -> total (CCN 44 -> 9 after all 3)"+ )+ assert core.action.steps[0].signature == "def sum_rows(rows, limit):"+++def test_an_anchor_unique_only_in_its_function_says_so() -> None:+ anchors = {"first": "x = 1\n y = 2", "last": "return y", "unique_in": "function"}+ plans = _anchored_plans(anchors)+ plans[0].update(file_path="src/core.py", target_symbol="src/core.py::run")+ lone = _build(plans=plans, refactoring=[], performance=[]).lead+ # A finding with no plan of its own borrows the span with its anchors.+ assert lone.action.steps[0].text == (+ "Extract run from `x = 1\n y = 2` to `return y` into sum_rows(rows, limit) -> total. "+ f"{ELSEWHERE_NOTE}"+ )+++def test_a_staged_anchor_unique_only_in_its_function_says_so_after_the_stage() -> None:+ plans = _anchored_plans({"first": "a = 1", "last": "b = 2", "unique_in": "function"}, staged=True)+ core = next(i for i in _build(plans=plans).items if i.kind == "refactor")+ assert core.action.steps[0].text == (+ "Stage 1 of 3: Extract run from `a = 1` to `b = 2` into sum_rows(rows, limit) -> total "+ f"(CCN 44 -> 9 after all 3). {ELSEWHERE_NOTE}"+ )+++def test_malformed_anchors_fall_back_to_lines() -> None:+ plans = _anchored_plans({"first": "a = 1", "last": None})+ core = next(i for i in _build(plans=plans).items if i.kind == "refactor")+ assert core.action.steps[0].text == "Extract lines 20-35 of run into sum_rows(rows, limit) -> total"