Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(refactoring): anchor every Extract Method stage by its first and last lines (#3468)

Raghav Chamadiya0df153d91866
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.md
index 571a016cf..605e05329 100644
--- a/docs/layers/REFACTORING.md
+++ b/docs/layers/REFACTORING.md
@@ -273,6 +273,12 @@ Most plans answer a health finding, so per-path marker rules in
labelled sections is named after them. When a function moves
between a single helper and a staged plan, or its stages change, the plan
gets a new id.
+- Every Extract Method step, and every stage of a staged plan, shows the exact
+ first and last lines of its span, so an agent finds it by its text after
+ earlier stages have moved its lines; the line numbers are only a hint. The
+ plan asks for each stage as a direct edit to the file, one at a time, never a
+ script that rewrites it. A staged plan whose stages cannot all be pinned down
+ that way falls back to a single helper, and a function with neither gets no plan.
- Move Method never targets a class the method only instantiates, or an ancestor of
its own class.
- Split File works on any language with call resolution and suggests a split only
diff --git a/packages/core/src/repowise/core/agent_prompts/refactoring.py b/packages/core/src/repowise/core/agent_prompts/refactoring.py
index 890310618..d7ce77a50 100644
--- a/packages/core/src/repowise/core/agent_prompts/refactoring.py
+++ b/packages/core/src/repowise/core/agent_prompts/refactoring.py
@@ -10,7 +10,15 @@ from __future__ import annotations
from collections.abc import Mapping
from typing import Any
-from repowise.core.analysis.health.refactoring.recipe import build_recipe, label, verify_check
+from repowise.core.analysis.health.refactoring.recipe import (
+ ELSEWHERE_NOTE,
+ LINE_RULE,
+ SCRIPT_RULE,
+ build_recipe,
+ label,
+ verify_check,
+)
+from repowise.core.ci.markdown import longest_backtick_run
from .preamble import preamble
from .sections import bullet_list, closing_sections, join_sections, repo_suffix
@@ -46,8 +54,8 @@ def _symbol_lines(step: Mapping[str, Any]) -> list[str]:
if symbol.get("return_text"):
out.append(f"End the helper with: `{symbol['return_text']}`")
if call.get("new_text"):
- lines = f"{span.get('start')}-{span.get('end')}"
- out.append(f"Replace lines {lines} with: `{call['new_text']}`")
+ lines = "the span" if step.get("anchors") else f"lines {span.get('start')}-{span.get('end')}"
+ out.append(f"Replace {lines} with: `{call['new_text']}`")
if symbol:
out.append(f"Parameters (in): {', '.join(symbol.get('params') or []) or '(none)'}")
out.append(f"Returns (out): {', '.join(symbol.get('returns') or []) or '(nothing)'}")
@@ -66,10 +74,27 @@ def _step_lines(step: Mapping[str, Any]) -> list[str]:
return out
+def _anchor_lines(step: Mapping[str, Any], pad: str) -> list[str]:
+ """The span's first and last lines, each fenced at column 0 so its
+ indentation reads exactly as the file has it."""
+ anchors = step.get("anchors")
+ if not anchors:
+ return []
+ out = []
+ for edge, text in (("starts", anchors["first"]), ("ends", anchors["last"])):
+ fence = "`" * max(3, longest_backtick_run(text) + 1)
+ out += [f"{pad} - The span {edge} with:", fence, text, fence]
+ if anchors.get("unique_in") == "function":
+ out.append(f"{pad} - {ELSEWHERE_NOTE}")
+ return out
+
+
def _step_entry(step: Mapping[str, Any], marker: str, pad: str) -> str:
where = f" ({_loc(step['file'], step.get('span'))})" if step.get("file") else ""
head = f"{pad}{marker} {step['text']}{where}"
- return "\n".join([head, *(f"{pad} - {line}" for line in _step_lines(step))])
+ return "\n".join(
+ [head, *_anchor_lines(step, pad), *(f"{pad} - {line}" for line in _step_lines(step))]
+ )
def _verify_lines(check: Mapping[str, Any], *, runnable: bool = True) -> list[str]:
@@ -114,13 +139,14 @@ def _before_section(recipe: Mapping[str, Any]) -> str:
return join_sections(["## Before you edit", "", bullet_list(pre), ""])
+def _rule(item: Mapping[str, Any]) -> str:
+ reason = item.get("reason")
+ tail = f" {reason[0].upper()}{reason[1:]}." if reason else ""
+ return f"**Do not {item['constraint']}.**{tail}"
+
+
def _does_not(recipe: Mapping[str, Any]) -> list[str]:
- out = []
- for item in recipe["does_not"]:
- reason = item.get("reason")
- tail = f" {reason[0].upper()}{reason[1:]}." if reason else ""
- out.append(f"**Do not {item['constraint']}.**{tail}")
- return out
+ return [_rule(item) for item in recipe["does_not"]]
#: The heading an advisory plan's steps sit under, unnumbered.
@@ -381,14 +407,30 @@ def _opportunity_handoff(o: Mapping[str, Any], flavor: str) -> str:
)
-_OPPORTUNITY_CONSTRAINTS = (
+_OPPORTUNITY_ORDER = (
"**Apply the steps in the order given.** It is dependency-safe; reordering it is not.",
"**Read a judgment step's code before applying it.** Its obligation is unproven.",
+)
+_OPPORTUNITY_CONSTRAINTS = (
"**Keep behaviour.** Run the tests (and type-checker / linter) before and after.",
*_CONSTRAINTS,
)
+def _edit_rules(steps: list[Any], plans: Mapping[Any, Any]) -> list[str]:
+ """Extract Method's apply rules, only for an opportunity holding such a
+ step: no script always, find-by-text only when a step's plan is anchored."""
+ extracts = [
+ plans.get(s.get("plan_id")) or {}
+ for s in steps
+ if s.get("refactoring_type") == "extract_method"
+ ]
+ if not extracts:
+ return []
+ anchored = any((p.get("plan") or {}).get("anchors") for p in extracts)
+ return [_rule(SCRIPT_RULE), *([_rule(LINE_RULE)] if anchored else [])]
+
+
def render_opportunity(
detail: Mapping[str, Any], flavor: str = "generic", repo_name: str | None = None
) -> str:
@@ -421,7 +463,10 @@ def render_opportunity(
"",
_opportunity_evidence(detail),
_opportunity_verify(detail),
- *closing_sections(_OPPORTUNITY_CONSTRAINTS, expected),
+ *closing_sections(
+ [*_OPPORTUNITY_ORDER, *_edit_rules(steps, plans), *_OPPORTUNITY_CONSTRAINTS],
+ expected,
+ ),
_opportunity_handoff(detail, flavor),
]
)
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/anchors.py b/packages/core/src/repowise/core/analysis/health/refactoring/anchors.py
new file mode 100644
index 000000000..755a66386
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/anchors.py
@@ -0,0 +1,157 @@
+"""Text anchors for an Extract Method span, so an agent finds it by its text.
+
+Line numbers go stale with the first edit: a staged plan applied by line
+number, stage after stage, moves every later span. An anchor is the exact
+text the span starts with and the text it ends with, so a string-matching
+edit finds the span wherever it has moved to; the line numbers stay as a hint.
+
+``first`` is the span's first line, ``last`` its last, with indentation as
+written and no trailing line ending. When that line also occurs elsewhere,
+the anchor grows by the next line in (``first``) or the line before
+(``last``), within :data:`MAX_ANCHOR_LINES` lines that hold a word (a run of
+closing brackets or a blank line does not count). A multi-line anchor keeps
+the file's own line endings, so it matches the bytes on disk, CRLF included.
+Occurrences are counted as substrings, the way a string-matching edit sees
+them.
+
+An anchor unique in the whole file is preferred (``unique_in: "file"``); one
+unique only inside the function (``"function"``) is kept, and the plan says
+the edit must stay inside its host. A span with no anchor unique even in the
+function gets none, and its plan is refused (``extract_method``): a stage
+served with line numbers alone is the one that gets scripted over the file.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Literal, NamedTuple, get_args
+
+#: The longest anchor, in lines holding a word. A span whose ends repeat for
+#: longer is a copied block, which a text match cannot tell apart from its twin.
+MAX_ANCHOR_LINES = 4
+
+AnchorScope = Literal["file", "function"]
+#: Where an anchor is unique (``unique_in``), mirrored in ``packages/types``.
+ANCHOR_SCOPES: tuple[str, ...] = get_args(AnchorScope)
+
+
+class Source(NamedTuple):
+ """One file's text as written and its lines, each still ending in ``\\r``
+ in a CRLF file, so joining them with ``\\n`` gives the text back."""
+
+ text: str
+ rows: list[str]
+
+
+class Scope(NamedTuple):
+ """The function a span lives in: its file, first and last line, and text."""
+
+ source: Source
+ start: int
+ end: int
+ text: str
+
+
+def file_source(fn_node: Any) -> Source | None:
+ """The file *fn_node* was parsed from, or None without its source."""
+ root = fn_node
+ while root.parent is not None:
+ root = root.parent
+ src = root.text
+ if not src:
+ return None
+ # The root starts at the first token: put back the blank lines above it so
+ # rows line up with line numbers (what it skipped is whitespace only).
+ row, column = root.start_point
+ text = "\n" * row + " " * column + src.decode("utf-8", errors="replace")
+ return Source(text, text.split("\n"))
+
+
+def function_scope(fn_node: Any, source: Source | None) -> Scope | None:
+ """The function's whole lines (its first from column 0) in *source*, or
+ None without a parsed function or its source."""
+ if fn_node is None or source is None:
+ return None
+ start, end = fn_node.start_point[0] + 1, fn_node.end_point[0] + 1
+ return Scope(source, start, end, "\n".join(source.rows[start - 1 : end]))
+
+
+def occurrences(text: str, snippet: str) -> int:
+ """How many times *snippet* occurs in *text*, overlaps included."""
+ count, at = 0, text.find(snippet)
+ while at >= 0:
+ count += 1
+ at = text.find(snippet, at + 1)
+ return count
+
+
+def _grown(rows: list[str]) -> list[list[str]]:
+ """*rows*' leading runs, one line longer each, while at most
+ :data:`MAX_ANCHOR_LINES` of the lines hold a word."""
+ out, words = [], 0
+ for k, row in enumerate(rows, 1):
+ words += any(ch.isalnum() for ch in row)
+ if words > MAX_ANCHOR_LINES:
+ break
+ out.append(rows[:k])
+ return out
+
+
+def _snippet(run: list[str]) -> str:
+ # The rows keep a CRLF file's ``\r``; only the snippet's own end drops it.
+ return "\n".join(run).removesuffix("\r")
+
+
+def _pick(scope: Scope, snippets: list[str]) -> tuple[str, str] | None:
+ """The shortest snippet unique in the file, else in the function, with
+ where it is unique; None when none is."""
+ snippets = [s for s in snippets if s.strip()]
+ for where, text in (("file", scope.source.text), ("function", scope.text)):
+ found = next((s for s in snippets if occurrences(text, s) == 1), None)
+ if found is not None:
+ return found, where
+ return None
+
+
+def span_anchors(scope: Scope, start: int, end: int) -> dict[str, str] | None:
+ """``{"first", "last", "unique_in"}`` for lines *start*..*end* of *scope*,
+ or None when either end has no anchor unique in the function."""
+ if not scope.start <= start <= end <= scope.end:
+ return None
+ span = scope.source.rows[start - 1 : end]
+ first = _pick(scope, [_snippet(run) for run in _grown(span)])
+ # The last anchor grows upward: grow the reversed span, then restore the order.
+ last = _pick(scope, [_snippet(run[::-1]) for run in _grown(span[::-1])])
+ if first is None or last is None:
+ return None
+ unique_in = "file" if first[1] == last[1] == "file" else "function"
+ return {"first": first[0], "last": last[0], "unique_in": unique_in}
+
+
+def anchor_plan(plan: dict[str, Any], scope: Scope | None) -> bool:
+ """Give *plan*'s span and every stage's their ``anchors``, in place.
+ False, with *plan* left as it was, when any of them cannot be anchored."""
+ targets = [plan, *(plan.get("stages") or [])]
+ found = []
+ for target in targets:
+ span = target.get("span") or {}
+ anchors = span_anchors(scope, span["start"], span["end"]) if scope and span else None
+ if anchors is None:
+ return False
+ found.append(anchors)
+ for target, anchors in zip(targets, found, strict=True):
+ target["anchors"] = anchors
+ return True
+
+
+__all__ = [
+ "ANCHOR_SCOPES",
+ "MAX_ANCHOR_LINES",
+ "AnchorScope",
+ "Scope",
+ "Source",
+ "anchor_plan",
+ "file_source",
+ "function_scope",
+ "occurrences",
+ "span_anchors",
+]
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py
index 8144fcdd2..abe743a06 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
@@ -76,6 +76,12 @@ Plan shape (open dict, no migration):
``kind`` is; ``call_site`` also when an awaiting span sits in a host that
is not async. A missing name reads ``<name>`` in them,
and ``suggested_name`` is in the language's private form (Python ``_x``).
+- ``plan.anchors`` = ``{"first": str, "last": str}`` -- the exact text the
+ span starts and ends with, each unique in the function (``anchors``), so an
+ agent finds it by text once earlier edits have moved its lines; every stage
+ carries its own. A staged split that cannot be anchored falls back to the
+ function's best single span; when that cannot be either, the function is
+ refused (``span_unanchored``).
- ``evidence`` = ``{"slice_nloc": int, "ccn_removed": int}`` -- the size and
complexity (code lines, decision points) the residual method sheds.
- ``plan.stages`` -- only on a staged plan (``dataflow.stages``): a function
@@ -115,6 +121,7 @@ from ..effort import effort_bucket
from ..perf.dialects import PERF_DIALECTS
from ..scoring import severity_deduction
from . import render
+from .anchors import Scope, anchor_plan, file_source, function_scope
from .declarative import declarative_flat
from .helper_naming import ScopeNames, helper_names, out_value_name
from .models import RefactoringContext, RefactoringSuggestion
@@ -180,6 +187,8 @@ class ExtractMethodDetector(RefactoringDetector):
out: list[RefactoringSuggestion] = []
names = ScopeNames(lmap)
dialect = get_defuse_dialect(ctx.language or "")
+ # The file's text, read off the tree once, when the first plan needs it.
+ files: dict[str, Any] = {}
# Source order, so the first of two colliding plans keeps the name.
for analysis in sorted(analyses, key=lambda a: (a.start_line, a.end_line)):
matched = self._findings_for(analysis, ctx.findings)
@@ -201,12 +210,16 @@ class ExtractMethodDetector(RefactoringDetector):
candidates = find_extractions(analysis, lmap, receiver, prefixes)
best = _choose(analysis, candidates, markers)
staged = _staged(analysis, best, lmap, receiver, ctx.language, markers, prefixes)
+ scope = _scope(fn_node, files) if staged is not None or best is not None else None
if staged is not None:
- out.append(
- self._staged_suggestion(ctx, analysis, staged, matched, names, receiver)
- )
- continue
+ split = self._staged_suggestion(ctx, analysis, staged, matched, names, receiver)
+ if anchor_plan(split.plan, scope):
+ out.append(split)
+ continue
if best is None:
+ # Nothing to fall back to from a split no text anchors.
+ if staged is not None:
+ _mark_refused(matched, "span_unanchored")
continue
impact, share, source = self._impact_for(analysis, best, matched)
name = render.private_name(
@@ -226,7 +239,8 @@ class ExtractMethodDetector(RefactoringDetector):
_symbol_fields(best, receiver),
async_host=async_fields.get("async_host", True),
)
- out.append(
+ _serve_anchored(
+ out,
RefactoringSuggestion(
refactoring_type=self.name,
file_path=ctx.file_path,
@@ -250,7 +264,9 @@ class ExtractMethodDetector(RefactoringDetector):
blast_radius={"scope": "local"},
confidence=self._confidence(best, share),
source_biomarker=source,
- )
+ ),
+ matched,
+ scope,
)
# Stable order: biggest recovery first, then symbol, then span start.
@@ -354,6 +370,27 @@ def _mark_refused(findings: list[Any], reason: str) -> None:
details[REFUSED_DETAIL] = reason
+def _scope(fn_node: Any, files: dict[str, Any]) -> Scope | None:
+ """*fn_node*'s lines in its file, the file read once per detect call."""
+ if "source" not in files and fn_node is not None:
+ files["source"] = file_source(fn_node)
+ return function_scope(fn_node, files.get("source"))
+
+
+def _serve_anchored(
+ out: list[RefactoringSuggestion],
+ suggestion: RefactoringSuggestion,
+ findings: list[Any],
+ scope: Scope | None,
+) -> None:
+ """Serve *suggestion* only when every span in it is anchored by its text
+ (``anchors``); one that is not is refused, never served by line alone."""
+ if anchor_plan(suggestion.plan, scope):
+ out.append(suggestion)
+ else:
+ _mark_refused(findings, "span_unanchored")
+
+
def recovered_share(
biomarker: str, analysis: FunctionAnalysis, extraction: Extraction
) -> float:
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recipe.py b/packages/core/src/repowise/core/analysis/health/refactoring/recipe.py
index 391e6a46d..0b00fab73 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/recipe.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recipe.py
@@ -177,15 +177,23 @@ 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"))
+ lines = (
+ f"the span of `{host}` that starts and ends with the lines shown "
+ f"(lines {where['start']}-{where['end']} when planned)"
+ if anchors
+ else f"lines {where['start']}-{where['end']} of `{host}`"
+ )
text = (
- f"Move lines {where['start']}-{where['end']} of `{host}` into a new helper "
- f"`{name}`{named} in the same scope, and replace them with one call to it."
+ f"Move {lines} into a new helper `{name}`{named} in the same scope, and replace "
+ f"{'it' if anchors else 'them'} with one call to it."
)
return _step(
"extract",
d.get("file_path"),
where,
text,
+ **({"anchors": anchors} if anchors else {}),
new_symbol={
"name": name,
"kind": symbol.get("kind"),
@@ -200,6 +208,18 @@ def _extract_step(d: Mapping[str, Any], plan: Mapping[str, Any]) -> Step:
)
+def _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 the
+ file, so a text match must stay inside the host."""
+ anchors = _dict(value)
+ first, last = anchors.get("first"), anchors.get("last")
+ if not (isinstance(first, str) and isinstance(last, str)):
+ return None
+ unique_in = "function" if anchors.get("unique_in") == "function" else "file"
+ return {"first": first, "last": last, "unique_in": unique_in}
+
+
def _extract_notes(
plan: Mapping[str, Any], symbol: Mapping[str, Any], is_async: bool
) -> list[str]:
@@ -560,6 +580,23 @@ def _postconditions(d: Mapping[str, Any]) -> list[dict[str, Any]]:
return out
+#: How an Extract Method edit is made, read after "Do not" like ``does_not``.
+#: The UI's fallback renderers repeat these words (a parity test holds them).
+SCRIPT_RULE: dict[str, str | None] = {
+ "constraint": "generate a script that rewrites the file",
+ "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."
+)
+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 "
+ "and last lines",
+}
+
#: Per type, what the edit must not do and, when it is not obvious, why.
_DOES_NOT: dict[str, tuple[str, str | None]] = {
"extract_helper": ("merge sites that differ", "a difference between them becomes a parameter"),
@@ -582,15 +619,7 @@ def _does_not(d: Mapping[str, Any], steps: list[Step]) -> list[dict[str, str | N
spans = [s["span"] for s in steps if s.get("action") == "extract" and s.get("span")]
span = {"start": spans[0]["start"], "end": spans[-1]["end"]} if spans else None
if kind == "extract_method" and span:
- lines = f"{span['start']}-{span['end']}"
- added = (
- "the calls that replace them (and the object the stages share, if any)"
- if len(spans) > 1
- else "the call that replaces them"
- )
- out.append(
- {"constraint": f"touch anything outside lines {lines} and {added}", "reason": None}
- )
+ out.extend(_extract_does_not(steps, span, len(spans) > 1))
elif kind == "extract_helper" and (name := _reused(d)):
out.append({"constraint": f"change `{name}` to fit a site", "reason": "its callers rely on it"})
elif kind in _DOES_NOT:
@@ -604,6 +633,29 @@ def _does_not(d: Mapping[str, Any], steps: list[Step]) -> list[dict[str, str | N
return out
+def _extract_does_not(
+ steps: list[Step], span: dict[str, int], staged: bool
+) -> list[dict[str, str | None]]:
+ """Extract Method's limits, and how its edits are made: by hand, each found
+ by its text when the steps carry anchors (a stage applied by line number
+ moves every later one)."""
+ lines = f"{span['start']}-{span['end']}"
+ added = (
+ "the calls that replace them (and the object the stages share, if any)"
+ if staged
+ else "the call that replaces them"
+ )
+ anchored = any(s.get("anchors") for s in steps)
+ where = f"the lines the steps move (lines {lines} when planned)" if anchored else f"lines {lines}"
+ out: list[dict[str, str | None]] = [
+ {"constraint": f"touch anything outside {where} and {added}", "reason": None},
+ dict(SCRIPT_RULE),
+ ]
+ if anchored:
+ out.append(dict(LINE_RULE))
+ return out
+
+
def build_recipe(detail: Mapping[str, Any]) -> dict[str, Any]:
"""*detail* as ``{id, kind, advisory, summary, target, preconditions, steps,
postconditions, does_not}``. Pure: reads only the dict it is given."""
@@ -629,8 +681,11 @@ def build_recipe(detail: Mapping[str, Any]) -> dict[str, Any]:
__all__ = [
+ "ELSEWHERE_NOTE",
+ "LINE_RULE",
"PRECONDITION_KINDS",
"RECIPE_ACTIONS",
+ "SCRIPT_RULE",
"TYPE_LABEL",
"RecipeAction",
"build_recipe",
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/render.py b/packages/core/src/repowise/core/analysis/health/refactoring/render.py
index a1c7e4aca..62dfebb52 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/render.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/render.py
@@ -485,9 +485,9 @@ def render_context(
#: What the renderer adds to a stored plan, served on plan detail only.
_DETAIL_SYMBOL_KEYS = ("params", "returns", "signature_text", "return_text", "notes")
-#: Plan keys on detail only: Extract Method's call and staged plan (stages,
-#: parameter object, residual), Extract Helper's calls to an existing function.
-_DETAIL_PLAN_KEYS = ("call_site", "stages", "parameter_object", "orchestrator", "reuse")
+#: Plan keys on detail only: Extract Method's call, span anchors and staged plan
+#: (stages, parameter object, residual), Extract Helper's calls to an existing function.
+_DETAIL_PLAN_KEYS = ("call_site", "anchors", "stages", "parameter_object", "orchestrator", "reuse")
def list_plan(plan: dict) -> dict:
diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.ts
index 303d17d4b..9182bb2bb 100644
--- a/packages/types/src/refactoring.ts
+++ b/packages/types/src/refactoring.ts
@@ -211,6 +211,10 @@ export type RecipePreconditionKind =
| "unchecked"
| "kind_unaudited";
+/** Where an Extract Method anchor is unique: the whole file, or only inside
+ * its function (a text match must then stay inside the host). */
+export type AnchorScope = "file" | "function";
+
export interface RecipeStep {
n: number;
action: RecipeAction;
@@ -232,6 +236,9 @@ export interface RecipeStep {
notes: string[];
};
call_site?: ExtractCallSite;
+ /** Extract Method: the exact text the span starts and ends with, so the
+ * step is found by text, not line. */
+ anchors?: { first: string; last: string; unique_in: AnchorScope };
symbols?: string[];
to_file?: string | null;
/** Extract Helper: the directory the shared helper belongs in. */
diff --git a/packages/ui/__tests__/health/refactoring-anchor-prompt.test.ts b/packages/ui/__tests__/health/refactoring-anchor-prompt.test.ts
new file mode 100644
index 000000000..b95c46dde
--- /dev/null
+++ b/packages/ui/__tests__/health/refactoring-anchor-prompt.test.ts
@@ -0,0 +1,100 @@
+/**
+ * An Extract Method span is found by the text core serves (`plan.anchors`), not
+ * by its line numbers, and the plan says to make the edit by hand. The prompts
+ * name capabilities, never a harness's tools.
+ */
+import { describe, expect, it } from "vitest";
+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
+
+import { buildRefactoringPlanPrompt } from "../../src/health/ai-prompt-builder";
+import {
+ LINE_RULE_TEXT,
+ SCRIPT_RULE_TEXT,
+} from "../../src/health/ai-prompts/refactoring-plan-steps";
+
+const TOOLS = /\b(Read|Grep|Glob|Edit|Write|TodoWrite|Bash|str_replace)\b/;
+
+function plan(extra: Record<string, unknown> = {}): RefactoringPlan {
+ return {
+ id: "refac4_walk",
+ refactoring_type: "extract_method",
+ file_path: "pkg/walker.py",
+ target_symbol: "walk_file",
+ line_start: 94,
+ line_end: 208,
+ plan: {
+ span: { start: 120, end: 140 },
+ params: ["rows"],
+ returns: ["total"],
+ suggested_name: "_sum_rows",
+ new_symbol: { kind: "function", signature_text: "def _sum_rows(rows):" },
+ call_site: { replace_span: { start: 120, end: 140 }, new_text: "total = _sum_rows(rows)" },
+ ...extra,
+ },
+ evidence: {},
+ impact_delta: 1.2,
+ effort_bucket: "M",
+ blast_radius: {},
+ confidence: "high",
+ source_biomarker: "complex_method",
+ rank_score: 1,
+ };
+}
+
+describe("Extract Method anchors", () => {
+ it("shows the span's first and last lines exactly, fenced at column 0", () => {
+ const prompt = buildRefactoringPlanPrompt({
+ plan: plan({
+ anchors: { first: "\tfor row in rows:", last: ' out.append(f"`{row}`")\n return out' },
+ }),
+ });
+ expect(prompt).toContain(
+ "Extract the span of `walk_file` that starts and ends with the lines shown (lines 120–140 when planned)",
+ );
+ expect(prompt).toContain("- **The span starts with:**\n```\n\tfor row in rows:\n```");
+ expect(prompt).toContain(
+ '- **The span ends with:**\n```\n out.append(f"`{row}`")\n return out\n```',
+ );
+ 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");
+ });
+
+ it("says when the anchor text also appears 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.",
+ );
+ });
+
+ it("widens the fence past a backtick run in the anchor", () => {
+ const prompt = buildRefactoringPlanPrompt({
+ plan: plan({ anchors: { first: " s = ```x```", last: " return s" } }),
+ });
+ expect(prompt).toContain("````\n s = ```x```\n````");
+ });
+
+ it("keeps line numbers on a plan stored before anchors", () => {
+ const prompt = buildRefactoringPlanPrompt({ plan: plan() });
+ expect(prompt).toContain("Extract lines 120–140 of `walk_file`");
+ expect(prompt).toContain("- **Replace lines 120–140 with:** `total = _sum_rows(rows)`");
+ expect(prompt).toContain(SCRIPT_RULE_TEXT);
+ expect(prompt).not.toContain(LINE_RULE_TEXT);
+ });
+
+ it("names no harness tool in the steps it renders", () => {
+ for (const flavor of ["generic", "claude-code", "claude-code-mcp", "cursor"] as const) {
+ const prompt = buildRefactoringPlanPrompt({
+ plan: plan({ anchors: { first: " a = 1", last: " b = 2" } }),
+ flavor,
+ });
+ const steps = prompt.slice(prompt.indexOf("## The plan"), prompt.indexOf("## Hard constraints"));
+ expect(steps).toContain("The span starts with");
+ expect(steps).not.toMatch(TOOLS);
+ expect(steps).not.toContain("@codebase");
+ }
+ });
+});
diff --git a/packages/ui/__tests__/refactoring/opportunity-prompt.test.ts b/packages/ui/__tests__/refactoring/opportunity-prompt.test.ts
index df1e09761..9d5d71b50 100644
--- a/packages/ui/__tests__/refactoring/opportunity-prompt.test.ts
+++ b/packages/ui/__tests__/refactoring/opportunity-prompt.test.ts
@@ -16,6 +16,10 @@ import type {
} from "@repowise-dev/types/refactoring";
import { buildRefactoringOpportunityPrompt } from "../../src/health/ai-prompt-builder";
+import {
+ LINE_RULE_TEXT,
+ SCRIPT_RULE_TEXT,
+} from "../../src/health/ai-prompts/refactoring-plan-steps";
function plan(overrides: Partial<RefactoringPlan> = {}): RefactoringPlan {
return {
@@ -243,3 +247,35 @@ describe("buildRefactoringOpportunityPrompt", () => {
expect(text).not.toMatch(/Keep these co-affected files consistent:.*src\/big\.py/);
});
});
+
+describe("Extract Method apply rules", () => {
+ const extract = (anchors?: Record<string, string>) =>
+ plan({
+ id: "refac2_extract",
+ refactoring_type: "extract_method",
+ plan: { span: { start: 400, end: 460 }, params: [], returns: [], ...(anchors ? { anchors } : {}) },
+ });
+
+ it("states neither rule when no step is an Extract Method", () => {
+ const prompt = buildRefactoringOpportunityPrompt({
+ opportunity: detail({ steps: detail().steps.slice(0, 1) }),
+ });
+ expect(prompt).not.toContain(SCRIPT_RULE_TEXT);
+ expect(prompt).not.toContain(LINE_RULE_TEXT);
+ });
+
+ it("says no script for an Extract Method step, and find-by-text only when anchored", () => {
+ const plain = buildRefactoringOpportunityPrompt({
+ opportunity: detail({ plans: [plan(), extract()] }),
+ });
+ expect(plain).toContain(SCRIPT_RULE_TEXT);
+ expect(plain).not.toContain(LINE_RULE_TEXT);
+ const anchored = buildRefactoringOpportunityPrompt({
+ opportunity: detail({
+ plans: [plan(), extract({ first: " a = 1", last: " b = 2", unique_in: "file" })],
+ }),
+ });
+ expect(anchored).toContain(SCRIPT_RULE_TEXT);
+ expect(anchored).toContain(LINE_RULE_TEXT);
+ });
+});
diff --git a/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts b/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts
index bede557ad..e84522f06 100644
--- a/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts
+++ b/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts
@@ -62,24 +62,74 @@ function extractHelperSteps(plan: RefactoringPlan): string {
].join("\n");
}
+/** How an Extract Method edit is made. Core's recipe says the same words
+ * (`recipe.SCRIPT_RULE`, `LINE_RULE`, `ELSEWHERE_NOTE`; a parity test holds them). */
+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.";
+
+interface SpanAnchors {
+ first: string;
+ last: string;
+ /** "function": the text also occurs elsewhere in the file. */
+ unique_in: "file" | "function";
+}
+
+/** The span's first and last lines as core serves them (`plan.anchors`), or
+ * null on a plan stored before them. Never computed here. */
+function spanAnchors(plan: RefactoringPlan): SpanAnchors | null {
+ const raw = ((plan.plan ?? {}) as Record<string, unknown>).anchors as
+ | Record<string, unknown>
+ | null
+ | undefined;
+ if (!raw || typeof raw.first !== "string" || typeof raw.last !== "string") return null;
+ return {
+ first: raw.first,
+ last: raw.last,
+ unique_in: raw.unique_in === "function" ? "function" : "file",
+ };
+}
+
+/** *text* fenced at column 0, so its indentation reads exactly as the file has it. */
+function fenced(text: string): string[] {
+ const ticks = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length));
+ const fence = "`".repeat(Math.max(3, ticks + 1));
+ return [fence, text, fence];
+}
+
function extractMethodSteps(plan: RefactoringPlan): string {
const em = extractMethodPlan(plan);
if (!em.span) return "Extract the indicated slice into a helper method.";
const params = em.params.length ? em.params.join(", ") : "(none)";
const returns = em.returns.length ? em.returns.join(", ") : "(nothing)";
const name = em.suggested_name ?? HELPER_NAME_PLACEHOLDER;
+ const anchors = spanAnchors(plan);
+ const lines = `${em.span.start}–${em.span.end}`;
const rendered = [
+ ...(anchors
+ ? [
+ "- **The span starts with:**",
+ ...fenced(anchors.first),
+ "- **The span ends with:**",
+ ...fenced(anchors.last),
+ ...(anchors.unique_in === "function" ? [`- ${ELSEWHERE_NOTE}`] : []),
+ ]
+ : []),
...(em.signature_text ? [`- **New helper:** \`${em.signature_text}\``] : []),
...(em.return_text ? [`- **End the helper with:** \`${em.return_text}\``] : []),
...(em.call_site
- ? [`- **Replace lines ${em.span.start}–${em.span.end} with:** \`${em.call_site.new_text}\``]
+ ? [`- **Replace ${anchors ? "the span" : `lines ${lines}`} with:** \`${em.call_site.new_text}\``]
: []),
...em.notes.map((note) => `- **Note:** ${note}`),
];
+ const what = anchors
+ ? `the span of \`${plan.target_symbol}\` that starts and ends with the lines shown (lines ${lines} when planned)`
+ : `lines ${lines} of \`${plan.target_symbol}\``;
return [
- `Extract lines ${em.span.start}–${em.span.end} of \`${plan.target_symbol}\` into \`${name}\`${
- em.suggested_name ? "" : " (name it for what the lines do)"
- }:`,
+ `Extract ${what} into \`${name}\`${em.suggested_name ? "" : " (name it for what the lines do)"}:`,
"",
...rendered,
`- **Parameters (in):** ${params}`,
@@ -92,6 +142,7 @@ function extractMethodSteps(plan: RefactoringPlan): string {
: []),
"",
"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.",
+ anchors ? `${SCRIPT_RULE_TEXT} ${LINE_RULE_TEXT}` : SCRIPT_RULE_TEXT,
].join("\n");
}
diff --git a/packages/ui/src/health/ai-prompts/refactoring-prompts.ts b/packages/ui/src/health/ai-prompts/refactoring-prompts.ts
index b51dc1539..9ac5f9e3e 100644
--- a/packages/ui/src/health/ai-prompts/refactoring-prompts.ts
+++ b/packages/ui/src/health/ai-prompts/refactoring-prompts.ts
@@ -9,8 +9,10 @@ import type {
import { planBlurb, typeMeta } from "../../refactoring/meta";
import { blastFiles } from "../../refactoring/types";
import {
+ LINE_RULE_TEXT,
planSourceLink,
refactoringPlanSteps,
+ SCRIPT_RULE_TEXT,
verifySubject,
} from "./refactoring-plan-steps";
import {
@@ -375,6 +377,15 @@ export function buildRefactoringOpportunityPrompt({
const meta = typeMeta(opportunity.lead_refactoring_type || "");
const others = opportunity.affected_files.filter((f) => f !== opportunity.file_path);
const anyRelocated = opportunity.steps.some((step) => Boolean(step.relocated_by));
+ // Extract Method's apply rules, only when a step is one; find-by-text only
+ // when its plan carries anchors.
+ const plans = new Map(opportunity.plans.map((plan) => [plan.id, plan]));
+ const extracts = opportunity.steps
+ .filter((step) => step.refactoring_type === "extract_method")
+ .map((step) => plans.get(step.plan_id));
+ const anchored = extracts.some(
+ (plan) => Boolean(((plan?.plan ?? {}) as Record<string, unknown>).anchors),
+ );
const constraintList = [
"Preserve behavior exactly — this is a refactoring, not a feature change. No public API or observable behavior should shift.",
@@ -383,6 +394,8 @@ export function buildRefactoringOpportunityPrompt({
? "Where a step says to locate its symbol again, do that before touching it: an earlier step moves it, so the recorded path and lines go stale mid-run."
: null,
"A step marked Judgment has an unproven obligation. Read the real code and decide before applying it; do not treat it like a mechanical one.",
+ extracts.length > 0 ? SCRIPT_RULE_TEXT : null,
+ anchored ? LINE_RULE_TEXT : null,
"Run the project's tests (and type-checker/linter) after the change; the suite must stay green.",
"If, after reading the real code, a step looks wrong or unsafe, stop and explain why instead of forcing it — the detection is static and can be a false positive.",
others.length > 0 ? `Keep these co-affected files consistent: ${codeList(others)}.` : null,
diff --git a/tests/fixtures/agent_prompts/golden.json b/tests/fixtures/agent_prompts/golden.json
index 239b5bc4e..c6709ca5c 100644
--- a/tests/fixtures/agent_prompts/golden.json
+++ b/tests/fixtures/agent_prompts/golden.json
@@ -59,10 +59,16 @@
},
"refactoring_plan": {
"extract_method_typed": {
- "generic": "You are a senior engineer in this repository. Repowise, a code-intelligence index, planned the refactoring below from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Read the code each step names and confirm it before you change it.\n## Extract Method (`acme/api`)\nExtract lines 61-78 of `Loader.load` into `_read_config`.\n- Plan: `refac4_aaaaaaaaaaaaaaaaaaaa`\n- Target: `src/loader.py:40-120` (`Loader.load`)\n## Before you edit\n- The guarding tests pass before the edit.\n- Decision \"Loaders stay sync-free\" governs this file; check it allows this change first.\n- Changed in 3 commits by ana in the 14 days before the last index; check nobody is mid-change.\n- Decision `dec_2` also governs this file; read it.\n## Steps, in order\n1. Move lines 61-78 of `Loader.load` into a new helper `_read_config` (a starting name; rename it if it collides) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - New helper: `async def _read_config(self, path: Path, strict) -> <type>:`\n - Replace lines 61-78 with: `config = await self._read_config(path, strict)`\n - Parameters (in): path, strict\n - Returns (out): config\n - Note: The return type is not named in the code.\n - Note: Fill each `<name>` / `<type>` placeholder from the code.\n## Verify\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py` (covers lines 61-78)\n- `tests/test_cli.py`\n2 of 3 guarding tests shown.\n\nRun:\n\n```\npytest tests/test_cli.py tests/test_loader.py\n```\n\n- Expect: `Loader.load` loses about 6 branches of cyclomatic complexity.\n- Expect: File health recovers about 1.25.\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not touch anything outside lines 61-78 and the call that replaces them.**\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step applied.\n2. What you named or introduced, and why.\n3. The Verify run, before and after, with its result.\n4. Any call sites or files you also had to change.",
- "claude-code": "You are Claude Code in this repository. Repowise, a code-intelligence index, planned the refactoring below from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Read each span with Read and Grep before editing, and track the steps with TodoWrite.\n## Extract Method (`acme/api`)\nExtract lines 61-78 of `Loader.load` into `_read_config`.\n- Plan: `refac4_aaaaaaaaaaaaaaaaaaaa`\n- Target: `src/loader.py:40-120` (`Loader.load`)\n## Before you edit\n- The guarding tests pass before the edit.\n- Decision \"Loaders stay sync-free\" governs this file; check it allows this change first.\n- Changed in 3 commits by ana in the 14 days before the last index; check nobody is mid-change.\n- Decision `dec_2` also governs this file; read it.\n## Steps, in order\n1. Move lines 61-78 of `Loader.load` into a new helper `_read_config` (a starting name; rename it if it collides) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - New helper: `async def _read_config(self, path: Path, strict) -> <type>:`\n - Replace lines 61-78 with: `config = await self._read_config(path, strict)`\n - Parameters (in): path, strict\n - Returns (out): config\n - Note: The return type is not named in the code.\n - Note: Fill each `<name>` / `<type>` placeholder from the code.\n## Verify\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py` (covers lines 61-78)\n- `tests/test_cli.py`\n2 of 3 guarding tests shown.\n\nRun:\n\n```\npytest tests/test_cli.py tests/test_loader.py\n```\n\n- Expect: `Loader.load` loses about 6 branches of cyclomatic complexity.\n- Expect: File health recovers about 1.25.\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not touch anything outside lines 61-78 and the call that replaces them.**\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step applied.\n2. What you named or introduced, and why.\n3. The Verify run, before and after, with its result.\n4. Any call sites or files you also had to change.",
- "claude-code-mcp": "You are Claude Code in this repository, which Repowise indexes and serves over MCP. Repowise planned the refactoring below from its static analysis. It does not edit code: the steps are a spec for you to apply. Use the MCP lookup under \"Look closer\" and `get_symbol` on each span before reading files by hand.\n## Extract Method (`acme/api`)\nExtract lines 61-78 of `Loader.load` into `_read_config`.\n- Plan: `refac4_aaaaaaaaaaaaaaaaaaaa`\n- Target: `src/loader.py:40-120` (`Loader.load`)\n## Before you edit\n- The guarding tests pass before the edit.\n- Decision \"Loaders stay sync-free\" governs this file; check it allows this change first.\n- Changed in 3 commits by ana in the 14 days before the last index; check nobody is mid-change.\n- Decision `dec_2` also governs this file; read it.\n## Steps, in order\n1. Move lines 61-78 of `Loader.load` into a new helper `_read_config` (a starting name; rename it if it collides) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - New helper: `async def _read_config(self, path: Path, strict) -> <type>:`\n - Replace lines 61-78 with: `config = await self._read_config(path, strict)`\n - Parameters (in): path, strict\n - Returns (out): config\n - Note: The return type is not named in the code.\n - Note: Fill each `<name>` / `<type>` placeholder from the code.\n## Verify\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py` (covers lines 61-78)\n- `tests/test_cli.py`\n2 of 3 guarding tests shown.\n\nRun:\n\n```\npytest tests/test_cli.py tests/test_loader.py\n```\n\n- Expect: `Loader.load` loses about 6 branches of cyclomatic complexity.\n- Expect: File health recovers about 1.25.\n## Look closer (Repowise MCP)\n`get_health(plan_id=\"refac4_aaaaaaaaaaaaaaaaaaaa\")`\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not touch anything outside lines 61-78 and the call that replaces them.**\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step applied.\n2. What you named or introduced, and why.\n3. The Verify run, before and after, with its result.\n4. Any call sites or files you also had to change.",
- "cursor": "Work in this repository. Repowise, a code-intelligence index, planned the refactoring below from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Open each span with @file and confirm it before editing.\n## Extract Method (`acme/api`)\nExtract lines 61-78 of `Loader.load` into `_read_config`.\n- Plan: `refac4_aaaaaaaaaaaaaaaaaaaa`\n- Target: `src/loader.py:40-120` (`Loader.load`)\n## Before you edit\n- The guarding tests pass before the edit.\n- Decision \"Loaders stay sync-free\" governs this file; check it allows this change first.\n- Changed in 3 commits by ana in the 14 days before the last index; check nobody is mid-change.\n- Decision `dec_2` also governs this file; read it.\n## Steps, in order\n1. Move lines 61-78 of `Loader.load` into a new helper `_read_config` (a starting name; rename it if it collides) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - New helper: `async def _read_config(self, path: Path, strict) -> <type>:`\n - Replace lines 61-78 with: `config = await self._read_config(path, strict)`\n - Parameters (in): path, strict\n - Returns (out): config\n - Note: The return type is not named in the code.\n - Note: Fill each `<name>` / `<type>` placeholder from the code.\n## Verify\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py` (covers lines 61-78)\n- `tests/test_cli.py`\n2 of 3 guarding tests shown.\n\nRun:\n\n```\npytest tests/test_cli.py tests/test_loader.py\n```\n\n- Expect: `Loader.load` loses about 6 branches of cyclomatic complexity.\n- Expect: File health recovers about 1.25.\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not touch anything outside lines 61-78 and the call that replaces them.**\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step applied.\n2. What you named or introduced, and why.\n3. The Verify run, before and after, with its result.\n4. Any call sites or files you also had to change."
+ "generic": "You are a senior engineer in this repository. Repowise, a code-intelligence index, planned the refactoring below from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Read the code each step names and confirm it before you change it.\n## Extract Method (`acme/api`)\nExtract lines 61-78 of `Loader.load` into `_read_config`.\n- Plan: `refac4_aaaaaaaaaaaaaaaaaaaa`\n- Target: `src/loader.py:40-120` (`Loader.load`)\n## Before you edit\n- The guarding tests pass before the edit.\n- Decision \"Loaders stay sync-free\" governs this file; check it allows this change first.\n- Changed in 3 commits by ana in the 14 days before the last index; check nobody is mid-change.\n- Decision `dec_2` also governs this file; read it.\n## Steps, in order\n1. Move lines 61-78 of `Loader.load` into a new helper `_read_config` (a starting name; rename it if it collides) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - New helper: `async def _read_config(self, path: Path, strict) -> <type>:`\n - Replace lines 61-78 with: `config = await self._read_config(path, strict)`\n - Parameters (in): path, strict\n - Returns (out): config\n - Note: The return type is not named in the code.\n - Note: Fill each `<name>` / `<type>` placeholder from the code.\n## Verify\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py` (covers lines 61-78)\n- `tests/test_cli.py`\n2 of 3 guarding tests shown.\n\nRun:\n\n```\npytest tests/test_cli.py tests/test_loader.py\n```\n\n- Expect: `Loader.load` loses about 6 branches of cyclomatic complexity.\n- Expect: File health recovers about 1.25.\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not touch anything outside lines 61-78 and the call that replaces them.**\n- **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.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step applied.\n2. What you named or introduced, and why.\n3. The Verify run, before and after, with its result.\n4. Any call sites or files you also had to change.",
+ "claude-code": "You are Claude Code in this repository. Repowise, a code-intelligence index, planned the refactoring below from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Read each span with Read and Grep before editing, and track the steps with TodoWrite.\n## Extract Method (`acme/api`)\nExtract lines 61-78 of `Loader.load` into `_read_config`.\n- Plan: `refac4_aaaaaaaaaaaaaaaaaaaa`\n- Target: `src/loader.py:40-120` (`Loader.load`)\n## Before you edit\n- The guarding tests pass before the edit.\n- Decision \"Loaders stay sync-free\" governs this file; check it allows this change first.\n- Changed in 3 commits by ana in the 14 days before the last index; check nobody is mid-change.\n- Decision `dec_2` also governs this file; read it.\n## Steps, in order\n1. Move lines 61-78 of `Loader.load` into a new helper `_read_config` (a starting name; rename it if it collides) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - New helper: `async def _read_config(self, path: Path, strict) -> <type>:`\n - Replace lines 61-78 with: `config = await self._read_config(path, strict)`\n - Parameters (in): path, strict\n - Returns (out): config\n - Note: The return type is not named in the code.\n - Note: Fill each `<name>` / `<type>` placeholder from the code.\n## Verify\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py` (covers lines 61-78)\n- `tests/test_cli.py`\n2 of 3 guarding tests shown.\n\nRun:\n\n```\npytest tests/test_cli.py tests/test_loader.py\n```\n\n- Expect: `Loader.load` loses about 6 branches of cyclomatic complexity.\n- Expect: File health recovers about 1.25.\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not touch anything outside lines 61-78 and the call that replaces them.**\n- **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.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step applied.\n2. What you named or introduced, and why.\n3. The Verify run, before and after, with its result.\n4. Any call sites or files you also had to change.",
+ "claude-code-mcp": "You are Claude Code in this repository, which Repowise indexes and serves over MCP. Repowise planned the refactoring below from its static analysis. It does not edit code: the steps are a spec for you to apply. Use the MCP lookup under \"Look closer\" and `get_symbol` on each span before reading files by hand.\n## Extract Method (`acme/api`)\nExtract lines 61-78 of `Loader.load` into `_read_config`.\n- Plan: `refac4_aaaaaaaaaaaaaaaaaaaa`\n- Target: `src/loader.py:40-120` (`Loader.load`)\n## Before you edit\n- The guarding tests pass before the edit.\n- Decision \"Loaders stay sync-free\" governs this file; check it allows this change first.\n- Changed in 3 commits by ana in the 14 days before the last index; check nobody is mid-change.\n- Decision `dec_2` also governs this file; read it.\n## Steps, in order\n1. Move lines 61-78 of `Loader.load` into a new helper `_read_config` (a starting name; rename it if it collides) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - New helper: `async def _read_config(self, path: Path, strict) -> <type>:`\n - Replace lines 61-78 with: `config = await self._read_config(path, strict)`\n - Parameters (in): path, strict\n - Returns (out): config\n - Note: The return type is not named in the code.\n - Note: Fill each `<name>` / `<type>` placeholder from the code.\n## Verify\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py` (covers lines 61-78)\n- `tests/test_cli.py`\n2 of 3 guarding tests shown.\n\nRun:\n\n```\npytest tests/test_cli.py tests/test_loader.py\n```\n\n- Expect: `Loader.load` loses about 6 branches of cyclomatic complexity.\n- Expect: File health recovers about 1.25.\n## Look closer (Repowise MCP)\n`get_health(plan_id=\"refac4_aaaaaaaaaaaaaaaaaaaa\")`\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not touch anything outside lines 61-78 and the call that replaces them.**\n- **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.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step applied.\n2. What you named or introduced, and why.\n3. The Verify run, before and after, with its result.\n4. Any call sites or files you also had to change.",
+ "cursor": "Work in this repository. Repowise, a code-intelligence index, planned the refactoring below from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Open each span with @file and confirm it before editing.\n## Extract Method (`acme/api`)\nExtract lines 61-78 of `Loader.load` into `_read_config`.\n- Plan: `refac4_aaaaaaaaaaaaaaaaaaaa`\n- Target: `src/loader.py:40-120` (`Loader.load`)\n## Before you edit\n- The guarding tests pass before the edit.\n- Decision \"Loaders stay sync-free\" governs this file; check it allows this change first.\n- Changed in 3 commits by ana in the 14 days before the last index; check nobody is mid-change.\n- Decision `dec_2` also governs this file; read it.\n## Steps, in order\n1. Move lines 61-78 of `Loader.load` into a new helper `_read_config` (a starting name; rename it if it collides) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - New helper: `async def _read_config(self, path: Path, strict) -> <type>:`\n - Replace lines 61-78 with: `config = await self._read_config(path, strict)`\n - Parameters (in): path, strict\n - Returns (out): config\n - Note: The return type is not named in the code.\n - Note: Fill each `<name>` / `<type>` placeholder from the code.\n## Verify\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py` (covers lines 61-78)\n- `tests/test_cli.py`\n2 of 3 guarding tests shown.\n\nRun:\n\n```\npytest tests/test_cli.py tests/test_loader.py\n```\n\n- Expect: `Loader.load` loses about 6 branches of cyclomatic complexity.\n- Expect: File health recovers about 1.25.\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not touch anything outside lines 61-78 and the call that replaces them.**\n- **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.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step applied.\n2. What you named or introduced, and why.\n3. The Verify run, before and after, with its result.\n4. Any call sites or files you also had to change."
+ },
+ "extract_method_staged_anchored": {
+ "generic": "You are a senior engineer in this repository. Repowise, a code-intelligence index, planned the refactoring below from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Read the code each step names and confirm it before you change it.\n## Extract Method\nSplit `build_report` into 2 helpers it calls in order (cyclomatic complexity 31 -> 19).\n- Plan: `refac4_iiiiiiiiiiiiiiiiiiii`\n- Target: `src/report.py:10-60` (`build_report`)\n## Steps, in order\n1. Stage 1 of 2: Move the span of `build_report` that starts and ends with the lines shown (lines 14-30 when planned) into a new helper `_sum_rows` (a starting name; rename it if it collides) in the same scope, and replace it with one call to it. (`src/report.py:14-30`)\n - The span starts with:\n```\n for row in rows:\n```\n - The span ends with:\n```\n totals[row.key] += row.amount\n```\n - New helper: `def _sum_rows(rows):`\n - End the helper with: `return totals`\n - Replace the span with: `totals = _sum_rows(rows)`\n - Parameters (in): rows\n - Returns (out): totals\n2. Stage 2 of 2: Move the span of `build_report` that starts and ends with the lines shown (lines 32-51 when planned) into a new helper `_format_totals` (a starting name; rename it if it collides) in the same scope, and replace it with one call to it. (`src/report.py:32-51`)\n - The span starts with:\n```\n if not totals:\n return None\n```\n - The span ends with:\n```\n out.append(f\"`{key}`: {value}\")\n```\n - New helper: `def _format_totals(totals):`\n - End the helper with: `return out`\n - Replace the span with: `out = _format_totals(totals)`\n - Parameters (in): totals\n - Returns (out): out\n## Verify\nThe tests that exercise the change pass; add one if none does.\n\n- Expect: `build_report` loses about 12 branches of cyclomatic complexity.\n- Expect: File health recovers about 0.90.\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not touch anything outside the lines the steps move (lines 14-51 when planned) and the calls that replace them (and the object the stages share, if any).**\n- **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.\n- **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.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step applied.\n2. What you named or introduced, and why.\n3. The Verify run, before and after, with its result.\n4. Any call sites or files you also had to change.",
+ "claude-code": "You are Claude Code in this repository. Repowise, a code-intelligence index, planned the refactoring below from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Read each span with Read and Grep before editing, and track the steps with TodoWrite.\n## Extract Method\nSplit `build_report` into 2 helpers it calls in order (cyclomatic complexity 31 -> 19).\n- Plan: `refac4_iiiiiiiiiiiiiiiiiiii`\n- Target: `src/report.py:10-60` (`build_report`)\n## Steps, in order\n1. Stage 1 of 2: Move the span of `build_report` that starts and ends with the lines shown (lines 14-30 when planned) into a new helper `_sum_rows` (a starting name; rename it if it collides) in the same scope, and replace it with one call to it. (`src/report.py:14-30`)\n - The span starts with:\n```\n for row in rows:\n```\n - The span ends with:\n```\n totals[row.key] += row.amount\n```\n - New helper: `def _sum_rows(rows):`\n - End the helper with: `return totals`\n - Replace the span with: `totals = _sum_rows(rows)`\n - Parameters (in): rows\n - Returns (out): totals\n2. Stage 2 of 2: Move the span of `build_report` that starts and ends with the lines shown (lines 32-51 when planned) into a new helper `_format_totals` (a starting name; rename it if it collides) in the same scope, and replace it with one call to it. (`src/report.py:32-51`)\n - The span starts with:\n```\n if not totals:\n return None\n```\n - The span ends with:\n```\n out.append(f\"`{key}`: {value}\")\n```\n - New helper: `def _format_totals(totals):`\n - End the helper with: `return out`\n - Replace the span with: `out = _format_totals(totals)`\n - Parameters (in): totals\n - Returns (out): out\n## Verify\nThe tests that exercise the change pass; add one if none does.\n\n- Expect: `build_report` loses about 12 branches of cyclomatic complexity.\n- Expect: File health recovers about 0.90.\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not touch anything outside the lines the steps move (lines 14-51 when planned) and the calls that replace them (and the object the stages share, if any).**\n- **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.\n- **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.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step applied.\n2. What you named or introduced, and why.\n3. The Verify run, before and after, with its result.\n4. Any call sites or files you also had to change.",
+ "claude-code-mcp": "You are Claude Code in this repository, which Repowise indexes and serves over MCP. Repowise planned the refactoring below from its static analysis. It does not edit code: the steps are a spec for you to apply. Use the MCP lookup under \"Look closer\" and `get_symbol` on each span before reading files by hand.\n## Extract Method\nSplit `build_report` into 2 helpers it calls in order (cyclomatic complexity 31 -> 19).\n- Plan: `refac4_iiiiiiiiiiiiiiiiiiii`\n- Target: `src/report.py:10-60` (`build_report`)\n## Steps, in order\n1. Stage 1 of 2: Move the span of `build_report` that starts and ends with the lines shown (lines 14-30 when planned) into a new helper `_sum_rows` (a starting name; rename it if it collides) in the same scope, and replace it with one call to it. (`src/report.py:14-30`)\n - The span starts with:\n```\n for row in rows:\n```\n - The span ends with:\n```\n totals[row.key] += row.amount\n```\n - New helper: `def _sum_rows(rows):`\n - End the helper with: `return totals`\n - Replace the span with: `totals = _sum_rows(rows)`\n - Parameters (in): rows\n - Returns (out): totals\n2. Stage 2 of 2: Move the span of `build_report` that starts and ends with the lines shown (lines 32-51 when planned) into a new helper `_format_totals` (a starting name; rename it if it collides) in the same scope, and replace it with one call to it. (`src/report.py:32-51`)\n - The span starts with:\n```\n if not totals:\n return None\n```\n - The span ends with:\n```\n out.append(f\"`{key}`: {value}\")\n```\n - New helper: `def _format_totals(totals):`\n - End the helper with: `return out`\n - Replace the span with: `out = _format_totals(totals)`\n - Parameters (in): totals\n - Returns (out): out\n## Verify\nThe tests that exercise the change pass; add one if none does.\n\n- Expect: `build_report` loses about 12 branches of cyclomatic complexity.\n- Expect: File health recovers about 0.90.\n## Look closer (Repowise MCP)\n`get_health(plan_id=\"refac4_iiiiiiiiiiiiiiiiiiii\")`\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not touch anything outside the lines the steps move (lines 14-51 when planned) and the calls that replace them (and the object the stages share, if any).**\n- **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.\n- **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.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step applied.\n2. What you named or introduced, and why.\n3. The Verify run, before and after, with its result.\n4. Any call sites or files you also had to change.",
+ "cursor": "Work in this repository. Repowise, a code-intelligence index, planned the refactoring below from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Open each span with @file and confirm it before editing.\n## Extract Method\nSplit `build_report` into 2 helpers it calls in order (cyclomatic complexity 31 -> 19).\n- Plan: `refac4_iiiiiiiiiiiiiiiiiiii`\n- Target: `src/report.py:10-60` (`build_report`)\n## Steps, in order\n1. Stage 1 of 2: Move the span of `build_report` that starts and ends with the lines shown (lines 14-30 when planned) into a new helper `_sum_rows` (a starting name; rename it if it collides) in the same scope, and replace it with one call to it. (`src/report.py:14-30`)\n - The span starts with:\n```\n for row in rows:\n```\n - The span ends with:\n```\n totals[row.key] += row.amount\n```\n - New helper: `def _sum_rows(rows):`\n - End the helper with: `return totals`\n - Replace the span with: `totals = _sum_rows(rows)`\n - Parameters (in): rows\n - Returns (out): totals\n2. Stage 2 of 2: Move the span of `build_report` that starts and ends with the lines shown (lines 32-51 when planned) into a new helper `_format_totals` (a starting name; rename it if it collides) in the same scope, and replace it with one call to it. (`src/report.py:32-51`)\n - The span starts with:\n```\n if not totals:\n return None\n```\n - The span ends with:\n```\n out.append(f\"`{key}`: {value}\")\n```\n - New helper: `def _format_totals(totals):`\n - End the helper with: `return out`\n - Replace the span with: `out = _format_totals(totals)`\n - Parameters (in): totals\n - Returns (out): out\n## Verify\nThe tests that exercise the change pass; add one if none does.\n\n- Expect: `build_report` loses about 12 branches of cyclomatic complexity.\n- Expect: File health recovers about 0.90.\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not touch anything outside the lines the steps move (lines 14-51 when planned) and the calls that replace them (and the object the stages share, if any).**\n- **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.\n- **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.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step applied.\n2. What you named or introduced, and why.\n3. The Verify run, before and after, with its result.\n4. Any call sites or files you also had to change."
},
"performance_fix_steps": {
"generic": "You are a senior engineer in this repository. Repowise, a code-intelligence index, planned the refactoring below from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Read the code each step names and confirm it before you change it.\n## Performance\nBatch the repeated per-item calls in `load_rows`.\n- Plan: `refac4_bbbbbbbbbbbbbbbbbbbb`\n- Target: `src/rows.py:12` (`load_rows`)\n## Before you edit\n- No test reaches this; add a characterization test for `load_rows` before the edit.\n## Steps, in order\n1. Add a form of fetch_row that takes every key at once. (`src/db.py`)\n - Judgment step.\n2. Collect the keys before the loop and replace the per-key fetch_row call with one batched call in `load_rows`. (`src/rows.py:12`)\n - Judgment step.\n - Verify this step: `pytest tests/test_rows.py`\n## Verify\nNo guarding test was found; the test added before the edit passes after it.\n\n- Expect: The repeated work no longer runs once per item at 2 call sites.\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not change the results or errors the batched or reordered calls produce.**\n- **Do not apply a judgment step without reading the code it names first.**\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step applied.\n2. What you named or introduced, and why.\n3. The Verify run, before and after, with its result.\n4. Any call sites or files you also had to change.",
@@ -90,7 +96,8 @@
}
},
"refactoring_plan_spec": {
- "extract_method_typed": "## Extract Method\nExtract lines 61-78 of `Loader.load` into `_read_config`.\n- Plan: `refac4_aaaaaaaaaaaaaaaaaaaa`\n- Target: `src/loader.py:40-120` (`Loader.load`)\n## Before you edit\n- The guarding tests pass before the edit.\n- Decision \"Loaders stay sync-free\" governs this file; check it allows this change first.\n- Changed in 3 commits by ana in the 14 days before the last index; check nobody is mid-change.\n- Decision `dec_2` also governs this file; read it.\n## Steps, in order\n1. Move lines 61-78 of `Loader.load` into a new helper `_read_config` (a starting name; rename it if it collides) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - New helper: `async def _read_config(self, path: Path, strict) -> <type>:`\n - Replace lines 61-78 with: `config = await self._read_config(path, strict)`\n - Parameters (in): path, strict\n - Returns (out): config\n - Note: The return type is not named in the code.\n - Note: Fill each `<name>` / `<type>` placeholder from the code.\n## Verify\nThe tests that guard this change, the most direct first:\n\n- `tests/test_loader.py` (covers lines 61-78)\n- `tests/test_cli.py`\n2 of 3 guarding tests shown.\n\n- Expect: `Loader.load` loses about 6 branches of cyclomatic complexity.\n- Expect: File health recovers about 1.25.\n## Blast radius\n- scope: local\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not touch anything outside lines 61-78 and the call that replaces them.**",
+ "extract_method_typed": "## Extract Method\nExtract lines 61-78 of `Loader.load` into `_read_config`.\n- Plan: `refac4_aaaaaaaaaaaaaaaaaaaa`\n- Target: `src/loader.py:40-120` (`Loader.load`)\n## Before you edit\n- The guarding tests pass before the edit.\n- Decision \"Loaders stay sync-free\" governs this file; check it allows this change first.\n- Changed in 3 commits by ana in the 14 days before the last index; check nobody is mid-change.\n- Decision `dec_2` also governs this file; read it.\n## Steps, in order\n1. Move lines 61-78 of `Loader.load` into a new helper `_read_config` (a starting name; rename it if it collides) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - New helper: `async def _read_config(self, path: Path, strict) -> <type>:`\n - Replace lines 61-78 with: `config = await self._read_config(path, strict)`\n - Parameters (in): path, strict\n - Returns (out): config\n - Note: The return type is not named in the code.\n - Note: Fill each `<name>` / `<type>` placeholder from the code.\n## Verify\nThe tests that guard this change, the most direct first:\n\n- `tests/test_loader.py` (covers lines 61-78)\n- `tests/test_cli.py`\n2 of 3 guarding tests shown.\n\n- Expect: `Loader.load` loses about 6 branches of cyclomatic complexity.\n- Expect: File health recovers about 1.25.\n## Blast radius\n- scope: local\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not touch anything outside lines 61-78 and the call that replaces them.**\n- **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.",
+ "extract_method_staged_anchored": "## Extract Method\nSplit `build_report` into 2 helpers it calls in order (cyclomatic complexity 31 -> 19).\n- Plan: `refac4_iiiiiiiiiiiiiiiiiiii`\n- Target: `src/report.py:10-60` (`build_report`)\n## Steps, in order\n1. Stage 1 of 2: Move the span of `build_report` that starts and ends with the lines shown (lines 14-30 when planned) into a new helper `_sum_rows` (a starting name; rename it if it collides) in the same scope, and replace it with one call to it. (`src/report.py:14-30`)\n - The span starts with:\n```\n for row in rows:\n```\n - The span ends with:\n```\n totals[row.key] += row.amount\n```\n - New helper: `def _sum_rows(rows):`\n - End the helper with: `return totals`\n - Replace the span with: `totals = _sum_rows(rows)`\n - Parameters (in): rows\n - Returns (out): totals\n2. Stage 2 of 2: Move the span of `build_report` that starts and ends with the lines shown (lines 32-51 when planned) into a new helper `_format_totals` (a starting name; rename it if it collides) in the same scope, and replace it with one call to it. (`src/report.py:32-51`)\n - The span starts with:\n```\n if not totals:\n return None\n```\n - The span ends with:\n```\n out.append(f\"`{key}`: {value}\")\n```\n - New helper: `def _format_totals(totals):`\n - End the helper with: `return out`\n - Replace the span with: `out = _format_totals(totals)`\n - Parameters (in): totals\n - Returns (out): out\n## Verify\nThe tests that exercise the change pass; add one if none does.\n\n- Expect: `build_report` loses about 12 branches of cyclomatic complexity.\n- Expect: File health recovers about 0.90.\n## Blast radius\n- scope: local\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not touch anything outside the lines the steps move (lines 14-51 when planned) and the calls that replace them (and the object the stages share, if any).**\n- **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.\n- **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.",
"performance_fix_steps": "## Performance\nBatch the repeated per-item calls in `load_rows`.\n- Plan: `refac4_bbbbbbbbbbbbbbbbbbbb`\n- Target: `src/rows.py:12` (`load_rows`)\n## Before you edit\n- No test reaches this; add a characterization test for `load_rows` before the edit.\n## Steps, in order\n1. Add a form of fetch_row that takes every key at once. (`src/db.py`)\n - Judgment step.\n2. Collect the keys before the loop and replace the per-key fetch_row call with one batched call in `load_rows`. (`src/rows.py:12`)\n - Judgment step.\n - Verify this step: `pytest tests/test_rows.py`\n## Verify\nNo guarding test was found; the test added before the edit passes after it.\n\n- Expect: The repeated work no longer runs once per item at 2 call sites.\n## Blast radius\n- call sites: 2\n- file count: 1\n- files: src/rows.py\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not change the results or errors the batched or reordered calls produce.**\n- **Do not apply a judgment step without reading the code it names first.**",
"split_file_older_row": "## Split File\nSplit `pkg/big.py`: move 2 groups of symbols into their own files.\n- Plan: `refac4_cccccccccccccccccccc`\n- Target: `pkg/big.py`\n## Before you edit\n- Risks and governing decisions were not checked for this plan.\n## Steps, in order\n1. Move `parse_a`, `parse_b` to `pkg/parsing.py` (a starting name; follow the repo's convention). (`pkg/parsing.py`)\n2. Move `render` to a new file (part 2) (a starting name; follow the repo's convention).\n3. Leave `Config` in `pkg/big.py`: more than one group uses them. (`pkg/big.py`)\n4. Keep `pkg/big.py` importable: re-export the moved symbols, or update every importer. (`pkg/big.py`)\n## Verify\nThe tests that exercise the change pass; add one if none does.\n\n- Expect: No resulting file is near the original's 900 lines.\n## Blast radius\n- dependent count: 4\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not put one symbol in two files.**",
"break_cycle_advisory": "## Break Cycle\nBreak the 2-file import cycle by cutting 1 import.\n- Plan: `refac4_gggggggggggggggggggg`\n- Target: `pkg/a.py`\n## Advisory: one way to cut the cycle\n- Remove the import of `pkg/b.py`: invert the dependency or move what both need into a module neither imports. A function-local import only if it really breaks the cycle. (`pkg/a.py`)\n## Verify\nThe tests that exercise the change pass; add one if none does.\n\n- Expect: The 2-file import cycle is gone.\n## Blast radius\n- file count: 2\n- files: pkg/a.py, pkg/b.py\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not merge the files in the cycle.**",
@@ -98,10 +105,10 @@
},
"refactoring_opportunity": {
"two_steps_one_relocated": {
- "generic": "You are a senior engineer in this repository. Repowise, a code-intelligence index, composed the ordered refactoring steps below for one file from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Read the code each step names and confirm it before you change it.\n## Extract Method in `src/loader.py` (`acme/api`)\n- Opportunity: `refop4_dddddddddddddddddddd`\n- File: `src/loader.py`\n- Leading cause: complex method.\n- 2 steps: 1 mechanical, 1 judgment.\n- Recovers ~2.50 of health score if applied.\n- Effort: M bucket. Detector confidence: high.\n- No dominant problem was recorded for this file, so whether these steps address it is unknown.\n## Steps, in order\nA step carrying `relocated_by` names a symbol an earlier step moves.\n\n1. **Extract Method** at `src/loader.py:40-120` (`Loader.load`)\n - Step id: `refac4_aaaaaaaaaaaaaaaaaaaa`\n - Mechanical: dataflow proved local extraction.\n - Move lines 61-78 of `Loader.load` into a new helper `<name>` (name it for what the lines do) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - Parameters (in): path\n - Returns (out): (nothing)\n\n2. **Move Method** at `src/loader.py:130` (`Loader.parse`)\n - Step id: `refac4_eeeeeeeeeeeeeeeeeeee`\n - Judgment. Not established: call sites resolved.\n - **Locate it again first.** Step `refac4_aaaaaaaaaaaaaaaaaaaa` moves this symbol, so the path and lines above are where it was, not where it will be when you get here.\n - This step's plan was not in this payload; ask for it by id: `refac4_eeeeeeeeeeeeeeeeeeee`.\n## Evidence behind the diagnosis\nSupporting observations, not extra work.\n- Extract Helper `loader.py:10-20`: duplicated lines: 11; occurrence count: 2\n1 of 3 shown.\n## Verify\n### For `Loader.load`\n\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py`\n\nRun:\n\n```\npytest tests/test_loader.py\n```\n\n### For `Loader.parse`\n\nNo guarding test was found; the test added before the edit passes after it.\n## Hard constraints\n- **Apply the steps in the order given.** It is dependency-safe; reordering it is not.\n- **Read a judgment step's code before applying it.** Its obligation is unproven.\n- **Keep behaviour.** Run the tests (and type-checker / linter) before and after.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step above applied in order.\n2. Per step: whether you applied it, and for anything you skipped, the reason.\n3. The Verify run, before and after, with its result.\n4. The opportunity id `refop4_dddddddddddddddddddd`, so the work can be matched back to the record.\n## This opportunity's id\n`refop4_dddddddddddddddddddd`\nQuote it when you report back.",
- "claude-code": "You are Claude Code in this repository. Repowise, a code-intelligence index, composed the ordered refactoring steps below for one file from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Read each span with Read and Grep before editing, and track the steps with TodoWrite.\n## Extract Method in `src/loader.py` (`acme/api`)\n- Opportunity: `refop4_dddddddddddddddddddd`\n- File: `src/loader.py`\n- Leading cause: complex method.\n- 2 steps: 1 mechanical, 1 judgment.\n- Recovers ~2.50 of health score if applied.\n- Effort: M bucket. Detector confidence: high.\n- No dominant problem was recorded for this file, so whether these steps address it is unknown.\n## Steps, in order\nA step carrying `relocated_by` names a symbol an earlier step moves.\n\n1. **Extract Method** at `src/loader.py:40-120` (`Loader.load`)\n - Step id: `refac4_aaaaaaaaaaaaaaaaaaaa`\n - Mechanical: dataflow proved local extraction.\n - Move lines 61-78 of `Loader.load` into a new helper `<name>` (name it for what the lines do) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - Parameters (in): path\n - Returns (out): (nothing)\n\n2. **Move Method** at `src/loader.py:130` (`Loader.parse`)\n - Step id: `refac4_eeeeeeeeeeeeeeeeeeee`\n - Judgment. Not established: call sites resolved.\n - **Locate it again first.** Step `refac4_aaaaaaaaaaaaaaaaaaaa` moves this symbol, so the path and lines above are where it was, not where it will be when you get here.\n - This step's plan was not in this payload; ask for it by id: `refac4_eeeeeeeeeeeeeeeeeeee`.\n## Evidence behind the diagnosis\nSupporting observations, not extra work.\n- Extract Helper `loader.py:10-20`: duplicated lines: 11; occurrence count: 2\n1 of 3 shown.\n## Verify\n### For `Loader.load`\n\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py`\n\nRun:\n\n```\npytest tests/test_loader.py\n```\n\n### For `Loader.parse`\n\nNo guarding test was found; the test added before the edit passes after it.\n## Hard constraints\n- **Apply the steps in the order given.** It is dependency-safe; reordering it is not.\n- **Read a judgment step's code before applying it.** Its obligation is unproven.\n- **Keep behaviour.** Run the tests (and type-checker / linter) before and after.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step above applied in order.\n2. Per step: whether you applied it, and for anything you skipped, the reason.\n3. The Verify run, before and after, with its result.\n4. The opportunity id `refop4_dddddddddddddddddddd`, so the work can be matched back to the record.\n## This opportunity's id\n`refop4_dddddddddddddddddddd`\nQuote it when you report back.",
- "claude-code-mcp": "You are Claude Code in this repository, which Repowise indexes and serves over MCP. Repowise composed the ordered refactoring steps below for one file from its static analysis. It does not edit code: the steps are a spec for you to apply. Pull the record with the call at the end and `get_symbol` each span before reading files by hand.\n## Extract Method in `src/loader.py` (`acme/api`)\n- Opportunity: `refop4_dddddddddddddddddddd`\n- File: `src/loader.py`\n- Leading cause: complex method.\n- 2 steps: 1 mechanical, 1 judgment.\n- Recovers ~2.50 of health score if applied.\n- Effort: M bucket. Detector confidence: high.\n- No dominant problem was recorded for this file, so whether these steps address it is unknown.\n## Steps, in order\nA step carrying `relocated_by` names a symbol an earlier step moves.\n\n1. **Extract Method** at `src/loader.py:40-120` (`Loader.load`)\n - Step id: `refac4_aaaaaaaaaaaaaaaaaaaa`\n - Mechanical: dataflow proved local extraction.\n - Move lines 61-78 of `Loader.load` into a new helper `<name>` (name it for what the lines do) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - Parameters (in): path\n - Returns (out): (nothing)\n\n2. **Move Method** at `src/loader.py:130` (`Loader.parse`)\n - Step id: `refac4_eeeeeeeeeeeeeeeeeeee`\n - Judgment. Not established: call sites resolved.\n - **Locate it again first.** Step `refac4_aaaaaaaaaaaaaaaaaaaa` moves this symbol, so the path and lines above are where it was, not where it will be when you get here.\n - This step's plan was not in this payload; ask for it by id: `refac4_eeeeeeeeeeeeeeeeeeee`.\n## Evidence behind the diagnosis\nSupporting observations, not extra work.\n- Extract Helper `loader.py:10-20`: duplicated lines: 11; occurrence count: 2\n1 of 3 shown.\n## Verify\n### For `Loader.load`\n\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py`\n\nRun:\n\n```\npytest tests/test_loader.py\n```\n\n### For `Loader.parse`\n\nNo guarding test was found; the test added before the edit passes after it.\n## Hard constraints\n- **Apply the steps in the order given.** It is dependency-safe; reordering it is not.\n- **Read a judgment step's code before applying it.** Its obligation is unproven.\n- **Keep behaviour.** Run the tests (and type-checker / linter) before and after.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step above applied in order.\n2. Per step: whether you applied it, and for anything you skipped, the reason.\n3. The Verify run, before and after, with its result.\n4. The opportunity id `refop4_dddddddddddddddddddd`, so the work can be matched back to the record.\n## Pull this record yourself\n`get_health(opportunity_id=\"refop4_dddddddddddddddddddd\")`\nIt returns this opportunity from the index: every ordered step with its plan, the validation profiles and the evidence. Call it before you start; the steps above are a snapshot.",
- "cursor": "Work in this repository. Repowise, a code-intelligence index, composed the ordered refactoring steps below for one file from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Open each span with @file and confirm it before editing.\n## Extract Method in `src/loader.py` (`acme/api`)\n- Opportunity: `refop4_dddddddddddddddddddd`\n- File: `src/loader.py`\n- Leading cause: complex method.\n- 2 steps: 1 mechanical, 1 judgment.\n- Recovers ~2.50 of health score if applied.\n- Effort: M bucket. Detector confidence: high.\n- No dominant problem was recorded for this file, so whether these steps address it is unknown.\n## Steps, in order\nA step carrying `relocated_by` names a symbol an earlier step moves.\n\n1. **Extract Method** at `src/loader.py:40-120` (`Loader.load`)\n - Step id: `refac4_aaaaaaaaaaaaaaaaaaaa`\n - Mechanical: dataflow proved local extraction.\n - Move lines 61-78 of `Loader.load` into a new helper `<name>` (name it for what the lines do) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - Parameters (in): path\n - Returns (out): (nothing)\n\n2. **Move Method** at `src/loader.py:130` (`Loader.parse`)\n - Step id: `refac4_eeeeeeeeeeeeeeeeeeee`\n - Judgment. Not established: call sites resolved.\n - **Locate it again first.** Step `refac4_aaaaaaaaaaaaaaaaaaaa` moves this symbol, so the path and lines above are where it was, not where it will be when you get here.\n - This step's plan was not in this payload; ask for it by id: `refac4_eeeeeeeeeeeeeeeeeeee`.\n## Evidence behind the diagnosis\nSupporting observations, not extra work.\n- Extract Helper `loader.py:10-20`: duplicated lines: 11; occurrence count: 2\n1 of 3 shown.\n## Verify\n### For `Loader.load`\n\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py`\n\nRun:\n\n```\npytest tests/test_loader.py\n```\n\n### For `Loader.parse`\n\nNo guarding test was found; the test added before the edit passes after it.\n## Hard constraints\n- **Apply the steps in the order given.** It is dependency-safe; reordering it is not.\n- **Read a judgment step's code before applying it.** Its obligation is unproven.\n- **Keep behaviour.** Run the tests (and type-checker / linter) before and after.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step above applied in order.\n2. Per step: whether you applied it, and for anything you skipped, the reason.\n3. The Verify run, before and after, with its result.\n4. The opportunity id `refop4_dddddddddddddddddddd`, so the work can be matched back to the record.\n## This opportunity's id\n`refop4_dddddddddddddddddddd`\nQuote it when you report back."
+ "generic": "You are a senior engineer in this repository. Repowise, a code-intelligence index, composed the ordered refactoring steps below for one file from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Read the code each step names and confirm it before you change it.\n## Extract Method in `src/loader.py` (`acme/api`)\n- Opportunity: `refop4_dddddddddddddddddddd`\n- File: `src/loader.py`\n- Leading cause: complex method.\n- 2 steps: 1 mechanical, 1 judgment.\n- Recovers ~2.50 of health score if applied.\n- Effort: M bucket. Detector confidence: high.\n- No dominant problem was recorded for this file, so whether these steps address it is unknown.\n## Steps, in order\nA step carrying `relocated_by` names a symbol an earlier step moves.\n\n1. **Extract Method** at `src/loader.py:40-120` (`Loader.load`)\n - Step id: `refac4_aaaaaaaaaaaaaaaaaaaa`\n - Mechanical: dataflow proved local extraction.\n - Move lines 61-78 of `Loader.load` into a new helper `<name>` (name it for what the lines do) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - Parameters (in): path\n - Returns (out): (nothing)\n\n2. **Move Method** at `src/loader.py:130` (`Loader.parse`)\n - Step id: `refac4_eeeeeeeeeeeeeeeeeeee`\n - Judgment. Not established: call sites resolved.\n - **Locate it again first.** Step `refac4_aaaaaaaaaaaaaaaaaaaa` moves this symbol, so the path and lines above are where it was, not where it will be when you get here.\n - This step's plan was not in this payload; ask for it by id: `refac4_eeeeeeeeeeeeeeeeeeee`.\n## Evidence behind the diagnosis\nSupporting observations, not extra work.\n- Extract Helper `loader.py:10-20`: duplicated lines: 11; occurrence count: 2\n1 of 3 shown.\n## Verify\n### For `Loader.load`\n\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py`\n\nRun:\n\n```\npytest tests/test_loader.py\n```\n\n### For `Loader.parse`\n\nNo guarding test was found; the test added before the edit passes after it.\n## Hard constraints\n- **Apply the steps in the order given.** It is dependency-safe; reordering it is not.\n- **Read a judgment step's code before applying it.** Its obligation is unproven.\n- **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.\n- **Keep behaviour.** Run the tests (and type-checker / linter) before and after.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step above applied in order.\n2. Per step: whether you applied it, and for anything you skipped, the reason.\n3. The Verify run, before and after, with its result.\n4. The opportunity id `refop4_dddddddddddddddddddd`, so the work can be matched back to the record.\n## This opportunity's id\n`refop4_dddddddddddddddddddd`\nQuote it when you report back.",
+ "claude-code": "You are Claude Code in this repository. Repowise, a code-intelligence index, composed the ordered refactoring steps below for one file from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Read each span with Read and Grep before editing, and track the steps with TodoWrite.\n## Extract Method in `src/loader.py` (`acme/api`)\n- Opportunity: `refop4_dddddddddddddddddddd`\n- File: `src/loader.py`\n- Leading cause: complex method.\n- 2 steps: 1 mechanical, 1 judgment.\n- Recovers ~2.50 of health score if applied.\n- Effort: M bucket. Detector confidence: high.\n- No dominant problem was recorded for this file, so whether these steps address it is unknown.\n## Steps, in order\nA step carrying `relocated_by` names a symbol an earlier step moves.\n\n1. **Extract Method** at `src/loader.py:40-120` (`Loader.load`)\n - Step id: `refac4_aaaaaaaaaaaaaaaaaaaa`\n - Mechanical: dataflow proved local extraction.\n - Move lines 61-78 of `Loader.load` into a new helper `<name>` (name it for what the lines do) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - Parameters (in): path\n - Returns (out): (nothing)\n\n2. **Move Method** at `src/loader.py:130` (`Loader.parse`)\n - Step id: `refac4_eeeeeeeeeeeeeeeeeeee`\n - Judgment. Not established: call sites resolved.\n - **Locate it again first.** Step `refac4_aaaaaaaaaaaaaaaaaaaa` moves this symbol, so the path and lines above are where it was, not where it will be when you get here.\n - This step's plan was not in this payload; ask for it by id: `refac4_eeeeeeeeeeeeeeeeeeee`.\n## Evidence behind the diagnosis\nSupporting observations, not extra work.\n- Extract Helper `loader.py:10-20`: duplicated lines: 11; occurrence count: 2\n1 of 3 shown.\n## Verify\n### For `Loader.load`\n\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py`\n\nRun:\n\n```\npytest tests/test_loader.py\n```\n\n### For `Loader.parse`\n\nNo guarding test was found; the test added before the edit passes after it.\n## Hard constraints\n- **Apply the steps in the order given.** It is dependency-safe; reordering it is not.\n- **Read a judgment step's code before applying it.** Its obligation is unproven.\n- **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.\n- **Keep behaviour.** Run the tests (and type-checker / linter) before and after.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step above applied in order.\n2. Per step: whether you applied it, and for anything you skipped, the reason.\n3. The Verify run, before and after, with its result.\n4. The opportunity id `refop4_dddddddddddddddddddd`, so the work can be matched back to the record.\n## This opportunity's id\n`refop4_dddddddddddddddddddd`\nQuote it when you report back.",
+ "claude-code-mcp": "You are Claude Code in this repository, which Repowise indexes and serves over MCP. Repowise composed the ordered refactoring steps below for one file from its static analysis. It does not edit code: the steps are a spec for you to apply. Pull the record with the call at the end and `get_symbol` each span before reading files by hand.\n## Extract Method in `src/loader.py` (`acme/api`)\n- Opportunity: `refop4_dddddddddddddddddddd`\n- File: `src/loader.py`\n- Leading cause: complex method.\n- 2 steps: 1 mechanical, 1 judgment.\n- Recovers ~2.50 of health score if applied.\n- Effort: M bucket. Detector confidence: high.\n- No dominant problem was recorded for this file, so whether these steps address it is unknown.\n## Steps, in order\nA step carrying `relocated_by` names a symbol an earlier step moves.\n\n1. **Extract Method** at `src/loader.py:40-120` (`Loader.load`)\n - Step id: `refac4_aaaaaaaaaaaaaaaaaaaa`\n - Mechanical: dataflow proved local extraction.\n - Move lines 61-78 of `Loader.load` into a new helper `<name>` (name it for what the lines do) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - Parameters (in): path\n - Returns (out): (nothing)\n\n2. **Move Method** at `src/loader.py:130` (`Loader.parse`)\n - Step id: `refac4_eeeeeeeeeeeeeeeeeeee`\n - Judgment. Not established: call sites resolved.\n - **Locate it again first.** Step `refac4_aaaaaaaaaaaaaaaaaaaa` moves this symbol, so the path and lines above are where it was, not where it will be when you get here.\n - This step's plan was not in this payload; ask for it by id: `refac4_eeeeeeeeeeeeeeeeeeee`.\n## Evidence behind the diagnosis\nSupporting observations, not extra work.\n- Extract Helper `loader.py:10-20`: duplicated lines: 11; occurrence count: 2\n1 of 3 shown.\n## Verify\n### For `Loader.load`\n\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py`\n\nRun:\n\n```\npytest tests/test_loader.py\n```\n\n### For `Loader.parse`\n\nNo guarding test was found; the test added before the edit passes after it.\n## Hard constraints\n- **Apply the steps in the order given.** It is dependency-safe; reordering it is not.\n- **Read a judgment step's code before applying it.** Its obligation is unproven.\n- **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.\n- **Keep behaviour.** Run the tests (and type-checker / linter) before and after.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step above applied in order.\n2. Per step: whether you applied it, and for anything you skipped, the reason.\n3. The Verify run, before and after, with its result.\n4. The opportunity id `refop4_dddddddddddddddddddd`, so the work can be matched back to the record.\n## Pull this record yourself\n`get_health(opportunity_id=\"refop4_dddddddddddddddddddd\")`\nIt returns this opportunity from the index: every ordered step with its plan, the validation profiles and the evidence. Call it before you start; the steps above are a snapshot.",
+ "cursor": "Work in this repository. Repowise, a code-intelligence index, composed the ordered refactoring steps below for one file from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Open each span with @file and confirm it before editing.\n## Extract Method in `src/loader.py` (`acme/api`)\n- Opportunity: `refop4_dddddddddddddddddddd`\n- File: `src/loader.py`\n- Leading cause: complex method.\n- 2 steps: 1 mechanical, 1 judgment.\n- Recovers ~2.50 of health score if applied.\n- Effort: M bucket. Detector confidence: high.\n- No dominant problem was recorded for this file, so whether these steps address it is unknown.\n## Steps, in order\nA step carrying `relocated_by` names a symbol an earlier step moves.\n\n1. **Extract Method** at `src/loader.py:40-120` (`Loader.load`)\n - Step id: `refac4_aaaaaaaaaaaaaaaaaaaa`\n - Mechanical: dataflow proved local extraction.\n - Move lines 61-78 of `Loader.load` into a new helper `<name>` (name it for what the lines do) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - Parameters (in): path\n - Returns (out): (nothing)\n\n2. **Move Method** at `src/loader.py:130` (`Loader.parse`)\n - Step id: `refac4_eeeeeeeeeeeeeeeeeeee`\n - Judgment. Not established: call sites resolved.\n - **Locate it again first.** Step `refac4_aaaaaaaaaaaaaaaaaaaa` moves this symbol, so the path and lines above are where it was, not where it will be when you get here.\n - This step's plan was not in this payload; ask for it by id: `refac4_eeeeeeeeeeeeeeeeeeee`.\n## Evidence behind the diagnosis\nSupporting observations, not extra work.\n- Extract Helper `loader.py:10-20`: duplicated lines: 11; occurrence count: 2\n1 of 3 shown.\n## Verify\n### For `Loader.load`\n\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py`\n\nRun:\n\n```\npytest tests/test_loader.py\n```\n\n### For `Loader.parse`\n\nNo guarding test was found; the test added before the edit passes after it.\n## Hard constraints\n- **Apply the steps in the order given.** It is dependency-safe; reordering it is not.\n- **Read a judgment step's code before applying it.** Its obligation is unproven.\n- **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.\n- **Keep behaviour.** Run the tests (and type-checker / linter) before and after.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step above applied in order.\n2. Per step: whether you applied it, and for anything you skipped, the reason.\n3. The Verify run, before and after, with its result.\n4. The opportunity id `refop4_dddddddddddddddddddd`, so the work can be matched back to the record.\n## This opportunity's id\n`refop4_dddddddddddddddddddd`\nQuote it when you report back."
}
}
}
diff --git a/tests/fixtures/agent_prompts/refactoring.json b/tests/fixtures/agent_prompts/refactoring.json
index 8132b426f..f1d100c4a 100644
--- a/tests/fixtures/agent_prompts/refactoring.json
+++ b/tests/fixtures/agent_prompts/refactoring.json
@@ -114,6 +114,184 @@
]
}
},
+ {
+ "name": "extract_method_staged_anchored",
+ "detail": {
+ "id": "refac4_iiiiiiiiiiiiiiiiiiii",
+ "refactoring_type": "extract_method",
+ "file_path": "src/report.py",
+ "target_symbol": "build_report",
+ "line_start": 10,
+ "line_end": 60,
+ "plan": {
+ "span": {
+ "start": 14,
+ "end": 30
+ },
+ "params": [
+ "rows"
+ ],
+ "returns": [
+ "totals"
+ ],
+ "suggested_name": "_sum_rows",
+ "needs_async": false,
+ "new_symbol": {
+ "kind": "function",
+ "async": false,
+ "receiver": null,
+ "uses_receiver": false,
+ "assigns": [],
+ "params": [
+ {
+ "name": "rows",
+ "type": null,
+ "mode": "in"
+ }
+ ],
+ "returns": [
+ {
+ "name": "totals",
+ "type": null
+ }
+ ],
+ "signature_text": "def _sum_rows(rows):",
+ "return_text": "return totals"
+ },
+ "call_site": {
+ "replace_span": {
+ "start": 14,
+ "end": 30
+ },
+ "new_text": "totals = _sum_rows(rows)"
+ },
+ "anchors": {
+ "first": " for row in rows:",
+ "last": " totals[row.key] += row.amount"
+ },
+ "stages": [
+ {
+ "span": {
+ "start": 14,
+ "end": 30
+ },
+ "params": [
+ "rows"
+ ],
+ "returns": [
+ "totals"
+ ],
+ "suggested_name": "_sum_rows",
+ "needs_async": false,
+ "new_symbol": {
+ "kind": "function",
+ "async": false,
+ "receiver": null,
+ "uses_receiver": false,
+ "assigns": [],
+ "params": [
+ {
+ "name": "rows",
+ "type": null,
+ "mode": "in"
+ }
+ ],
+ "returns": [
+ {
+ "name": "totals",
+ "type": null
+ }
+ ],
+ "signature_text": "def _sum_rows(rows):",
+ "return_text": "return totals"
+ },
+ "call_site": {
+ "replace_span": {
+ "start": 14,
+ "end": 30
+ },
+ "new_text": "totals = _sum_rows(rows)"
+ },
+ "anchors": {
+ "first": " for row in rows:",
+ "last": " totals[row.key] += row.amount"
+ },
+ "ccn": 6,
+ "nloc": 12,
+ "context_params": []
+ },
+ {
+ "span": {
+ "start": 32,
+ "end": 51
+ },
+ "params": [
+ "totals"
+ ],
+ "returns": [
+ "out"
+ ],
+ "suggested_name": "_format_totals",
+ "needs_async": false,
+ "new_symbol": {
+ "kind": "function",
+ "async": false,
+ "receiver": null,
+ "uses_receiver": false,
+ "assigns": [],
+ "params": [
+ {
+ "name": "totals",
+ "type": null,
+ "mode": "in"
+ }
+ ],
+ "returns": [
+ {
+ "name": "out",
+ "type": null
+ }
+ ],
+ "signature_text": "def _format_totals(totals):",
+ "return_text": "return out"
+ },
+ "call_site": {
+ "replace_span": {
+ "start": 32,
+ "end": 51
+ },
+ "new_text": "out = _format_totals(totals)"
+ },
+ "anchors": {
+ "first": " if not totals:\n return None",
+ "last": " out.append(f\"`{key}`: {value}\")"
+ },
+ "ccn": 6,
+ "nloc": 12,
+ "context_params": []
+ }
+ ],
+ "parameter_object": null,
+ "orchestrator": {
+ "ccn_before": 31,
+ "ccn_after": 19
+ }
+ },
+ "evidence": {
+ "slice_nloc": 24,
+ "ccn_removed": 12
+ },
+ "impact_delta": 0.9,
+ "effort_bucket": "M",
+ "blast_radius": {
+ "scope": "local"
+ },
+ "confidence": "medium",
+ "source_biomarker": "complex_method",
+ "governed_by": [],
+ "risks": []
+ }
+ },
{
"name": "performance_fix_steps",
"repo_name": null,
diff --git a/tests/unit/health/test_refactoring_anchors.py b/tests/unit/health/test_refactoring_anchors.py
new file mode 100644
index 000000000..e45146ad6
--- /dev/null
+++ b/tests/unit/health/test_refactoring_anchors.py
@@ -0,0 +1,405 @@
+"""Extract Method spans carry text anchors: the exact first and last lines, grown
+until each is unique (in the file when it can be, else in the function), so an
+agent finds a stage by its text after earlier stages have moved its lines. A
+staged split no text anchors falls back to the best single span; a function
+with neither is refused.
+"""
+
+from __future__ import annotations
+
+import textwrap
+from datetime import datetime
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from repowise.core.agent_prompts import render_plan
+from repowise.core.analysis.health.dataflow import Extraction, analyze_file
+from repowise.core.analysis.health.fix_first.build import build_fix_first
+from repowise.core.analysis.health.refactoring import extract_method
+from repowise.core.analysis.health.refactoring.anchors import (
+ anchor_plan,
+ file_source,
+ function_scope,
+ occurrences,
+ span_anchors,
+)
+from repowise.core.analysis.health.refactoring.extract_method import (
+ REFUSED_DETAIL,
+ ExtractMethodDetector,
+ _serve_anchored,
+)
+from repowise.core.analysis.health.refactoring.models import RefactoringContext
+from repowise.core.analysis.health.refactoring.recipe import (
+ ELSEWHERE_NOTE,
+ LINE_RULE,
+ SCRIPT_RULE,
+ build_recipe,
+)
+from repowise.core.analysis.health.refactoring.render import list_plan
+from repowise.core.analysis.health.refactoring_summary import summarize_plans
+from tests.unit.health.test_extract_method_stages import _persist, _plans
+
+_ROOT = Path(__file__).resolve().parents[3]
+
+
+def _fn(src: bytes, name: str = "f", language: str = "python", ext: str = "py"):
+ 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, src, flagged_only=False)
+ return next(f for f in res.functions if f.name == name)
+
+
+def _scope(src: bytes, name: str = "f", language: str = "python", ext: str = "py"):
+ fn_node = _fn(src, name, language, ext).fn_node
+ return function_scope(fn_node, file_source(fn_node))
+
+
+_REPEATS = b"""\
+def f(rows):
+ total = 0
+ for r in rows:
+ total += r
+ for r in rows:
+ total += r
+ total -= 1
+ return total
+"""
+
+_TWIN = b"""\
+def f(rows):
+ for r in rows:
+ print(r)
+ x = 1
+ for r in rows:
+ print(r)
+"""
+
+
+def test_a_repeated_first_line_grows_until_unique():
+ # Lines 5-7: "for r in rows:" and "total += r" both occur twice.
+ assert span_anchors(_scope(_REPEATS), 5, 7) == {
+ "first": " for r in rows:\n total += r\n total -= 1",
+ "last": " total -= 1",
+ "unique_in": "file",
+ }
+
+
+def test_a_span_whose_ends_repeat_in_full_is_unanchored():
+ assert span_anchors(_scope(_TWIN), 5, 6) is None
+
+
+def test_crlf_anchors_match_the_bytes_on_disk():
+ raw = _REPEATS.replace(b"\n", b"\r\n")
+ anchors = span_anchors(_scope(raw), 2, 4)
+ # Lines 3-4 repeat as lines 5-6, so the last anchor reaches back to line 2.
+ assert anchors["first"] == " total = 0"
+ assert anchors["last"] == " total = 0\r\n for r in rows:\r\n total += r"
+ for text in (anchors["first"], anchors["last"]):
+ assert raw.count(text.encode()) == 1
+ # A string edit from the first anchor through the last replaces exactly the span.
+ start = raw.index(anchors["first"].encode())
+ end = raw.index(anchors["last"].encode()) + len(anchors["last"].encode())
+ edited = raw[:start] + b" total = _sum(rows)" + raw[end:]
+ assert edited.split(b"\r\n") == [
+ b"def f(rows):",
+ b" total = _sum(rows)",
+ b" for r in rows:",
+ b" total += r",
+ b" total -= 1",
+ b" return total",
+ b"",
+ ]
+
+
+def test_tabs_are_kept_as_written():
+ src = b"def f(rows):\n\ttotal = 0\n\tfor r in rows:\n\t\ttotal += r\n\treturn total\n"
+ assert span_anchors(_scope(src), 2, 4) == {
+ "first": "\ttotal = 0",
+ "last": "\t\ttotal += r",
+ "unique_in": "file",
+ }
+
+
+def test_a_span_at_the_function_start_and_end():
+ # No trailing newline: the span's last line is the file's last.
+ scope = _scope(b"def f(a):\n x = a + 1\n y = x * 2\n return y")
+ assert (scope.start, scope.end) == (1, 4)
+ assert span_anchors(scope, 2, 4) == {
+ "first": " x = a + 1",
+ "last": " return y",
+ "unique_in": "file",
+ }
+ # A span outside the function has nothing to anchor.
+ assert span_anchors(scope, 4, 5) is None
+
+
+def test_a_one_line_span_and_overlapping_anchors():
+ assert span_anchors(_scope(_REPEATS), 7, 7) == {
+ "first": " total -= 1",
+ "last": " total -= 1",
+ "unique_in": "file",
+ }
+ # "y = 2" repeats, so the first anchor grows over the line the last one is.
+ src = b"def f(a):\n x = 1\n y = 2\n z = 3\n x = 1\n y = 2\n"
+ anchors = span_anchors(_scope(src), 3, 4)
+ assert anchors["first"] == " y = 2\n z = 3"
+ assert anchors["last"] == " z = 3"
+
+
+def test_blank_lines_above_the_first_token_keep_line_numbers():
+ src = b"\n\n# lead\ndef f(a):\n x = a + 1\n return x\n"
+ scope = _scope(src)
+ assert scope.start == 4
+ assert span_anchors(scope, 5, 6)["first"] == " x = a + 1"
+
+
+def test_a_twin_elsewhere_in_the_file_grows_the_anchor_or_says_so():
+ src = textwrap.dedent(
+ """\
+ def g(rows):
+ for r in rows:
+ print(r)
+
+ def f(rows):
+ for r in rows:
+ print(r)
+ return rows
+ """
+ ).encode()
+ scope = _scope(src)
+ # Lines 6-7 are g's body too; line 8 makes the first anchor file-unique.
+ anchors = span_anchors(scope, 6, 8)
+ assert anchors["first"] == " for r in rows:\n print(r)\n return rows"
+ assert anchors["unique_in"] == "file"
+ # Lines 6-7 alone repeat g's whole body: unique only inside f, and served so.
+ assert span_anchors(scope, 6, 7) == {
+ "first": " for r in rows:",
+ "last": " print(r)",
+ "unique_in": "function",
+ }
+
+
+def test_typescript_anchors_follow_its_lines():
+ src = textwrap.dedent(
+ """\
+ export function f(rows: number[]): number {
+ let total = 0;
+ for (const r of rows) {
+ total += r;
+ }
+ return total;
+ }
+ """
+ ).encode()
+ scope = _scope(src, "f", "typescript", "ts")
+ assert span_anchors(scope, 3, 5) == {
+ "first": " for (const r of rows) {",
+ "last": " }",
+ "unique_in": "file",
+ }
+
+
+def test_anchor_plan_is_all_or_nothing():
+ scope = _scope(_REPEATS)
+ ok = {"span": {"start": 2, "end": 4}, "stages": [{"span": {"start": 2, "end": 4}}]}
+ assert anchor_plan(ok, scope)
+ assert ok["anchors"] == ok["stages"][0]["anchors"]
+ mixed = {"span": {"start": 2, "end": 4}, "stages": [{"span": {"start": 2, "end": 99}}]}
+ assert not anchor_plan(mixed, scope)
+ assert "anchors" not in mixed and "anchors" not in mixed["stages"][0]
+
+
+def test_every_stage_of_a_staged_plan_is_anchored_once_in_the_function():
+ src = textwrap.dedent(_persist())
+ plan = _plans(_persist())["persist"].plan
+ rows = src.split("\n")
+ grown = 0
+ for stage in plan["stages"]:
+ anchors, span = stage["anchors"], stage["span"]
+ for text in (anchors["first"], anchors["last"]):
+ assert occurrences(src, text) == 1
+ assert rows[span["start"] - 1] == anchors["first"].split("\n")[0]
+ assert rows[span["end"] - 1] == anchors["last"].split("\n")[-1]
+ grown += "\n" in anchors["last"]
+ # Every section ends on "if strict: raise", so a last line alone repeats.
+ assert grown
+ assert plan["anchors"] == plan["stages"][0]["anchors"]
+
+
+def _detail(plan: dict) -> dict:
+ return {"id": "x", "refactoring_type": "extract_method", "file_path": "m.py",
+ "target_symbol": "persist", "plan": plan}
+
+
+def test_anchors_are_detail_only_and_reach_the_recipe():
+ plan = _plans(_persist())["persist"].plan
+ assert "anchors" not in list_plan(plan)
+ recipe = build_recipe(_detail(plan))
+ extracts = [s for s in recipe["steps"] if s["action"] == "extract"]
+ assert [s["anchors"] for s in extracts] == [s["anchors"] for s in plan["stages"]]
+ assert "starts and ends with the lines shown" in extracts[0]["text"]
+ assert SCRIPT_RULE in recipe["does_not"] and LINE_RULE in recipe["does_not"]
+
+
+def _stage(first: str, last: str, unique_in: str = "file") -> dict:
+ return {"span": {"start": 3, "end": 9}, "params": [], "returns": [],
+ "anchors": {"first": first, "last": last, "unique_in": unique_in}}
+
+
+def test_the_prompt_fences_an_anchor_past_its_backticks_and_flags_a_twin():
+ text = render_plan(_detail(_stage(' s = """```x```"""', " return s", "function")))
+ assert '````\n s = """```x```"""\n````' in text
+ assert "```\n return s\n```" in text
+ assert ELSEWHERE_NOTE in text
+ assert ELSEWHERE_NOTE not in render_plan(_detail(_stage(" a = 1", " b = 2")))
+
+
+def test_the_apply_rules_read_the_same_in_every_renderer():
+ def sentence(rule: dict) -> str:
+ reason = rule["reason"]
+ return f"Do not {rule['constraint']}. {reason[0].upper()}{reason[1:]}."
+
+ text = render_plan(_detail(_stage(" a = 1", " b = 2"))).replace("**", "")
+ ui = _ROOT / "packages/ui/src/health/ai-prompts"
+ steps_ts = (ui / "refactoring-plan-steps.ts").read_text(encoding="utf-8")
+ prompts_ts = (ui / "refactoring-prompts.ts").read_text(encoding="utf-8")
+ for wording in (sentence(SCRIPT_RULE), sentence(LINE_RULE)):
+ assert wording in text
+ assert f'"{wording}"' in steps_ts
+ assert f'"{ELSEWHERE_NOTE}"' in steps_ts
+ # The opportunity fallback reads the same constants.
+ assert "SCRIPT_RULE_TEXT," in prompts_ts and "LINE_RULE_TEXT," in prompts_ts
+
+
+def test_an_unanchorable_span_refuses_the_plan_with_a_reason():
+ scope = _scope(_TWIN)
+ finding = SimpleNamespace(details={})
+ out: list = []
+ _serve_anchored(out, SimpleNamespace(plan={"span": {"start": 5, "end": 6}}), [finding], scope)
+ assert out == [] and finding.details == {REFUSED_DETAIL: "span_unanchored"}
+ served = SimpleNamespace(plan={"span": {"start": 2, "end": 4}})
+ _serve_anchored(out, served, [finding], scope)
+ assert out == [served]
+ assert served.plan["anchors"]["first"] == " for r in rows:\n print(r)\n x = 1"
+
+
+def _persist_ctx() -> RefactoringContext:
+ src = textwrap.dedent(_persist()).encode()
+ fns = analyze_file("m.py", "python", src, flagged_only=False).functions
+ if not fns:
+ pytest.skip("tree-sitter language pack missing for python")
+ findings = [
+ SimpleNamespace(biomarker_type="complex_method", function_name=f.name,
+ line_start=f.start_line, health_impact=2.0, details={})
+ for f in fns
+ ]
+ return RefactoringContext(
+ file_path="m.py", language="python", nloc=300, findings=findings, function_analyses=fns
+ )
+
+
+def _unanchor(monkeypatch, *, single: bool) -> None:
+ """Make every staged plan (and with *single*, every plan) unanchorable."""
+ real = extract_method.anchor_plan
+
+ def fake(plan, scope):
+ if plan.get("stages") or single:
+ return False
+ return real(plan, scope)
+
+ monkeypatch.setattr(extract_method, "anchor_plan", fake)
+
+
+def _persist_plans(ctx: RefactoringContext) -> list:
+ return [p for p in ExtractMethodDetector().detect(ctx) if p.target_symbol == "persist"]
+
+
+def test_a_staged_split_no_text_anchors_falls_back_to_one_span(monkeypatch):
+ ctx = _persist_ctx()
+ (staged,) = _persist_plans(ctx)
+ first = staged.plan["stages"][0]["span"]
+ # The fixture's function has no single span of its own: give it stage 1's.
+ single = Extraction(first["start"], first["end"], (), (), slice_nloc=10, ccn_removed=2)
+ monkeypatch.setattr(extract_method, "_choose", lambda *_: single)
+ _unanchor(monkeypatch, single=False)
+ (plan,) = _persist_plans(ctx)
+ assert "stages" not in plan.plan and plan.plan["anchors"]
+ assert all(REFUSED_DETAIL not in f.details for f in ctx.findings)
+
+
+def test_a_function_neither_plan_anchors_is_refused(monkeypatch):
+ _unanchor(monkeypatch, single=True)
+ ctx = _persist_ctx()
+ assert _persist_plans(ctx) == []
+ refused = {f.function_name: f.details.get(REFUSED_DETAIL) for f in ctx.findings}
+ assert refused["persist"] == "span_unanchored"
+
+
+def _fix_first_plan_leads(ctx: RefactoringContext, plans: list) -> int:
+ """How many Fix first items lead with a stored Extract Method plan's step."""
+ metrics = [{"file_path": "m.py", "score": 3.0, "nloc": 300, "is_test": False,
+ "commit_count_90d": 5, "dependents": 2, "analyzed_commit": "abc",
+ "updated_at": datetime(2026, 10, 1)}]
+ findings = [
+ {"file_path": "m.py", "biomarker_type": f.biomarker_type, "severity": "high",
+ "function_name": f.function_name, "line_start": f.line_start, "health_impact": 2.0,
+ "public_id": f"finding_{i}", "dimension": "defect",
+ "details": {"ccn": 40, "nloc": 120, "max_nesting": 4,
+ "deepest_block": {"start": 20, "end": 30}, **f.details}}
+ for i, f in enumerate(ctx.findings)
+ if f.function_name == "persist"
+ ]
+ rows = [{"public_id": f"refac_{i}", "refactoring_type": p.refactoring_type,
+ "file_path": "m.py", "target_symbol": p.target_symbol, "plan": p.plan,
+ "evidence": p.evidence} for i, p in enumerate(plans)]
+ queue = build_fix_first(metrics=metrics, findings=findings, plans=rows, limit=None)
+ # With or without a plan the function is one item; only its first step differs.
+ assert len(queue.items) == 1
+ return sum(
+ bool(item.action.steps) and item.action.steps[0].text.startswith(("Extract", "Stage"))
+ for item in queue.items
+ )
+
+
[email protected]("anchored", [True, False])
+def test_fix_first_and_refactoring_totals_count_a_refusal_alike(monkeypatch, anchored):
+ if not anchored:
+ _unanchor(monkeypatch, single=True)
+ ctx = _persist_ctx()
+ plans = _persist_plans(ctx)
+ total = summarize_plans(plans)["total"]
+ assert total == (1 if anchored else 0)
+ assert _fix_first_plan_leads(ctx, plans) == total
+
+
+def _opportunity(kind: str, plan: dict | None) -> dict:
+ import json
+
+ fixture = json.loads(
+ (_ROOT / "tests/fixtures/agent_prompts/refactoring.json").read_text(encoding="utf-8")
+ )
+ detail = dict(fixture["opportunities"][0]["detail"])
+ step = {**detail["steps"][0], "refactoring_type": kind, "plan_id": "p1"}
+ detail["steps"] = [step]
+ detail["plans"] = [{**_detail(plan or {}), "id": "p1", "refactoring_type": kind}]
+ return detail
+
+
+ ("kind", "plan", "rules"),
+ [
+ ("move_method", {"method": "m", "from_class": "A", "to_class": "B"}, ()),
+ ("extract_method", {"span": {"start": 3, "end": 9}}, (SCRIPT_RULE,)),
+ ("extract_method", _stage(" a = 1", " b = 2"), (SCRIPT_RULE, LINE_RULE)),
+ ],
+)
+def test_an_opportunity_states_only_the_rules_its_steps_need(kind, plan, rules):
+ from repowise.core.agent_prompts import render_opportunity
+
+ text = render_opportunity(_opportunity(kind, plan)).replace("**", "")
+ for rule in (SCRIPT_RULE, LINE_RULE):
+ assert (f"Do not {rule['constraint']}." in text) == (rule in rules)
diff --git a/tests/unit/health/test_refactoring_extract_method.py b/tests/unit/health/test_refactoring_extract_method.py
index bedae47e8..f16f49945 100644
--- a/tests/unit/health/test_refactoring_extract_method.py
+++ b/tests/unit/health/test_refactoring_extract_method.py
@@ -677,6 +677,7 @@ def test_detector_emits_suggestion_for_flagged_function():
"needs_async",
"new_symbol",
"call_site",
+ "anchors",
}
assert s.plan["needs_async"] is False
# A module-level function: the helper is a plain function too.
@@ -1040,6 +1041,8 @@ def test_a_best_span_below_the_floor_yields_to_the_next_one(monkeypatch):
trivial = Extraction(10, 17, ("a",), (), slice_nloc=8, ccn_removed=1)
worth = Extraction(20, 27, ("b",), (), slice_nloc=8, ccn_removed=3)
monkeypatch.setattr(extract_method, "find_extractions", lambda _a, _l, _r=None, _p=None: [trivial, worth])
+ # No parsed source to anchor against: this pins span choice, not anchoring.
+ monkeypatch.setattr(extract_method, "anchor_plan", lambda _plan, _fn: True)
fn = _Shape(12, 40)
analysis = type(
"A", (), {"name": "f", "start_line": 1, "end_line": 50, "ccn": 12, "nloc": 40,
@@ -1254,6 +1257,7 @@ def test_a_refused_span_yields_only_to_a_disjoint_one(monkeypatch):
monkeypatch.setattr(
extract_method, "find_extractions", lambda _a, _l, _r=None, _p=None: [whole, shrunk, disjoint]
)
+ monkeypatch.setattr(extract_method, "anchor_plan", lambda _plan, _fn: True)
analysis = type(
"A", (), {"name": "f", "start_line": 1, "end_line": 100, "ccn": 30, "nloc": 90,
"fn_node": None}
diff --git a/tests/unit/server/test_wire_vocabulary_parity.py b/tests/unit/server/test_wire_vocabulary_parity.py
index 647584481..b800d99a6 100644
--- a/tests/unit/server/test_wire_vocabulary_parity.py
+++ b/tests/unit/server/test_wire_vocabulary_parity.py
@@ -181,6 +181,12 @@ def test_refactoring_recipe_vocabularies_match_python() -> None:
assert _union_members("RecipePreconditionKind", "refactoring.ts") == set(PRECONDITION_KINDS)
+def test_anchor_scopes_match_python() -> None:
+ from repowise.core.analysis.health.refactoring.anchors import ANCHOR_SCOPES
+
+ assert _union_members("AnchorScope", "refactoring.ts") == set(ANCHOR_SCOPES)
+
+
def test_refactoring_payoff_outcomes_match_python() -> None:
from repowise.core.analysis.health.refactoring.payoff import PAYOFF_OUTCOMES