Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(refactoring): leave the Extract Method helper's name to the person applying the plan (#3588)
Raghav Chamadiyabe8a4ca5ce6c
diff --git a/docs/architecture/refactoring.md b/docs/architecture/refactoring.mdindex 258546b55..106fc020e 100644--- a/docs/architecture/refactoring.md+++ b/docs/architecture/refactoring.md@@ -31,10 +31,9 @@ feature-envy distance, MFAS for cycles, Newman modularity for decomposition.`source_biomarker`, `validation`). Text is rendered only at the surfaces.`impact_delta` credits the share of the source finding the plan removes; forExtract Method that is `ccn_removed / ccn`, `slice_nloc / nloc`, or the larger of-the two for `brain_method`, capped at 1. `naming.py` returns `null` when no fact-anchors a name. Extract Method's `helper_naming.py` names a helper from a `timed()`-label, a banner comment, or `compute_<out>` for an effect-free span, and drops any-name already taken in scope.+the two for `brain_method`, capped at 1. Extract Method's `helper_naming.py` gives+a helper the placeholder `extracted_helper`, numbered when the name is taken in+scope, and the plan asks the agent applying it to rename it.Plan ids come from `identity.py`: a `refac<version>_` prefix over a per-type stablekernel. Bumping the version re-mints ids; a held id from an older version reportsdiff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.mdindex e3d7ca9b0..281a780bf 100644--- a/docs/layers/REFACTORING.md+++ b/docs/layers/REFACTORING.md@@ -168,10 +168,10 @@ that kind passes a per-language review. When such a step follows another lead, tFix first item leaves it out and says how many steps it held back; the full plankeeps them. Code only moves within a language family,so Java, Kotlin and Scala are separate. A callback is named after the call it is-passed to. An Extract Method helper is named from a stage label, a banner comment,-or `compute_<value>` when the span has no outside effects; otherwise it is the host-function's name plus what the span handles, such as `render_card_directive`. A-name already taken where the helper lands is skipped for the next candidate.+passed to. An Extract Method helper follows the same rule: the code rarely says+what a block is for, so the plan gives the helper a placeholder name,+`extracted_helper`. The plan and its prompt ask you to rename it for what it+returns or does when you apply it.An empty list means no detector found work that clears its gates. It does not meanthe code needs no attention: check the findings in@@ -286,8 +286,7 @@ Most plans answer a health finding, so per-path marker rules indeclares them. In TypeScript, an optional parameter is written `T | undefined`,and a type an earlier guard narrows (`if (!x) return;`) is written narrowed, ora note asks for the narrowed type. Plan detail shows both with a copy button.- Where the code names no helper or type, the text reads `<name>` or `<type>` for- you to fill in.+ Where the code names no type, the text reads `<type>` for you to fill in.- A Python, TypeScript or JavaScript function too complex for one helper canget a staged plan instead: several helpers the function calls in order, eachsmall enough to leave the finding behind. Plan detail lists them as steps,diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/bindings.py b/packages/core/src/repowise/core/analysis/health/dataflow/bindings.pynew file mode 100644index 000000000..9b0d24c72--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/dataflow/bindings.py@@ -0,0 +1,109 @@+"""The names a node binds and the names a file imports, read off the tree.++``bound_names`` / ``binding_target`` read an assignment or declaration's plain+names (not ``a.b`` or ``a[i]``); ``imported_names`` the names a file's+top-level imports bring in.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from tree_sitter import Node++ from ..complexity.languages import LanguageNodeMap++_MEMBER_KINDS = frozenset(+ {"attribute", "member_expression", "field_expression", "selector_expression", "field_access"}+)+# Write targets that reach through a name instead of rebinding it.+_REACH_KINDS = _MEMBER_KINDS | {+ "subscript",+ "subscript_expression",+ "index_expression",+ "array_access",+ "pointer_expression",+}+# Binding forms outside ``lmap.assignment_kinds`` / ``local_decl_kinds``: the+# declarator a declaration statement wraps, and module-level constants.+_DECLARATOR_KINDS = frozenset(+ {+ "variable_declarator",+ "init_declarator",+ "var_spec",+ "const_spec",+ "let_declaration",+ "short_var_declaration",+ "const_item",+ "static_item",+ }+)+_TARGET_FIELDS = ("left", "name", "pattern", "declarator")+# Namespaces every file can call without importing them.+_BUILTIN_NAMESPACES = frozenset(+ {"Math", "JSON", "Object", "Array", "Number", "String", "Date", "Promise", "Reflect",+ "Symbol", "BigInt", "Intl", "Integer", "Long", "Double", "Float", "Boolean", "Character"}+) # fmt: skip+++def bound_names(target: Node) -> list[str]:+ """The plain names a binding target binds (not ``a.b`` or ``a[i]``)."""+ out: list[str] = []+ stack = [target]+ while stack:+ node = stack.pop()+ if node.type in _REACH_KINDS or _is_deref(node):+ continue+ if _is_name(node):+ out.append(_text(node))+ continue+ # A declarator's own target only: its type and initializer bind nothing.+ inner = _field(node, _TARGET_FIELDS)+ stack.extend([inner] if inner is not None else node.named_children)+ return out+++def binding_target(node: Node, lmap: LanguageNodeMap) -> Node | None:+ """The target of *node* when it binds names, else ``None``."""+ binders = lmap.assignment_kinds | lmap.local_decl_kinds | _DECLARATOR_KINDS+ return _field(node, _TARGET_FIELDS) if node.type in binders else None+++def imported_names(root: Node, *, namespaces: bool = True) -> frozenset[str]:+ """Names a file's top-level imports bring in, plus built-in namespaces+ unless *namespaces* is False.++ Every name leaf of an import counts (``os`` and ``path`` of ``os.path``),+ and a quoted path counts by its last segment (Go ``"net/http"`` is+ ``http``).+ """+ names = set(_BUILTIN_NAMESPACES) if namespaces else set()+ for node in root.named_children:+ if "import" not in node.type and node.type != "use_declaration":+ continue+ stack = [node]+ while stack:+ leaf = stack.pop()+ if leaf.named_children:+ stack.extend(leaf.named_children)+ continue+ text = _text(leaf).strip("\"'`")+ names.add(text.rsplit("/", 1)[-1])+ return frozenset(names)+++def _field(node: Node, fields: tuple[str, ...]) -> Node | None:+ return next((c for f in fields if (c := node.child_by_field_name(f)) is not None), None)+++def _is_deref(node: Node) -> bool:+ return node.type == "unary_expression" and bool(node.children) and node.children[0].type == "*"+++def _is_name(node: Node) -> bool:+ return not node.named_children and "identifier" in node.type+++def _text(node: Node) -> str:+ return (node.text or b"").decode("utf-8", "replace")diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/effects.py b/packages/core/src/repowise/core/analysis/health/dataflow/effects.pydeleted file mode 100644index 63dc12585..000000000--- a/packages/core/src/repowise/core/analysis/health/dataflow/effects.py+++ /dev/null@@ -1,402 +0,0 @@-"""Whether an Extract Method span acts on anything it does not own.--A span that only builds values can be named for the value (``compute_total``);-one that prints, awaits, mutates an argument or writes through ``self`` is an-action, and a value name would describe it wrongly. A wrong ``compute_`` name-costs more than no name, so every doubt here resolves to "acts outside".--What the span owns is what it binds to a fresh value: a literal, a collection-or comprehension, an operator result, or an empty built-in collection. A name-bound from a call result or from another name may alias an outside object, so-calls and writes through it count as outside effects. Aliasing beyond that-(a fresh list later handed a parameter's object) is not followed.--Calls are judged by position and receiver:--- in statement position (result dropped), any call except a method call on an- owned name: it ran for what it does;-- elsewhere, a method call whose receiver is not owned, unless the receiver is- an imported module or a built-in namespace (``os.path.join``,- ``Math.max``), or the method is a read that changes nothing on the built-in- types it is almost always called on (``_PURE_METHODS``). A free function or a- constructor in expression position is not judged: without types there is no- telling ``len`` from ``open``, and its result is checked where it is used.-"""--from __future__ import annotations--from dataclasses import dataclass-from typing import TYPE_CHECKING--if TYPE_CHECKING:- from tree_sitter import Node-- from ..complexity.languages import LanguageNodeMap- from .defuse import FunctionDefUse--_MEMBER_KINDS = frozenset(- {"attribute", "member_expression", "field_expression", "selector_expression", "field_access"}-)-# Write targets that reach through a name instead of rebinding it.-_REACH_KINDS = _MEMBER_KINDS | {- "subscript",- "subscript_expression",- "index_expression",- "array_access",- "pointer_expression",-}-_LIST_KINDS = frozenset({"expression_list", "pattern_list", "tuple_pattern", "list_pattern"})-# Fields that lead from an access or call to the name it starts from.-_BASE_FIELDS = ("function", "object", "value", "operand", "argument", "array")-_RECEIVER_FIELDS = ("object", "operand", "value", "argument")-_MEMBER_FIELDS = ("property", "attribute", "field")-# Binding forms outside ``lmap.assignment_kinds`` / ``local_decl_kinds``: the-# declarator a declaration statement wraps, and module-level constants.-_DECLARATOR_KINDS = frozenset(- {- "variable_declarator",- "init_declarator",- "var_spec",- "const_spec",- "let_declaration",- "short_var_declaration",- "const_item",- "static_item",- }-)-_TARGET_FIELDS = ("left", "name", "pattern", "declarator")-_VALUE_FIELDS = ("right", "value")-# Statements that act outside the span whatever they hold.-_EFFECT_STMT_KINDS = frozenset(- {"go_statement", "defer_statement", "global_statement", "nonlocal_statement", "send_statement"}-)-_UPDATE_KINDS = frozenset({"update_expression", "inc_statement", "dec_statement"})-# Every grammar the slicer serves names its expression statement this;-# ``lmap.expr_stmt_kinds`` lists only the grammars that do not.-_EXPR_STMT = "expression_statement"-# Values that are new objects or plain values, never an alias.-_FRESH_KINDS = frozenset(- {- # Python- "list", "dictionary", "set", "tuple", "list_comprehension", "set_comprehension",- "dictionary_comprehension", "generator_expression", "string", "concatenated_string",- "integer", "float", "true", "false", "none",- # TS / JS- "array", "object", "template_string", "number", "null", "undefined", "regex",- # Go- "composite_literal", "interpreted_string_literal", "raw_string_literal", "int_literal",- "float_literal", "nil",- # Java- "array_creation_expression", "string_literal", "decimal_integer_literal", "null_literal",- "character_literal",- # Rust / C++- "array_expression", "tuple_expression", "integer_literal", "boolean_literal", "initializer_list", "number_literal", "nullptr",- }-) # fmt: skip-_OPERATOR_KINDS = frozenset(- {"binary_operator", "binary_expression", "boolean_operator", "comparison_operator",- "not_operator", "unary_operator"}-) # fmt: skip-# Constructors of an empty or copied built-in collection: the result is new.-_FRESH_CTORS = frozenset(- {- "list", "dict", "set", "tuple", "frozenset", "defaultdict", "OrderedDict", "Counter",- "deque", "str", "int", "float", "bool", "bytearray",- "Map", "Set", "Array", "Object", "WeakMap", "WeakSet",- "make", "new",- "ArrayList", "HashMap", "HashSet", "LinkedList", "LinkedHashMap", "TreeMap", "ArrayDeque",- "StringBuilder",- "Vec::new", "Vec::with_capacity", "HashMap::new", "HashSet::new", "BTreeMap::new",- "BTreeSet::new", "VecDeque::new", "String::new", "String::from",- }-) # fmt: skip-_FRESH_MACROS = frozenset({"vec", "format"})-# Reads that change nothing on the str / list / dict / array / map they are-# nearly always called on. A name here on a type that does mutate is the-# ceiling of a type-free check; mutators (append, pop, push, set, sort, update,-# write, ...) are deliberately absent.-_PURE_METHODS = frozenset(- {- # str- "strip", "lstrip", "rstrip", "lower", "upper", "casefold", "title", "capitalize",- "split", "rsplit", "splitlines", "join", "startswith", "endswith", "replace", "format",- "encode", "decode", "find", "rfind", "index", "count", "partition", "rpartition",- "removeprefix", "removesuffix", "isdigit", "isalpha", "isalnum", "isspace", "isupper",- "islower", "zfill", "ljust", "rjust", "center",- # dict / list reads, compiled patterns- "items", "keys", "values", "copy", "match", "fullmatch", "search", "findall",- "finditer", "sub",- # JS / TS strings and arrays (callbacks are walked like the rest of the span)- "trim", "trimStart", "trimEnd", "toLowerCase", "toUpperCase", "slice", "substring",- "includes", "indexOf", "lastIndexOf", "startsWith", "endsWith", "map", "filter", "some",- "every", "findIndex", "findLast", "flatMap", "flat", "concat", "reduce", "at",- "charAt", "charCodeAt", "padStart", "padEnd", "repeat", "replaceAll", "test", "toString",- "toFixed", "localeCompare", "entries", "has",- # Java / Rust reads- "equals", "length", "size", "isEmpty", "contains", "containsKey", "getOrDefault",- "len", "is_empty", "iter", "clone", "to_string", "as_str", "starts_with", "ends_with",- "to_lowercase", "to_uppercase",- }-) # fmt: skip-# A keyed read (``d.get(k)``); with no argument it is ``q.get()``, which pops.-_READ_WITH_KEY = frozenset({"get"})-# Namespaces every file can call without importing them.-_BUILTIN_NAMESPACES = frozenset(- {"Math", "JSON", "Object", "Array", "Number", "String", "Date", "Promise", "Reflect",- "Symbol", "BigInt", "Intl", "Integer", "Long", "Double", "Float", "Boolean", "Character"}-) # fmt: skip---@dataclass(frozen=True)-class Ownership:- """What a span may touch without acting outside itself.-- ``owned``: names the span binds, every time, to a fresh value.- ``declared``: names its function declares (parameters included); a write- to any other name reaches a captured variable. ``None`` for a language- where assignment is declaration (Python), whose outer writes need- ``global`` / ``nonlocal`` and are caught there.- ``modules``: imported names and built-in namespaces.- """-- owned: frozenset[str]- declared: frozenset[str] | None- modules: frozenset[str]---def has_outside_effects(stmts: list[Node], own: Ownership, lmap: LanguageNodeMap) -> bool:- """Whether running *stmts* acts on anything the span does not own.-- Lambdas and callbacks are walked with the span: most run where they are- written (``map``, ``sort(key=...)``). The slicer refuses spans holding a- named nested function, so none is walked by mistake.- """- expr_kinds = lmap.expr_stmt_kinds | {_EXPR_STMT}- stack = list(stmts)- while stack:- node = stack.pop()- if _acts_outside(node, own, lmap, expr_kinds):- return True- stack.extend(node.named_children)- return False---def _acts_outside(- node: Node, own: Ownership, lmap: LanguageNodeMap, expr_kinds: frozenset[str]-) -> bool:- t = node.type- if t in lmap.with_kinds or t in _EFFECT_STMT_KINDS:- return True- if t in expr_kinds:- return _drops_a_call(node, own, lmap)- if t in lmap.call_kinds:- return _impure_call(node, own)- if t in lmap.assignment_kinds or t in lmap.augmented_assign_kinds:- left = node.child_by_field_name("left")- return left is not None and any(_escapes(x, own) for x in _targets(left))- if t in _UPDATE_KINDS:- target = node.child_by_field_name("argument") or _first(node)- return target is not None and _escapes(target, own)- if t == "delete_statement":- return any(_escapes(x, own) for x in _targets(_first(node)))- if t == "unary_expression" and node.children and node.children[0].type == "delete":- target = node.child_by_field_name("argument")- return target is not None and _escapes(target, own)- if t == "reference_expression" and any(c.type == "mutable_specifier" for c in node.children):- target = node.child_by_field_name("value")- return target is not None and _root(target) not in own.owned- return False---def _drops_a_call(stmt: Node, own: Ownership, lmap: LanguageNodeMap) -> bool:- inner = _first(stmt)- while inner is not None and "await" in inner.type and inner.named_children:- inner = inner.named_children[0]- if inner is None:- return False- if inner.type.endswith("macro_invocation"):- return True- if inner.type not in lmap.call_kinds:- return False- receiver, _method = _call_parts(inner)- return receiver is None or _root(receiver) not in own.owned---def _impure_call(call: Node, own: Ownership) -> bool:- receiver, method = _call_parts(call)- if receiver is None or _root(receiver) in own.owned:- return False- if _module_path(receiver, own.modules) or method in _PURE_METHODS:- return False- if method in _READ_WITH_KEY:- args = call.child_by_field_name("arguments")- return args is None or not args.named_children- return True---def _call_parts(call: Node) -> tuple[Node | None, str | None]:- """A method call's receiver and method name; ``(None, None)`` for a call of- a plain function or a constructor."""- obj, name = call.child_by_field_name("object"), call.child_by_field_name("name")- if obj is not None and name is not None: # Java ``method_invocation``- return obj, _text(name)- fn = call.child_by_field_name("function")- if fn is None or fn.type not in _MEMBER_KINDS:- return None, None- receiver = _field(fn, _RECEIVER_FIELDS)- member = _field(fn, _MEMBER_FIELDS)- return receiver, _text(member) if member is not None else None---def _module_path(receiver: Node, modules: frozenset[str]) -> bool:- """True for ``os.path`` / ``Math``: plain member reads from a module name."""- node: Node | None = receiver- while node is not None and node.type in _MEMBER_KINDS:- node = _field(node, _RECEIVER_FIELDS)- return node is not None and _is_name(node) and _text(node) in modules---def _escapes(target: Node, own: Ownership) -> bool:- """Whether writing *target* changes something the span does not own."""- if target.type in _REACH_KINDS or _is_deref(target):- return _root(target) not in own.owned- if _is_name(target) and own.declared is not None:- return _text(target) not in own.declared- return False---def _is_deref(node: Node) -> bool:- return node.type == "unary_expression" and bool(node.children) and node.children[0].type == "*"---def owned_names(stmts: list[Node], lmap: LanguageNodeMap) -> frozenset[str]:- """Names *stmts* bind, at every binding, to a fresh value."""- binders = lmap.assignment_kinds | lmap.local_decl_kinds | _DECLARATOR_KINDS- fresh: dict[str, bool] = {}- stack = list(stmts)- while stack:- node = stack.pop()- stack.extend(node.named_children)- target = _field(node, _TARGET_FIELDS) if node.type in binders else None- if target is None:- continue- ok = _fresh(_field(node, _VALUE_FIELDS), lmap)- for name in bound_names(target):- fresh[name] = fresh.get(name, True) and ok- return frozenset(name for name, ok in fresh.items() if ok)---def _fresh(value: Node | None, lmap: LanguageNodeMap) -> bool:- if value is None:- return True # declared, not yet assigned: its later bindings decide- while value.type == "parenthesized_expression" and value.named_children:- value = value.named_children[0]- t = value.type- if t in _FRESH_KINDS or t in _OPERATOR_KINDS:- return True- if t in _LIST_KINDS:- return all(_fresh(v, lmap) for v in value.named_children)- if t.endswith("macro_invocation"):- macro = value.child_by_field_name("macro")- return macro is not None and _text(macro) in _FRESH_MACROS- if t in lmap.call_kinds or t == "new_expression":- callee = _field(value, ("function", "constructor", "type"))- return callee is not None and _text(callee).split("<")[0] in _FRESH_CTORS- return False---def bound_names(target: Node) -> list[str]:- """The plain names a binding target binds (not ``a.b`` or ``a[i]``)."""- out: list[str] = []- stack = [target]- while stack:- node = stack.pop()- if node.type in _REACH_KINDS or _is_deref(node):- continue- if _is_name(node):- out.append(_text(node))- continue- # A declarator's own target only: its type and initializer bind nothing.- inner = _field(node, _TARGET_FIELDS)- stack.extend([inner] if inner is not None else node.named_children)- return out---def binding_target(node: Node, lmap: LanguageNodeMap) -> Node | None:- """The target of *node* when it binds names, else ``None``."""- binders = lmap.assignment_kinds | lmap.local_decl_kinds | _DECLARATOR_KINDS- return _field(node, _TARGET_FIELDS) if node.type in binders else None---def declared_names(- fn_node: Node, def_use: FunctionDefUse, lmap: LanguageNodeMap-) -> frozenset[str] | None:- """Names *fn_node* declares, parameters and nested scopes included (over-- counting only hides a captured write). ``None`` where assignment is- declaration."""- if not lmap.local_decl_kinds:- return None- names = {p.name for p in def_use.params} | {d.var for d in def_use.definitions if d.declares}- decl = lmap.local_decl_kinds | _DECLARATOR_KINDS- stack = [fn_node]- while stack:- node = stack.pop()- stack.extend(node.named_children)- target = _field(node, _TARGET_FIELDS) if node.type in decl else None- if target is not None:- names.update(bound_names(target))- return frozenset(names)---def imported_names(root: Node, *, namespaces: bool = True) -> frozenset[str]:- """Names a file's top-level imports bring in, plus built-in namespaces- unless *namespaces* is False.-- Every name leaf of an import counts (``os`` and ``path`` of ``os.path``),- and a quoted path counts by its last segment (Go ``"net/http"`` is- ``http``); an extra name only exempts a module-style call, never a write.- """- names = set(_BUILTIN_NAMESPACES) if namespaces else set()- for node in root.named_children:- if "import" not in node.type and node.type != "use_declaration":- continue- stack = [node]- while stack:- leaf = stack.pop()- if leaf.named_children:- stack.extend(leaf.named_children)- continue- text = _text(leaf).strip("\"'`")- names.add(text.rsplit("/", 1)[-1])- return frozenset(names)---def _targets(left: Node | None) -> list[Node]:- if left is None:- return []- return list(left.named_children) if left.type in _LIST_KINDS else [left]---def _root(node: Node) -> str | None:- """The name an access or call chain starts from (``a`` in ``a.b[c].d()``)."""- for _ in range(64):- if not node.named_children:- return _text(node)- node = _field(node, _BASE_FIELDS) or node.named_children[0]- return None---def _field(node: Node, fields: tuple[str, ...]) -> Node | None:- return next((c for f in fields if (c := node.child_by_field_name(f)) is not None), None)---def _first(node: Node | None) -> Node | None:- return node.named_children[0] if node is not None and node.named_children else None---def _is_name(node: Node) -> bool:- return not node.named_children and "identifier" in node.type---def _text(node: Node) -> str:- return (node.text or b"").decode("utf-8", "replace")diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/span.py b/packages/core/src/repowise/core/analysis/health/dataflow/span.pyindex 717c04fbb..16bac3aac 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/span.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/span.py@@ -1,10 +1,8 @@-"""Where an Extract Method span sits in its function's tree: its statements, the-comments that head them, and the ``with`` block it may be the body of.+"""Where an Extract Method span sits in its function's tree: its statements,+the comments that head them, and whether a statement is an exiting guard.-Read by the helper-naming step only, after a span has been chosen, so the cost-is one walk of one function per emitted plan. The tree is the one the slicer-already holds (``FunctionAnalysis.fn_node``); nothing is re-parsed. Whether the-span acts outside itself is :mod:`effects`.+The tree is the one the slicer already holds (``FunctionAnalysis.fn_node``);+nothing is re-parsed."""from __future__ import annotations@@ -38,27 +36,6 @@ def span_statements(return []-def enclosing_with(stmts: list[Node], lmap: LanguageNodeMap) -> Node | None:- """The ``with`` statement whose whole body *stmts* is, else ``None``: a span- lifted out of ``with timed(...):`` is the block that header labels."""- holder = body_holder(stmts)- return holder if holder is not None and holder.type in lmap.with_kinds else None---def body_holder(stmts: list[Node]) -> Node | None:- """The statement whose whole body *stmts* is (a ``with``, an ``if`` arm, a- loop), else ``None``."""- if not stmts:- return None- block = stmts[0].parent- holder = block.parent if block is not None else None- if holder is None:- return None- code = [c for c in block.named_children if not is_comment(c)]- inside = [s for s in stmts if not is_comment(s)]- return holder if code and inside and code[0] == inside[0] and code[-1] == inside[-1] else None--def section_heads(stmts: list[Node]) -> list[tuple[Node, list[str]]]:"""Each code statement of the span with the comment lines directly above it.diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex 3ffd826b5..4ed08d5d7 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -114,7 +114,12 @@ log = structlog.get_logger(__name__)# Not a licence to move a calibrated scoring weight — those are frozen# independently of this stamp.#-# Current stamp (v39): a Python module named like a test outside every test+# Current stamp (v40): an Extract Method plan names its helper with a placeholder+# (``extracted_helper``, numbered when taken in scope) and asks the agent applying+# it to rename it, so every stored plan's ``suggested_name``, header and call text+# change. Plan ids do not depend on the name and hold.+#+# v39: a Python module named like a test outside every test# directory is production code when the nearest pytest config's ``testpaths``# or ``python_files`` leaves it out (``core/test_selection.py``). Its# ``is_test`` flag flips, and the biomarkers and ``has_test_file`` now read that@@ -395,7 +400,7 @@ log = structlog.get_logger(__name__)# forms. Files that were counted untested and are not become tested, which# moves untested-hotspot findings and the scores that carry them, on every# language with a prefix or spec convention rather than Ruby alone.-HEALTH_ANALYZER_VERSION = 39+HEALTH_ANALYZER_VERSION = 40#: Function facts a finding inside the function carries in its details.diff --git a/packages/core/src/repowise/core/analysis/health/fix_first/build.py b/packages/core/src/repowise/core/analysis/health/fix_first/build.pyindex 258bdd6e5..1d106fd1a 100644--- a/packages/core/src/repowise/core/analysis/health/fix_first/build.py+++ b/packages/core/src/repowise/core/analysis/health/fix_first/build.py@@ -1091,20 +1091,14 @@ def _staged_title(sym: str, stages: int) -> str:def _span_title(plan: _RefactorPlan, lead_plan: Any) -> str:start, end = _span(lead_plan)- # With no suggested name the title drops "into ...": the step already says- # to name the helper for what the lines do, and a title never reads "<name>".- name = _plan_body(lead_plan).get("suggested_name") or ""+ # Titles never quote the helper name: it is a placeholder the step asks to rename.spanned = plan.lead_type == "extract_method" and bool(start and end)if spanned and magnitude(plan.rank.shape) >= SIZE_BREAK_UP:- return _break_up_title(plan.sym, plan.rank.shape, f"{start}-{end}", name)+ return _break_up_title(plan.sym, plan.rank.shape, f"{start}-{end}")template = text.REFACTOR_TITLE.get("extract_method_span" if spanned else plan.lead_type, "Refactor {file}")- if not name:- template = template.replace(" into {name}", "")- title = template.format(- sym=plan.sym, file=text.basename(plan.path), start=start, end=end, name=name- )+ title = template.format(sym=plan.sym, file=text.basename(plan.path), start=start, end=end)return _with_more_steps(plan, title)@@ -1114,18 +1108,11 @@ def _with_more_steps(plan: _RefactorPlan, title: str) -> str:return title-def _break_up_title(- sym: str, shape: Mapping[str, int], span: str, name: str, suffix: str = ""-) -> str:- # The helper's signature is in the step; the title keeps its name, or- # drops it when the problem, the span and the suffix fill the line.+def _break_up_title(sym: str, shape: Mapping[str, int], span: str, suffix: str = "") -> str:title = f"Start breaking up {sym} ({text.size_brief(shape)}): first lift lines {span}"- into = f" into {name}" if name else ""- if not suffix:- return title + into if len(title + into) <= text.TITLE_MAX else title# A caveat outranks the span and the size, which the step and why name anyway.head = f"Start breaking up {sym}"- for candidate in (title + into, title, f"{head} ({text.size_brief(shape)})", head):+ for candidate in (title, f"{head} ({text.size_brief(shape)})", head):if len(candidate + suffix) <= text.TITLE_MAX:return candidate + suffixreturn head + suffix@@ -1544,8 +1531,7 @@ def _led_title(where: str, shape: Mapping[str, int], plan: Any) -> str:if stages:return _staged_title(where, stages) + suffixstart, end = _span(plan)- name = body.get("suggested_name") or ""- return _break_up_title(where, shape, f"{start}-{end}", name, suffix)+ return _break_up_title(where, shape, f"{start}-{end}", suffix)def _finding_plan_fields(led: Any, path: str, finding_id: str | None) -> dict[str, Any]:diff --git a/packages/core/src/repowise/core/analysis/health/fix_first/text.py b/packages/core/src/repowise/core/analysis/health/fix_first/text.pyindex 797d02c22..f11403e7d 100644--- a/packages/core/src/repowise/core/analysis/health/fix_first/text.py+++ b/packages/core/src/repowise/core/analysis/health/fix_first/text.py@@ -64,7 +64,7 @@ FINDING_TITLE: dict[str, str] = {#: Imperative title for a composed refactoring, by its lead step's type.REFACTOR_TITLE: dict[str, str] = {"extract_method": "Extract a helper from {sym}",- "extract_method_span": "Extract lines {start}-{end} of {sym} into {name}",+ "extract_method_span": "Extract lines {start}-{end} of {sym}","extract_helper": "Replace the duplicated code in {sym} with one shared helper","extract_class": "Extract a class from {sym}","split_file": "Split {file} into smaller modules",diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/declarative.py b/packages/core/src/repowise/core/analysis/health/refactoring/declarative.pyindex 4c2c21d6e..9137eb073 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/declarative.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/declarative.py@@ -25,7 +25,7 @@ from typing import TYPE_CHECKING, Anyfrom ..complexity.ast_utils import _find_function_entry_namefrom ..complexity.nloc import is_string_stmt-from ..dataflow.effects import binding_target, bound_names, imported_names+from ..dataflow.bindings import binding_target, bound_names, imported_namesfrom ..dataflow.span import is_commentfrom .helper_naming import defined_namesdiff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.pyindex e573484e3..09975ab06 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@@ -46,12 +46,11 @@ no suggestion.Plan shape (open dict, no migration):- ``plan`` = ``{"span": {"start": int, "end": int}, "params": [str, ...],- "returns": [str, ...], "suggested_name": str | None}`` -- the lines to lift,- the inferred signature, and a deterministic starting name (see- ``helper_naming``): a ``timed()`` stage label, a banner comment, or- ``compute_<out>`` for an effect-free span with one informative OUT value.- ``None`` when nothing anchors a name, or when the name is already taken in- the scope the helper lands in.+ "returns": [str, ...], "suggested_name": str}`` -- the lines to lift, the+ inferred signature, and a placeholder name for the helper+ (``extracted_helper``, ``extracted_helper_2`` for the next one in the same+ scope; ``helper_naming.placeholder_names``) that the agent applying the+ plan replaces with a name for what the helper returns or does.- ``plan.needs_async`` -- the span awaits, so the helper is async and its callis awaited. An awaiting plan also carries ``async_host``: False when theenclosing function is not declared async, which makes the step a judgment@@ -74,8 +73,8 @@ Plan shape (open dict, no migration):"new_text": str}`` is the statement replacing the span (``render``), and``new_symbol.notes`` what they cannot say. Both texts are None when``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``).+ is not async. ``suggested_name`` is in the language's private form+ (Python ``_x``).- ``plan.anchors`` = ``{"first": str, "last": str}`` -- the exact text thespan starts and ends with, each unique in the function (``anchors``), so anagent finds it by text once earlier edits have moved its lines; every stage@@ -123,7 +122,7 @@ from ..scoring import severity_deductionfrom . import renderfrom .anchors import Scope, anchor_plan, file_source, function_scopefrom .declarative import declarative_flat-from .helper_naming import ScopeNames, helper_names, out_value_name+from .helper_naming import ScopeNames, placeholder_namesfrom .models import RefactoringContext, RefactoringSuggestionfrom .narrowing import narrowed, narrowingsfrom .registry import RefactoringDetector, register@@ -245,17 +244,15 @@ class ExtractMethodDetector(RefactoringDetector):if anchor_plan(split.plan, scope):out.append(split)return+ # The fallback span takes the first placeholder, not the next one.+ names.release(analysis, _claimed(split.plan))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")returnname = render.private_name(- ctx.language,- names.claim_first(- analysis,- helper_names(analysis, best, lmap, ctx.language, names.imports(fn_node)),- ),+ ctx.language, names.claim_first(analysis, placeholder_names(ctx.language)))async_fields = _async_fields(analysis, best, lmap, ctx.language)symbol = _render_fields(@@ -370,13 +367,6 @@ class ExtractMethodDetector(RefactoringDetector):best = max(best, (full * share, share, full, biomarker))return best[0], best[1], best[3]- @staticmethod- def _suggested_name(- analysis: FunctionAnalysis, extraction: Extraction, language: str | None = None- ) -> str | None:- """The OUT-value name alone (:func:`helper_naming.out_value_name`)."""- return out_value_name(analysis, extraction, language)-@staticmethoddef _confidence(extraction: Extraction, share: float) -> str:"""High when the extraction is unambiguous and worth handing off: a@@ -486,6 +476,12 @@ def _staged(return plan+def _claimed(plan: dict[str, Any]) -> list[str]:+ """The names a staged plan claimed: each stage's and the parameter object's."""+ obj = plan.get("parameter_object") or {}+ return [s["suggested_name"] for s in plan["stages"]] + ([obj["name"]] if obj else [])++def _staged_fields(analysis: FunctionAnalysis,staged: StagePlan,@@ -500,7 +496,6 @@ def _staged_fields(obj = _parameter_object(analysis, staged, dialect, language, names)# Without an object (no free variable name for it) the values stay plain.context = staged.context if obj else ()- imports = names.imports(analysis.fn_node)# The function's import goes with the last stage reading it, so the code# still runs when the stages before it are applied and tested alone.last = {@@ -509,10 +504,7 @@ def _staged_fields(stages = []for i, (x, reimports) in enumerate(zip(staged.stages, staged.imports, strict=True)):name = render.private_name(- language,- names.claim_first(- analysis, helper_names(analysis, x, lmap, language, imports, sections=True)- ),+ language, names.claim_first(analysis, placeholder_names(language)))carried = [p for p in x.params if p in context]own = replace(x, params=tuple(p for p in x.params if p not in context))diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/helper_naming.py b/packages/core/src/repowise/core/analysis/health/refactoring/helper_naming.pyindex f45e87ce3..030186a52 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/helper_naming.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/helper_naming.py@@ -1,14 +1,9 @@-"""The starting name an Extract Method plan gives the helper it asks you to write.+"""The name an Extract Method plan gives the helper it asks for: a placeholder.-Sources, in order: a ``timed(..., "label")`` stage label on the span, a banner-comment over it (the author's own name for the block), and the span's single-OUT value as ``compute_<out>``. An OUT name describes a value, not an action,-so it is never given to a span that acts outside itself (``dataflow.effects``);-nor is a banner that opens with a value verb (``_VALUE_VERBS``). Whatever the-source, a name a symbol in the helper's scope already uses is dropped. Without-any of them, or when each is taken, the helper is named for its host function-and the span's subject (:mod:`.span_subject`), so every plan carries a name to-edit rather than a blank.+The agent applying the plan names the helper for what it returns or does.+The placeholder (``extracted_helper`` in the language's casing, numbered when+taken where the helper lands) keeps the header and the call valid code until+then."""from __future__ import annotations@@ -18,28 +13,12 @@ from collections.abc import Iterable, Iteratorfrom typing import TYPE_CHECKING, Anyfrom ..complexity.ast_utils import _find_function_entry_name-from ..dataflow.effects import (- Ownership,- binding_target,- bound_names,- declared_names,- has_outside_effects,- imported_names,- owned_names,-)-from ..dataflow.span import enclosing_with, section_heads, span_statements-from .naming import banner_words, join_identifier, label_words, split_words-from .span_subject import host_words, subjects+from ..dataflow.bindings import binding_target, bound_names, imported_names+from .naming import join_identifierif TYPE_CHECKING:from ..complexity.languages import LanguageNodeMap- from ..dataflow import Extraction, FunctionAnalysis--# OUT values whose name describes the variable's role, not the block's-# product: ``compute_result`` names nothing the reader did not know.-_UNINFORMATIVE_OUT = frozenset(- {"out", "result", "results", "value", "values", "ret", "tmp", "temp", "data", "item"}-)+ from ..dataflow import FunctionAnalysis# How each language that reaches this detector joins the words of a helper# name. Only the languages the Extract Method slicer has a dialect for@@ -59,12 +38,7 @@ NAME_CONVENTION: dict[str, str] = {}_SNAKE_CASE = "snake_case"-# Verbs that promise a value. A banner opening with one over a span that acts-# outside itself names it the way an OUT name would, wrongly.-_VALUE_VERBS = frozenset({"compute", "calculate", "calc", "derive", "get", "build", "make"})--# Past this a name joining several sections reads as a sentence, not a name.-_MAX_JOINED_WORDS = 6+_PLACEHOLDER_WORDS = ["extracted", "helper"]# How far below a scope a sibling definition can sit: ``export const f = () =>``# is four levels under a TS module, a decorated Python method three under its@@ -72,141 +46,14 @@ _MAX_JOINED_WORDS = 6_SIBLING_DEPTH = 4-def out_value_name(- analysis: FunctionAnalysis, extraction: Extraction, language: str | None = None-) -> str | None:- """``compute_<out>`` for the slice's single informative OUT value, in- *language*'s identifier convention; ``None`` without one.-- A span whose single product is ``average`` is, by construction, the code- that computes it, so ``compute_average`` describes it without inferring- intent. Convention is per language: Python, Rust and C++ keep- ``compute_average``; Go, Java and the TypeScript/JavaScript family take- ``computeAverage``. The out value's own casing is kept as word boundaries,- so ``meanValue`` is ``computeMeanValue`` in Java, not ``compute_meanvalue``.- """- if len(extraction.returns) != 1:- return None- out_words = split_words(extraction.returns[0])- if not out_words:- return None- # ``_UNINFORMATIVE_OUT`` is keyed on the single-word slug, matching the- # names it holds (``meanValue`` is a product, ``result`` is a role).- if "_".join(out_words) in _UNINFORMATIVE_OUT:- return None- return join_identifier(["compute", *out_words], _convention(language))---def helper_name(- analysis: FunctionAnalysis,- extraction: Extraction,- lmap: LanguageNodeMap,- language: str | None,- modules: frozenset[str] = frozenset(),- *,- sections: bool = False,-) -> str | None:- """A deterministic starting name for the helper, before the collision- check, or ``None`` when nothing in the code anchors one. *modules* are the- file's imported names (:func:`dataflow.effects.imported_names`). With- *sections* (a staged plan's stage), a span running across several named- sections is named after all of them (:func:`_joined`)."""- stmts = span_statements(analysis.fn_node, extraction.start_line, extraction.end_line, lmap)- if not stmts:- return None- words = _anchored_words(stmts, lmap, sections=sections)- own = Ownership(- owned=owned_names(stmts, lmap),- declared=declared_names(analysis.fn_node, analysis.def_use, lmap),- modules=modules,- )- effects = extraction.needs_async or has_outside_effects(stmts, own, lmap)- if words and not (effects and words[0] in _VALUE_VERBS):- return join_identifier(words, _convention(language))- return None if effects else out_value_name(analysis, extraction, language)---def helper_names(- analysis: FunctionAnalysis,- extraction: Extraction,- lmap: LanguageNodeMap,- language: str | None,- modules: frozenset[str] = frozenset(),- *,- sections: bool = False,-) -> Iterator[str]:- """Starting names, best first: :func:`helper_name`, then the host function- qualified by each subject of the span (``render_card_directive``). Lazy, so- the subjects are read only when the anchored name is missing or taken.- *sections* as for :func:`helper_name`."""- anchored = helper_name(analysis, extraction, lmap, language, modules, sections=sections)- if anchored:- yield anchored- stmts = span_statements(analysis.fn_node, extraction.start_line, extraction.end_line, lmap)- host = host_words(analysis.name) or ["handle"]- for subject in subjects(stmts, extraction.returns, lmap):- # ``render_card`` about ``card`` is ``render_card``: the host's own name.- rest = subject[_overlap(host, subject) :]- if rest:- yield join_identifier([*host, *rest], _convention(language))- # A span with no subject (it only logs, say) is still a block of the host;- # numbered when that is taken too, so every plan ends with a free name.- yield join_identifier([*host, "block"], _convention(language))+def placeholder_names(language: str | None) -> Iterator[str]:+ """``extracted_helper``, ``extracted_helper_2``, ... (``extractedHelper``,+ ``extractedHelper2`` where the language writes camelCase): the first one+ free where the helper lands is its name (:meth:`ScopeNames.claim_first`)."""+ convention = NAME_CONVENTION.get(language or "", _SNAKE_CASE)+ yield join_identifier(_PLACEHOLDER_WORDS, convention)for n in itertools.count(2):- yield join_identifier([*host, "block", str(n)], _convention(language))---def _overlap(host: list[str], subject: list[str]) -> int:- """How many of *subject*'s first words repeat the tail of *host*."""- top = min(len(host), len(subject))- return next((n for n in range(top, 0, -1) if host[-n:] == subject[:n]), 0)---def _anchored_words(stmts: list[Any], lmap: LanguageNodeMap, *, sections: bool = False) -> list[str]:- """The words of the label or banner naming the span, ``[]`` without one.-- The span may be the whole body of ``with timed(...)``; else the label or- banner heads its first statement. A label or banner names only its own- section, so one heading a later top-level statement means the span runs- across sections, and neither names it alone: with *sections* the name- joins them when the first statement opens a section too, else it is ``[]``.- """- wrapper = enclosing_with(stmts, lmap)- if wrapper is not None and (label := _label(wrapper)):- return label- heads = [_label(stmt) or banner_words(comment) for stmt, comment in section_heads(stmts)]- # A later head means a second section starts inside the span.- if heads and not any(heads[1:]):- return heads[0]- return _joined([h for h in heads if h]) if sections and heads and heads[0] else []---def _joined(heads: list[list[str]]) -> list[str]:- """One name for the sections *heads* name: their shared leading words,- then each one's own words, the last after ``and`` (``persist_kg_and_git``).- ``[]`` when a section adds no words of its own or the name would run past- ``_MAX_JOINED_WORDS``."""- common = 0- while all(len(h) > common and h[common] == heads[0][common] for h in heads):- common += 1- tails: list[list[str]] = []- for head in heads:- if head[common:] not in tails:- tails.append(head[common:])- if any(not tail for tail in tails):- return []- words = list(heads[0][:common])- for n, tail in enumerate(tails):- words.extend(["and", *tail] if n and n == len(tails) - 1 else tail)- return words if len(words) <= _MAX_JOINED_WORDS else []---def _label(stmt: Any) -> list[str]:- return label_words((stmt.text or b"").decode("utf-8", "replace"))---def _convention(language: str | None) -> str:- return NAME_CONVENTION.get(language or "", _SNAKE_CASE)+ yield join_identifier([*_PLACEHOLDER_WORDS, str(n)], convention)def _key(name: str) -> str:@@ -216,16 +63,16 @@ def _key(name: str) -> str:class ScopeNames:- """The names already taken where each helper lands, so a suggested name+ """The names already taken where each helper lands, so a placeholdernever shadows a sibling or another plan's helper.A helper lands where its host function sits: a method's class, a nestedfunction's enclosing function, else the module. Taken there: the functionsdefined in it, the names it assigns, and at module level its imports; plusthe host's own parameters and locals, which the helper's call sits among.- A colliding name is dropped rather than suffixed (``compute_total_2`` says- nothing the reader can use), and the first plan in source order keeps it.- Go's package scope spans files; only this file's names are seen.+ A taken placeholder moves to the next number, and the first plan in source+ order keeps the lowest. Go's package scope spans files; only this file's+ names are seen.Names come from the tree, not ingestion symbols: ``RefactoringContext``carries no per-file symbol list, and the tree is already parsed.@@ -260,9 +107,18 @@ class ScopeNames:def claim_first(self, analysis: FunctionAnalysis, names: Iterable[str]) -> str | None:"""The first of *names* free in the helper's scope, claimed; ``None``- when every one is taken (:func:`helper_names` never runs out)."""+ when every one is taken (:func:`placeholder_names` never runs out)."""return next((name for name in names if self.claim(analysis, name)), None)+ def release(self, analysis: FunctionAnalysis, names: Iterable[str]) -> None:+ """Give back *names*, claimed for a plan that was not offered. Each was+ free when claimed, so none is a name the scope defines."""+ if analysis.fn_node is None:+ return+ taken = self._taken.get(_enclosing_scope(analysis.fn_node, self._lmap).id)+ if taken is not None:+ taken.difference_update(_key(name) for name in names)+def _scope_names(self, scope: Any) -> set[str]:names = {_key(n) for n in defined_names(scope, self._lmap)}if scope.parent is None:diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/models.py b/packages/core/src/repowise/core/analysis/health/refactoring/models.pyindex ffa808dbc..f6a699ce6 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/models.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/models.py@@ -50,10 +50,10 @@ For Extract Method:- ``plan`` = ``{"span": {"start": int, "end": int}, "params": [str, ...],"returns": [str, ...], "suggested_name": str | None, "needs_async": bool}``- — the lines to lift, the inferred signature, a deterministic starting name- (a stage label, a banner comment, or the single OUT value of an effect-free- span; never one already taken in the helper's scope; else absent), and- whether the span awaits, so the helper is async and its call awaited. An+ — the lines to lift, the inferred signature, a placeholder name the agent+ applying the plan renames (``extracted_helper``, numbered when taken in the+ helper's scope), and whether the span awaits, so the helper is async and its+ call awaited. Anawaiting plan adds ``"async_host": bool``, False when the enclosing functionis not async. ``new_symbol`` and ``call_site`` carry the helper's typedparameters, its header and its call, written out (``extract_method``).diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/naming.py b/packages/core/src/repowise/core/analysis/health/refactoring/naming.pyindex 9a99942c8..74df592ce 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/naming.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/naming.py@@ -1,69 +1,10 @@-"""Deterministic identifier names for the code a plan asks you to create.--Shared by the detectors that name a new unit (Extract Helper's shared helper,-Extract Method's lifted helper) so one rule produces every ``suggested_name``-in the payload. The alternative — each detector slugging its own way — is how a-consumer ends up unable to say what a name means without knowing which detector-wrote it, which is the defect this module exists to not repeat.--Precision-first, and the same posture in both detectors: without semantics we-cannot name a block for what it *does*, so a name is anchored to something the-plan already knows for certain (where the helper lands, the value it produces,-or the name its author already wrote over it: a banner comment, a stage label)-and never guesses intent. It is an editable starting point, which is-how every surface frames it, not a claim about behaviour.+"""Identifier words: split a name into its words, and join words in a+language's casing. Shared by the plan renderer (a parameter object's type+name) and Extract Method's placeholder helper name."""from __future__ import annotations-import re--# A section banner names its block in a few words; a longer comment is an-# explanation, and a name built from it is a sentence.-_MAX_BANNER_WORDS = 5-_COMMENT_MARK = re.compile(r"^\s*(?:#+|//+|/\*+|\*+)|\*+/\s*$")-# Rules and separators drawn around a banner: ``# ---- Graph metrics ----``.-_RULE_CHARS = " \t-=~#*_+.─━═"-_ENUMERATION = re.compile(r"^(?:\d+[.)]|\[\d+\]|(?:step|pass)\s+\d+\s*[:.)])\s*", re.IGNORECASE)-_PARENTHETICAL = re.compile(r"\([^)]*\)")-# Editor folding markers around a section: ``# region Load edges``,-# ``// #endregion``, ``// <editor-fold desc="Load edges">``.-_FOLD = re.compile(r'^(?:(?:end)?region\b|</?editor-fold(?:[^>]*desc="([^"]*)")?[^>]*>)\s*', re.I)-_BANNER_WORD = re.compile(r"[A-Za-z][A-Za-z0-9]*(?:-[A-Za-z0-9]+)*")-# Comments that talk to a tool or a reviewer, not about the code below them.-_DIRECTIVES = frozenset(- {"todo", "fixme", "xxx", "hack", "note", "noqa", "nosec", "pragma"}- | {"eslint", "prettier", "istanbul", "c8", "biome", "nolint", "noinspection", "jshint"}-)-_ARTICLES = frozenset({"a", "an", "the"})-# ``with timed(timings, "persist.pages"):`` -- the stage label the timing-# helper already records for the block it opens.-_TIMED_LABEL = re.compile(r"\btimed\(\s*[^,()]+,\s*[\"']([A-Za-z_][\w.]*)[\"']")---def identifier_slug(label: str | None) -> str:- """*label* reduced to a lowercase identifier-safe slug, or ``""``.-- Non-alphanumerics collapse to single underscores, so a path leaf like- ``api-client`` becomes ``api_client``. A leading digit is prefixed with an- underscore because it is not a valid identifier start in most languages.- """- if not label:- return ""- cleaned: list[str] = []- prev_us = False- for ch in label.lower():- if ch.isalnum():- cleaned.append(ch)- prev_us = False- elif not prev_us:- cleaned.append("_")- prev_us = True- slug = "".join(cleaned).strip("_")- if slug and slug[0].isdigit():- slug = f"_{slug}"- return slug-def _starts_new_word(ch: str, current: list[str]) -> bool:"""True when *ch* opens a new word after the letters collected in *current*.@@ -90,7 +31,7 @@ def split_words(label: str | None) -> list[str]:Letters are tested with ``str.isalnum`` rather than an ASCII character class,so a non-ASCII identifier keeps its characters instead of losing them to a- dropped word, the same way ``identifier_slug`` treats them.+ dropped word."""if not label:return []@@ -114,39 +55,3 @@ def join_identifier(words: list[str], convention: str) -> str:head, *rest = wordsreturn head + "".join(w.capitalize() for w in rest)return "_".join(words)---def banner_words(comment_lines: list[str]) -> list[str]:- """The words of a section banner, or ``[]`` when the comment is not one.-- A banner is one line of short prose, optionally drawn between rules- (``# ==== / # Environment / # ====`` or ``# -- Load edges --``), with a- leading step number and any editor folding marker (``# region``) dropped. Two to ``_MAX_BANNER_WORDS`` plain words: one- word is a heading (``# Decisions``), not a name for what the block does,- and anything holding code, paths or punctuation (``# key -> value``) is- prose about the code rather than its name.- """- content = []- for line in comment_lines:- text = _COMMENT_MARK.sub("", line).strip(_RULE_CHARS)- text = _FOLD.sub(lambda m: m.group(1) or "", text).strip(_RULE_CHARS)- if text:- content.append(text)- if len(content) != 1:- return []- text = _ENUMERATION.sub("", _PARENTHETICAL.sub("", content[0]).strip())- tokens = text.strip().rstrip(".:").split()- if not 2 <= len(tokens) <= _MAX_BANNER_WORDS:- return []- if not all(_BANNER_WORD.fullmatch(t) for t in tokens):- return []- if tokens[0].lower().split("-")[0] in _DIRECTIVES:- return []- return [w for t in tokens for w in split_words(t) if w not in _ARTICLES]---def label_words(statement_text: str) -> list[str]:- """The words of a ``timed(..., "label")`` stage label opening a statement."""- first_line = statement_text.split("\n", 1)[0]- match = _TIMED_LABEL.search(first_line)- return split_words(match.group(1)) if match else []diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recipe.py b/packages/core/src/repowise/core/analysis/health/refactoring/recipe.pyindex 02a896f59..bb530e83f 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/recipe.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recipe.py@@ -14,6 +14,7 @@ older row yields a shorter recipe rather than an error.from __future__ import annotations+import refrom collections.abc import Callable, Mappingfrom typing import Any, Literal, get_args@@ -130,7 +131,7 @@ def _extract_method(d: Mapping[str, Any], plan: Mapping[str, Any]) -> list[Step]stages = [_dict(stage) for stage in _list(plan.get("stages"))]if stages:return _staged_steps(d, plan, stages)- return [_extract_step(d, plan)]+ return [_extract_step(d, plan, note=_rename_note(plan, 1))]def _staged_steps(@@ -157,13 +158,38 @@ def _staged_steps(}steps.append(_step("add_helper", d.get("file_path"), None, text, new_symbol=symbol))for n, stage in enumerate(stages, 1):- step = _extract_step(d, stage)+ note = _rename_note(stage, len(stages)) if n == 1 else None+ step = _extract_step(d, stage, note=note)step["text"] = f"Stage {n} of {len(stages)}: {step['text']}"steps.append(step)return steps-def _extract_step(d: Mapping[str, Any], plan: Mapping[str, Any]) -> Step:+#: Said once per Extract Method plan whose helper names are placeholders.+RENAME_NOTE = (+ "The helper's name is a placeholder: rename it for what it returns or does, "+ "in its header and its call."+)+_RENAME_EACH = RENAME_NOTE.replace("The helper's name", "Each stage's helper name").replace(+ "rename it", "rename each one"+)+#: The placeholder ``helper_naming.placeholder_names`` writes, in any casing.+_PLACEHOLDER = re.compile(r"_?extracted_?[hH]elper_?\d*")+++def _rename_note(plan: Mapping[str, Any], helpers: int) -> str | None:+ """The rename note for a plan of *helpers* helpers, None when the stored+ name is a real one (a plan written before names were placeholders)."""+ name = plan.get("suggested_name")+ if name and not _PLACEHOLDER.fullmatch(str(name)):+ return None+ return RENAME_NOTE if helpers == 1 else _RENAME_EACH+++def _extract_step(+ d: Mapping[str, Any], plan: Mapping[str, Any], *, note: str | None = None+) -> Step:+ """One extract step, ending with *note* when given (:func:`_rename_note`)."""span = _dict(plan.get("span"))where = _span(span.get("start"), span.get("end"))host = _short(d.get("target_symbol"))@@ -173,11 +199,6 @@ def _extract_step(d: Mapping[str, Any], plan: Mapping[str, Any]) -> Step:return _step("extract", d.get("file_path"), None, text)symbol = _dict(plan.get("new_symbol"))is_async = bool(symbol.get("async", plan.get("needs_async")))- named = (- " (a starting name; rename it if it collides)"- if plan.get("suggested_name")- else " (name it for what the lines do)"- )anchors = plan_anchors(plan.get("anchors"))lines = (f"the span of `{host}` that starts and ends with the lines shown "@@ -186,9 +207,11 @@ def _extract_step(d: Mapping[str, Any], plan: Mapping[str, Any]) -> Step:else f"lines {where['start']}-{where['end']} of `{host}`")text = (- f"Move {lines} into a new helper `{name}`{named} in the same scope, and replace "+ f"Move {lines} into a new helper `{name}` in the same scope, and replace "f"{'it' if anchors else 'them'} with one call to it.")+ if note:+ text += " " + notereturn _step("extract",d.get("file_path"),@@ -686,6 +709,7 @@ __all__ = ["LINE_RULE","PRECONDITION_KINDS","RECIPE_ACTIONS",+ "RENAME_NOTE","SCRIPT_RULE","TYPE_LABEL","RecipeAction",diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/span_subject.py b/packages/core/src/repowise/core/analysis/health/refactoring/span_subject.pydeleted file mode 100644index 96b55e972..000000000--- a/packages/core/src/repowise/core/analysis/health/refactoring/span_subject.py+++ /dev/null@@ -1,185 +0,0 @@-"""What an Extract Method span is about, read off its code, for the helper's name.--The last naming source, after a stage label, a banner and ``compute_<out>``-(:mod:`.helper_naming`): the host function's name qualified by the span's-subject, ``render_card`` + ``directive`` -> ``render_card_directive``. Both-halves are facts the plan holds, so the name says where the helper came from-and what it handles without guessing a verb for what it does.--The subject, first found: the span's single OUT value; the condition of the-``if`` arm or the target of the loop whose whole body the span is; then for-each of the span's statements in order, an ``if`` condition's subject (a string-key or compared literal, else the last name read), a loop's iterable, the-first name a statement binds, or a dropped call's name. Role words (``result``,-``self``) and one-letter names say nothing and are skipped.-"""--from __future__ import annotations--import re-from typing import TYPE_CHECKING, Any--from ..dataflow.effects import binding_target, bound_names-from ..dataflow.span import body_holder, is_comment-from .naming import split_words--if TYPE_CHECKING:- from ..complexity.languages import LanguageNodeMap--# Names that describe a role or a receiver, not what a block handles.-_ROLE_WORDS = frozenset(- {"out", "result", "results", "value", "values", "ret", "tmp", "temp", "data", "item"}- | {"self", "this", "cls", "none", "null", "undefined", "true", "false", "args", "kwargs"}- # ``typeof x === "number"`` compares a type name, not the subject.- | {"number", "string", "boolean", "object", "function", "bigint", "symbol"}-)-# A dropped call to one of these adds to something; the call's name says-# nothing about what (``out.append(...)``), so the next statement is read.-_GENERIC_CALLS = frozenset(- {"append", "push", "add", "extend", "insert", "update", "set", "write", "print", "echo"}- | {"log", "info", "debug", "warning", "warn", "error", "emit"}-)-# Calls that pass their subject through: ``card.get("owner")`` is about-# ``owner``, ``enumerate(groups)`` about ``groups``. ``_GENERIC_CALLS`` do too.-_PASS_THROUGH = frozenset(- {"get", "items", "keys", "values", "enumerate", "sorted", "reversed", "list", "tuple"}- | {"len", "iter", "getattr", "isinstance", "bool", "str", "int", "object", "array"}-)-_MEMBER_FIELDS = ("attribute", "property", "field")-_CALLEE_FIELDS = ("function", "callee")-_LOOP_SOURCE_FIELDS = ("right", "value", "iterable", "condition")-_PLAIN_NAME = re.compile(r"[A-Za-z_$][\w$]*")-_MAX_DEPTH = 8---def host_words(name: str) -> list[str]:- """The host function's name as words; ``[]`` for an anonymous or dotted one."""- return split_words(name) if _PLAIN_NAME.fullmatch(name or "") else []---def subjects(stmts: list[Any], returns: tuple[str, ...], lmap: LanguageNodeMap) -> list[list[str]]:- """The span's subjects, best first, each as words, without repeats."""- found: list[list[str]] = []- if len(returns) == 1:- found.append(_words(returns[0]))- found.append(_enclosing_subject(stmts, lmap))- code = [s for s in stmts if not is_comment(s)]- for stmt in code:- found.append(_statement_subject(stmt, lmap))- if stmt.type in lmap.loop_kinds:- # Over the host's own subject, the element is what the span handles.- found.append(_expr_words(stmt.child_by_field_name("left"), 0))- out: list[list[str]] = []- for words in found:- if words and words not in out:- out.append(words)- return out---def _words(text: str) -> list[str]:- words = split_words(text)- if not words or "_".join(words) in _ROLE_WORDS or all(len(w) == 1 for w in words):- return []- return words---def _enclosing_subject(stmts: list[Any], lmap: LanguageNodeMap) -> list[str]:- """The subject of the ``if`` arm or loop whose whole body *stmts* is."""- holder = body_holder(stmts)- if holder is None:- return []- if holder.type in lmap.loop_kinds:- return _expr_words(holder.child_by_field_name("left"), 0)- return _expr_words(holder.child_by_field_name("condition"), 0)---def _statement_subject(stmt: Any, lmap: LanguageNodeMap) -> list[str]:- kind = stmt.type- if kind in lmap.if_kinds:- return _expr_words(stmt.child_by_field_name("condition"), 0)- if kind in lmap.loop_kinds:- return _expr_words(_child(stmt, _LOOP_SOURCE_FIELDS), 0)- if kind in lmap.try_kinds or kind in lmap.with_kinds:- return _wrapper_subject(stmt, lmap)- expr = stmt.named_children[0] if stmt.named_child_count == 1 else stmt- if expr.type in lmap.await_kinds | {"await_expression"} and expr.named_child_count == 1:- expr = expr.named_children[0]- bound = _bound_subject(expr, lmap)- if bound is not None:- return bound- if expr.type not in lmap.call_kinds or _generic(_callee_words(expr, 0)):- # ``out.append(...)`` says nothing about what is added: read on.- return []- return _expr_words(expr, 0)---def _wrapper_subject(stmt: Any, lmap: LanguageNodeMap) -> list[str]:- """A ``try`` or ``with`` is about what its body opens with."""- body = stmt.child_by_field_name("body") or next(- (c for c in stmt.named_children if c.type in lmap.block_kinds), None- )- first = next((c for c in body.named_children if not is_comment(c)), None) if body else None- return _statement_subject(first, lmap) if first is not None else []---def _bound_subject(expr: Any, lmap: LanguageNodeMap) -> list[str] | None:- """``x = ...`` is about ``x``, ``state.registry = ...`` about ``registry``;- ``None`` when *expr* binds nothing."""- holders = [expr, *expr.named_children]- target = next((t for h in holders if (t := binding_target(h, lmap)) is not None), None)- if target is None:- return None- names = bound_names(target)- return _words(names[0]) if names else _expr_words(target, 0)---def _expr_words(node: Any, depth: int) -> list[str]:- """The name an expression is about (module docstring)."""- if node is None or depth > _MAX_DEPTH:- return []- if "string" in node.type:- return _literal_words(node)- if not node.named_children:- text = (node.text or b"").decode("utf-8", "replace")- return _words(text) if _PLAIN_NAME.fullmatch(text) else []- if node.type in ("call", "call_expression"):- return _call_words(node, depth)- member = _child(node, _MEMBER_FIELDS)- # A member names its field; otherwise a compared key, then the first operand.- keys = [c for c in node.named_children if "string" in c.type]- parts = [member] if member is not None else [*keys, *node.named_children]- return next((w for c in parts if (w := _expr_words(c, depth + 1))), [])---def _callee_words(call: Any, depth: int) -> list[str]:- return _expr_words(_child(call, _CALLEE_FIELDS), depth + 1)---def _generic(words: list[str]) -> bool:- return "_".join(words) in _GENERIC_CALLS---def _call_words(call: Any, depth: int) -> list[str]:- """A call is about its name, or, when the name only passes a value on- (``get``, ``len``, ``append``), its first argument, then its receiver."""- name = _callee_words(call, depth)- if name and not _generic(name) and "_".join(name) not in _PASS_THROUGH:- return name- callee = _child(call, _CALLEE_FIELDS)- args = call.child_by_field_name("arguments")- first = next((a for a in args.named_children if not is_comment(a)), None) if args else None- receiver = _child(callee, ("object", "value")) if callee is not None else None- return next((w for c in (first, receiver) if (w := _expr_words(c, depth + 1))), [])---def _child(node: Any, fields: tuple[str, ...]) -> Any:- return next((c for f in fields if (c := node.child_by_field_name(f)) is not None), None)---def _literal_words(literal: Any) -> list[str]:- """A string literal that is a plain key (``"recent_owner"``), as words."""- text = (literal.text or b"").decode("utf-8", "replace").strip("'\"`")- return _words(text) if _PLAIN_NAME.fullmatch(text) else []---__all__ = ["host_words", "subjects"]diff --git a/packages/ui/__tests__/health/refactoring-anchor-prompt.test.ts b/packages/ui/__tests__/health/refactoring-anchor-prompt.test.tsindex ae0de86df..55a22b4cd 100644--- a/packages/ui/__tests__/health/refactoring-anchor-prompt.test.ts+++ b/packages/ui/__tests__/health/refactoring-anchor-prompt.test.ts@@ -9,6 +9,7 @@ import type { RefactoringPlan } from "@repowise-dev/types/refactoring";import { buildRefactoringPlanPrompt } from "../../src/health/ai-prompt-builder";import {LINE_RULE_TEXT,+ RENAME_NOTE_TEXT,SCRIPT_RULE_TEXT,} from "../../src/health/ai-prompts/refactoring-plan-steps";@@ -85,6 +86,25 @@ describe("Extract Method anchors", () => {expect(prompt).not.toContain(LINE_RULE_TEXT);});+ it("says once that a placeholder name is to be renamed", () => {+ const note =+ "The helper's name is a placeholder: rename it for what it returns or does, in its header and its call.";+ expect(RENAME_NOTE_TEXT).toBe(note);+ const named = (name: string, extra: Record<string, unknown> = {}) =>+ buildRefactoringPlanPrompt({ plan: plan({ suggested_name: name, ...extra }) });+ expect(named("_extracted_helper").split(note).length - 1).toBe(1);+ // A staged plan's prompt shows stage 1 and says it once too.+ const staged = named("_extracted_helper", {+ stages: [+ { span: { start: 120, end: 130 }, suggested_name: "_extracted_helper" },+ { span: { start: 131, end: 140 }, suggested_name: "_extracted_helper_2" },+ ],+ });+ expect(staged.split(note).length - 1).toBe(1);+ // A plan stored with a real name does not call it a placeholder.+ expect(named("_sum_rows")).not.toContain(note);+ });+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({diff --git a/packages/ui/__tests__/refactoring/plan-payload-namespaces.test.ts b/packages/ui/__tests__/refactoring/plan-payload-namespaces.test.tsindex 065142762..8a97de679 100644--- a/packages/ui/__tests__/refactoring/plan-payload-namespaces.test.ts+++ b/packages/ui/__tests__/refactoring/plan-payload-namespaces.test.ts@@ -85,15 +85,17 @@ describe("helperSite namespace", () => {});describe("extract_method suggested_name reaches the rendered prompt", () => {- it("uses the computed name instead of the generic fallback", () => {- const prompt = buildRefactoringPlanPrompt({ plan: methodPlan("compute_average") });- expect(prompt).toContain("compute_average");+ it("uses the plan's placeholder and asks the agent to rename it", () => {+ const prompt = buildRefactoringPlanPrompt({ plan: methodPlan("_extracted_helper") });+ expect(prompt).toContain("into `_extracted_helper`:");+ expect(prompt).toContain("The helper's name is a placeholder: rename it");expect(prompt).not.toContain("a clearly named helper");});- it("asks the agent to fill the name placeholder when no name was anchored", () => {+ it("asks the agent to name a helper stored without a name", () => {const prompt = buildRefactoringPlanPrompt({ plan: methodPlan(null) });- expect(prompt).toContain("`<name>` (name it for what the lines do)");+ expect(prompt).toContain("into `<name>`:");+ expect(prompt).toContain("The helper's name is a placeholder: rename it");expect(extractMethodPlan(methodPlan(null)).suggested_name).toBeNull();});diff --git a/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts b/packages/ui/src/health/ai-prompts/refactoring-plan-steps.tsindex 4322556b5..9d29e373d 100644--- a/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts+++ b/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts@@ -63,12 +63,17 @@ function extractHelperSteps(plan: RefactoringPlan): string {}/** 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). */+ * (`recipe.SCRIPT_RULE`, `LINE_RULE`, `ELSEWHERE_NOTE`, `RENAME_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 = "Text repeats in the file: edit only inside this function.";+export const RENAME_NOTE_TEXT =+ "The helper's name is a placeholder: rename it for what it returns or does, in its header and its call.";+/** The placeholder core writes (`helper_naming.placeholder_names`), in any casing. */+const HELPER_PLACEHOLDER = /^_?extracted_?[hH]elper_?\d*$/;interface SpanAnchors {first: string;@@ -137,7 +142,7 @@ function extractMethodSteps(plan: RefactoringPlan): string {? `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 ${what} into \`${name}\`${em.suggested_name ? "" : " (name it for what the lines do)"}:`,+ `Extract ${what} into \`${name}\`:`,"",...rendered,`- **Parameters (in):** ${params}`,@@ -150,6 +155,8 @@ 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.",+ // A plan stored before names were placeholders keeps its real name unflagged.+ ...(!em.suggested_name || HELPER_PLACEHOLDER.test(em.suggested_name) ? [RENAME_NOTE_TEXT] : []),anchors ? `${SCRIPT_RULE_TEXT} ${LINE_RULE_TEXT}` : SCRIPT_RULE_TEXT,].join("\n");}diff --git a/tests/fixtures/agent_prompts/golden.json b/tests/fixtures/agent_prompts/golden.jsonindex c6709ca5c..29502a65f 100644--- a/tests/fixtures/agent_prompts/golden.json+++ b/tests/fixtures/agent_prompts/golden.json@@ -59,16 +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- **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."+ "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 `_extracted_helper`.\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 `_extracted_helper` in the same scope, and replace them with one call to it. The helper's name is a placeholder: rename it for what it returns or does, in its header and its call. (`src/loader.py:61-78`)\n - New helper: `async def _extracted_helper(self, path: Path, strict) -> <type>:`\n - Replace lines 61-78 with: `config = await self._extracted_helper(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 `_extracted_helper`.\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 `_extracted_helper` in the same scope, and replace them with one call to it. The helper's name is a placeholder: rename it for what it returns or does, in its header and its call. (`src/loader.py:61-78`)\n - New helper: `async def _extracted_helper(self, path: Path, strict) -> <type>:`\n - Replace lines 61-78 with: `config = await self._extracted_helper(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 `_extracted_helper`.\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 `_extracted_helper` in the same scope, and replace them with one call to it. The helper's name is a placeholder: rename it for what it returns or does, in its header and its call. (`src/loader.py:61-78`)\n - New helper: `async def _extracted_helper(self, path: Path, strict) -> <type>:`\n - Replace lines 61-78 with: `config = await self._extracted_helper(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 `_extracted_helper`.\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 `_extracted_helper` in the same scope, and replace them with one call to it. The helper's name is a placeholder: rename it for what it returns or does, in its header and its call. (`src/loader.py:61-78`)\n - New helper: `async def _extracted_helper(self, path: Path, strict) -> <type>:`\n - Replace lines 61-78 with: `config = await self._extracted_helper(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."+ "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 `_extracted_helper` in the same scope, and replace it with one call to it. Each stage's helper name is a placeholder: rename each one for what it returns or does, in its header and its call. (`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 _extracted_helper(rows):`\n - End the helper with: `return totals`\n - Replace the span with: `totals = _extracted_helper(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 `_extracted_helper_2` 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 _extracted_helper_2(totals):`\n - End the helper with: `return out`\n - Replace the span with: `out = _extracted_helper_2(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 `_extracted_helper` in the same scope, and replace it with one call to it. Each stage's helper name is a placeholder: rename each one for what it returns or does, in its header and its call. (`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 _extracted_helper(rows):`\n - End the helper with: `return totals`\n - Replace the span with: `totals = _extracted_helper(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 `_extracted_helper_2` 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 _extracted_helper_2(totals):`\n - End the helper with: `return out`\n - Replace the span with: `out = _extracted_helper_2(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 `_extracted_helper` in the same scope, and replace it with one call to it. Each stage's helper name is a placeholder: rename each one for what it returns or does, in its header and its call. (`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 _extracted_helper(rows):`\n - End the helper with: `return totals`\n - Replace the span with: `totals = _extracted_helper(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 `_extracted_helper_2` 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 _extracted_helper_2(totals):`\n - End the helper with: `return out`\n - Replace the span with: `out = _extracted_helper_2(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 `_extracted_helper` in the same scope, and replace it with one call to it. Each stage's helper name is a placeholder: rename each one for what it returns or does, in its header and its call. (`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 _extracted_helper(rows):`\n - End the helper with: `return totals`\n - Replace the span with: `totals = _extracted_helper(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 `_extracted_helper_2` 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 _extracted_helper_2(totals):`\n - End the helper with: `return out`\n - Replace the span with: `out = _extracted_helper_2(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.",@@ -96,8 +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.**\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.",+ "extract_method_typed": "## Extract Method\nExtract lines 61-78 of `Loader.load` into `_extracted_helper`.\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 `_extracted_helper` in the same scope, and replace them with one call to it. The helper's name is a placeholder: rename it for what it returns or does, in its header and its call. (`src/loader.py:61-78`)\n - New helper: `async def _extracted_helper(self, path: Path, strict) -> <type>:`\n - Replace lines 61-78 with: `config = await self._extracted_helper(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 `_extracted_helper` in the same scope, and replace it with one call to it. Each stage's helper name is a placeholder: rename each one for what it returns or does, in its header and its call. (`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 _extracted_helper(rows):`\n - End the helper with: `return totals`\n - Replace the span with: `totals = _extracted_helper(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 `_extracted_helper_2` 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 _extracted_helper_2(totals):`\n - End the helper with: `return out`\n - Replace the span with: `out = _extracted_helper_2(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.**",@@ -105,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- **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."+ "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>` in the same scope, and replace them with one call to it. The helper's name is a placeholder: rename it for what it returns or does, in its header and its call. (`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>` in the same scope, and replace them with one call to it. The helper's name is a placeholder: rename it for what it returns or does, in its header and its call. (`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>` in the same scope, and replace them with one call to it. The helper's name is a placeholder: rename it for what it returns or does, in its header and its call. (`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>` in the same scope, and replace them with one call to it. The helper's name is a placeholder: rename it for what it returns or does, in its header and its call. (`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.jsonindex f1d100c4a..eb3bd2755 100644--- a/tests/fixtures/agent_prompts/refactoring.json+++ b/tests/fixtures/agent_prompts/refactoring.json@@ -22,7 +22,7 @@"returns": ["config"],- "suggested_name": "_read_config",+ "suggested_name": "_extracted_helper","needs_async": true,"async_host": true,"new_symbol": {@@ -48,7 +48,7 @@"type": "<type>"}],- "signature_text": "async def _read_config(self, path: Path, strict) -> <type>:",+ "signature_text": "async def _extracted_helper(self, path: Path, strict) -> <type>:","notes": ["The return type is not named in the code."]@@ -58,7 +58,7 @@"start": 61,"end": 78},- "new_text": "config = await self._read_config(path, strict)"+ "new_text": "config = await self._extracted_helper(path, strict)"}},"evidence": {@@ -134,7 +134,7 @@"returns": ["totals"],- "suggested_name": "_sum_rows",+ "suggested_name": "_extracted_helper","needs_async": false,"new_symbol": {"kind": "function",@@ -155,7 +155,7 @@"type": null}],- "signature_text": "def _sum_rows(rows):",+ "signature_text": "def _extracted_helper(rows):","return_text": "return totals"},"call_site": {@@ -163,7 +163,7 @@"start": 14,"end": 30},- "new_text": "totals = _sum_rows(rows)"+ "new_text": "totals = _extracted_helper(rows)"},"anchors": {"first": " for row in rows:",@@ -181,7 +181,7 @@"returns": ["totals"],- "suggested_name": "_sum_rows",+ "suggested_name": "_extracted_helper","needs_async": false,"new_symbol": {"kind": "function",@@ -202,7 +202,7 @@"type": null}],- "signature_text": "def _sum_rows(rows):",+ "signature_text": "def _extracted_helper(rows):","return_text": "return totals"},"call_site": {@@ -210,7 +210,7 @@"start": 14,"end": 30},- "new_text": "totals = _sum_rows(rows)"+ "new_text": "totals = _extracted_helper(rows)"},"anchors": {"first": " for row in rows:",@@ -231,7 +231,7 @@"returns": ["out"],- "suggested_name": "_format_totals",+ "suggested_name": "_extracted_helper_2","needs_async": false,"new_symbol": {"kind": "function",@@ -252,7 +252,7 @@"type": null}],- "signature_text": "def _format_totals(totals):",+ "signature_text": "def _extracted_helper_2(totals):","return_text": "return out"},"call_site": {@@ -260,7 +260,7 @@"start": 32,"end": 51},- "new_text": "out = _format_totals(totals)"+ "new_text": "out = _extracted_helper_2(totals)"},"anchors": {"first": " if not totals:\n return None",diff --git a/tests/unit/cli/test_health_cmd_controls.py b/tests/unit/cli/test_health_cmd_controls.pyindex 8bb27df09..0eca4d365 100644--- a/tests/unit/cli/test_health_cmd_controls.py+++ b/tests/unit/cli/test_health_cmd_controls.py@@ -129,6 +129,6 @@ def test_the_report_leads_with_fix_first() -> None:assert out.startswith("\nFix first (3 of 3 eligible")# The growing, reachable database loop leads; the refactor follows.assert " 1. Batch the database calls loops make through load_all " in out- assert " 2. Start breaking up run (CCN 44, 50 lines): first lift lines 20-35 into sum_rows " in out+ assert " 2. Start breaking up run (CCN 44, 50 lines): first lift lines 20-35 " in outassert "src/core.py:20" in outassert "verify: pytest tests/test_core_0.py" in outdiff --git a/tests/unit/health/test_extract_method_render.py b/tests/unit/health/test_extract_method_render.pyindex a3a180857..3cefc9f09 100644--- a/tests/unit/health/test_extract_method_render.py+++ b/tests/unit/health/test_extract_method_render.py@@ -99,13 +99,13 @@ def test_python_plan_carries_an_awaited_method_header_and_call():plan = _py_plan()sym = plan["new_symbol"]# No label or banner: named for the host and the value it returns.- assert plan["suggested_name"] == "_run_total"+ assert plan["suggested_name"] == "_extracted_helper"assert sym["signature_text"] == (- "async def _run_total(self, items: list[int], limit: int) -> int:"+ "async def _extracted_helper(self, items: list[int], limit: int) -> int:")assert plan["call_site"] == {"replace_span": plan["span"],- "new_text": "total = await self._run_total(items, limit)",+ "new_text": "total = await self._extracted_helper(items, limit)",}# The receiver is not a parameter of a method.assert sym["params"] == [@@ -117,7 +117,7 @@ def test_python_plan_carries_an_awaited_method_header_and_call():def test_a_span_that_does_not_await_is_not_awaited():plan = _py_plan("print(-i)")- assert plan["new_symbol"]["signature_text"].startswith("def _run_total(items: list[int]")+ assert plan["new_symbol"]["signature_text"].startswith("def _extracted_helper(items: list[int]")assert "await" not in plan["call_site"]["new_text"]diff --git a/tests/unit/health/test_extract_method_stages.py b/tests/unit/health/test_extract_method_stages.pyindex 71d152d89..d527231fc 100644--- a/tests/unit/health/test_extract_method_stages.py+++ b/tests/unit/health/test_extract_method_stages.py@@ -133,12 +133,15 @@ def test_persistence_shape_yields_a_staged_plan():)-def test_stage_names_come_from_timed_labels_and_banners():- stages = _plans(_persist(sections=8, extend=()))["persist"].plan["stages"]- # A stage covering one section takes its label; one spanning two is named- # for the host and its subject.- for stage in stages:- assert stage["suggested_name"].startswith("_persist_")+def test_stage_names_are_numbered_placeholders():+ plan = _plans(_persist(sections=8, extend=()))["persist"].plan+ names = [stage["suggested_name"] for stage in plan["stages"]]+ # Labels and banners name nothing: the agent applying the plan names each.+ assert names == ["_extracted_helper"] + [f"_extracted_helper_{n}" for n in range(2, len(names) + 1)]+ for stage in plan["stages"]:+ name = stage["suggested_name"]+ assert stage["new_symbol"]["signature_text"].startswith(f"async def {name}(")+ assert f"await {name}(" in stage["call_site"]["new_text"]def test_shared_values_travel_on_a_parameter_object():@@ -670,20 +673,6 @@ def test_a_loop_body_is_cut_and_the_loop_stays_in_the_function():residual = plan.plan["orchestrator"]# The loop's own decision point stays with the function.assert residual["ccn_after"] >= 2- # A stage running across two banners is named after both.- assert "_handle_gamma_and_delta" in [s["suggested_name"] for s in plan.plan["stages"]]---def test_a_name_joining_sections_keeps_shared_words_once():- from repowise.core.analysis.health.refactoring.helper_naming import _joined-- assert _joined([["persist", "kg"], ["persist", "git"]]) == ["persist", "kg", "and", "git"]- assert _joined([["persist", "kg"], ["persist", "git"], ["persist", "decisions"]]) == [- "persist", "kg", "git", "and", "decisions"- ]- # A section adding no words of its own, or a name past six words, gives none.- assert _joined([["load", "config"], ["load"]]) == []- assert _joined([["load", "the", "pages"], ["sweep", "old", "rows"]]) == []def test_a_value_the_next_iteration_reads_comes_back_out_of_its_stage():diff --git a/tests/unit/health/test_fix_first_build.py b/tests/unit/health/test_fix_first_build.pyindex 2f7b8002e..4ef216239 100644--- a/tests/unit/health/test_fix_first_build.py+++ b/tests/unit/health/test_fix_first_build.py@@ -94,7 +94,7 @@ def test_history_never_leads_and_rides_along_as_context() -> None:def test_text_quotes_the_stored_numbers() -> None:core = next(i for i in _build().items if i.kind == "refactor")assert core.title == (- "Start breaking up run (CCN 44, 50 lines): first lift lines 20-35 into sum_rows"+ "Start breaking up run (CCN 44, 50 lines): first lift lines 20-35")# The size is a fact; the why says why it matters here.assert core.why == (@@ -214,7 +214,7 @@ def test_value_leads_tier_and_a_huge_function_says_so() -> None:big = {**FINDINGS[1], "details": {"ccn": 120, "nloc": 900, "max_nesting": 6}}planned = _build(findings=[big], performance=[]).leadassert planned.title == (- "Start breaking up run (CCN 120, 900 lines): first lift lines 20-35 into sum_rows"+ "Start breaking up run (CCN 120, 900 lines): first lift lines 20-35")@@ -447,7 +447,7 @@ def test_malformed_stages_never_crash_or_say_one_helper(stages, orchestrator) ->def test_an_unstaged_plan_reads_as_before() -> None:core = next(i for i in _build().items if i.kind == "refactor")assert core.title == (- "Start breaking up run (CCN 44, 50 lines): first lift lines 20-35 into sum_rows"+ "Start breaking up run (CCN 44, 50 lines): first lift lines 20-35")assert core.action.steps[0].text == "Extract lines 20-35 of run into sum_rows(rows, limit) -> total"@@ -575,7 +575,7 @@ def test_a_finding_whose_plan_is_below_the_worth_floor_leads_with_that_plan() ->run = next(i for i in queue.items if i.target.symbol == "run")assert queue.totals.excluded["below_min_worth"] == 1 and run.kind == "finding"assert run.title == (- "Start breaking up run (CCN 44, 50 lines): first lift lines 20-35 into sum_rows"+ "Start breaking up run (CCN 44, 50 lines): first lift lines 20-35")assert run.action.steps[0].text == ("Extract lines 20-35 of run into sum_rows(rows, limit) -> total"diff --git a/tests/unit/health/test_model_version_coupling.py b/tests/unit/health/test_model_version_coupling.pyindex b46bb4ac8..179faf29b 100644--- a/tests/unit/health/test_model_version_coupling.py+++ b/tests/unit/health/test_model_version_coupling.py@@ -22,7 +22,7 @@ from repowise.core.analysis.health.refactoring.identity import (# The three stamps as they stand together. Moving either identity model means# moving the analyzer with it, and updating this tuple in the same commit.-_STAMPS = (39, 3, 4)+_STAMPS = (40, 3, 4)def test_the_identity_models_and_the_analyzer_stamp_are_pinned_together() -> None:diff --git a/tests/unit/health/test_refactoring_anchors.py b/tests/unit/health/test_refactoring_anchors.pyindex e45146ad6..341c58bcd 100644--- a/tests/unit/health/test_refactoring_anchors.py+++ b/tests/unit/health/test_refactoring_anchors.py@@ -34,6 +34,7 @@ from repowise.core.analysis.health.refactoring.models import RefactoringContextfrom repowise.core.analysis.health.refactoring.recipe import (ELSEWHERE_NOTE,LINE_RULE,+ RENAME_NOTE,SCRIPT_RULE,build_recipe,)@@ -271,6 +272,7 @@ def test_the_apply_rules_read_the_same_in_every_renderer():assert wording in textassert f'"{wording}"' in steps_tsassert f'"{ELSEWHERE_NOTE}"' in steps_ts+ assert f'"{RENAME_NOTE}"' in steps_ts# The opportunity fallback reads the same constants.assert "SCRIPT_RULE_TEXT," in prompts_ts and "LINE_RULE_TEXT," in prompts_tsdiff --git a/tests/unit/health/test_refactoring_extract_method.py b/tests/unit/health/test_refactoring_extract_method.pyindex 6ad8e83f4..c7b670fcb 100644--- a/tests/unit/health/test_refactoring_extract_method.py+++ b/tests/unit/health/test_refactoring_extract_method.py@@ -703,105 +703,26 @@ def test_detector_emits_suggestion_for_flagged_function():assert s.confidence in ("medium", "high")-def test_plan_carries_a_computed_name_not_a_hardcoded_none():- """``suggested_name`` was ``None`` on every extract_method plan ever stored- (854 of 854 on this repo's index) while Extract Helper computed one, so the- field's meaning depended on which detector wrote it and every surface fell- through to a generic "helper". It is now always a real identifier."""+def test_plan_names_the_helper_with_a_placeholder():+ """The plan does not assert a name: the agent applying it names the helper+ for what it returns or does. The placeholder is valid code until then."""findings = [_Finding("complex_method", "process", line_start=2, health_impact=1.5)]s = ExtractMethodDetector().detect(_ctx(_PROCESS, findings))[0]- # The slice's single OUT value is ``average``, so the span is by- # construction the code that computes it.assert s.plan["returns"] == ["average"]# In Python's private form.- assert s.plan["suggested_name"] == "_compute_average"---class _Extraction:- def __init__(self, returns):- self.returns = list(returns)---class _Analysis:- def __init__(self, name):- self.name = name---def test_suggested_name_unit():- name = ExtractMethodDetector._suggested_name- # Exactly one OUT -> name the helper for what it produces, in the language's- # own convention.- assert name(_Analysis("process"), _Extraction(["average"]), "python") == "compute_average"- # Non-identifier characters normalised through the shared slug.- assert name(_Analysis("p"), _Extraction(["total-count"]), "python") == "compute_total_count"- # A call with no language keeps the snake_case default (the pre-existing- # behaviour), so an unset ``ctx.language`` degrades rather than changes shape.- assert name(_Analysis("process"), _Extraction(["average"])) == "compute_average"---def test_suggested_name_none_cases_are_unchanged_by_the_language():- """Control: the no-anchor rules this change must not touch. Each of these- was ``None`` before it and must stay ``None`` after, in every language."""- name = ExtractMethodDetector._suggested_name- # No single OUT -> no anchor, so no name. The enclosing function's name- # described the span's context, never the span, and collided with every- # sibling plan in the file.- assert name(_Analysis("run_pipeline"), _Extraction([])) is None- assert name(_Analysis("run_pipeline"), _Extraction(["a", "b"])) is None- # A return name that slugs to nothing must not yield "compute_".- assert name(_Analysis("process"), _Extraction(["___"])) is None- # An OUT named for its role, not the product: "compute_result" names- # nothing the reader did not already know.- assert name(_Analysis("process"), _Extraction(["result"])) is None- # Nothing usable at all -> no name at all.- assert name(_Analysis("___"), _Extraction([])) is None- # And none of the above becomes a name just because the language is camelCase.- for lang in ("java", "go", "typescript", "cpp", "python"):- assert name(_Analysis("process"), _Extraction([]), lang) is None- assert name(_Analysis("process"), _Extraction(["result"]), lang) is None- assert name(_Analysis("process"), _Extraction(["___"]), lang) is None---def test_suggested_name_follows_the_language_convention():- name = ExtractMethodDetector._suggested_name- # camelCase languages.- for lang in ("java", "go", "typescript", "tsx", "javascript", "jsx", "svelte", "vue"):- assert name(_Analysis("process"), _Extraction(["average"]), lang) == "computeAverage", lang- # snake_case languages, and C++ which has no single convention.- for lang in ("python", "rust", "cpp"):- assert name(_Analysis("process"), _Extraction(["average"]), lang) == "compute_average", lang- # An unknown language falls back rather than raising.- assert name(_Analysis("process"), _Extraction(["average"]), "cobol") == "compute_average"- # A language whose file has several words keeps all of them.- assert (- name(_Analysis("process"), _Extraction(["total_count"]), "java") == "computeTotalCount"- )---def test_suggested_name_keeps_the_out_values_own_casing():- name = ExtractMethodDetector._suggested_name- # ``meanValue`` must survive as word boundaries. Lowercasing the whole label- # first (the old slug) gave ``compute_meanvalue``, neither camelCase nor- # snake_case.- assert name(_Analysis("process"), _Extraction(["meanValue"]), "java") == "computeMeanValue"- assert name(_Analysis("process"), _Extraction(["mean_value"]), "java") == "computeMeanValue"- assert name(_Analysis("process"), _Extraction(["MeanValue"]), "java") == "computeMeanValue"- assert name(_Analysis("process"), _Extraction(["meanValue"]), "python") == "compute_mean_value"- # A run of capitals stays one word: splitting it needs a dictionary.- assert name(_Analysis("process"), _Extraction(["HTTPStatus"]), "java") == "computeHttpstatus"- # The role-word guard still sees a multi-word out value's joined slug.- assert name(_Analysis("process"), _Extraction(["item_value"]), "java") == "computeItemValue"+ assert s.plan["suggested_name"] == "_extracted_helper"+ assert s.plan["new_symbol"]["signature_text"].startswith("def _extracted_helper(")@pytest.mark.parametrize(("language", "expected"),[- ("python", "_compute_average"),- ("rust", "compute_average"),- ("cpp", "compute_average"),- ("java", "computeAverage"),- ("typescript", "computeAverage"),- ("go", "computeAverage"),+ ("python", "_extracted_helper"),+ ("rust", "extracted_helper"),+ ("cpp", "extracted_helper"),+ ("java", "extractedHelper"),+ ("typescript", "extractedHelper"),+ ("go", "extractedHelper"),],)def test_detector_names_the_helper_in_the_files_language(language: str, expected: str):diff --git a/tests/unit/health/test_refactoring_extract_method_naming.py b/tests/unit/health/test_refactoring_extract_method_naming.pyindex 188c33c39..cd0aad0d8 100644--- a/tests/unit/health/test_refactoring_extract_method_naming.py+++ b/tests/unit/health/test_refactoring_extract_method_naming.py@@ -1,7 +1,6 @@-"""Where an Extract Method helper's ``suggested_name`` comes from: a ``timed()``-stage label, a banner comment, ``compute_<out>`` for an effect-free span, else-the host function qualified by the span's subject; never a name a sibling in-the helper's scope already uses.+"""An Extract Method helper's ``suggested_name`` is a placeholder the agent+applying the plan renames: ``extracted_helper`` in the file's casing,+numbered when a name in the helper's scope already takes it."""from __future__ import annotations@@ -11,10 +10,8 @@ from dataclasses import dataclassimport pytest-from repowise.core.analysis.health.complexity.languages import get_language_map-from repowise.core.analysis.health.dataflow import Extraction, analyze_file+from repowise.core.analysis.health.dataflow import analyze_filefrom repowise.core.analysis.health.refactoring.extract_method import ExtractMethodDetector-from repowise.core.analysis.health.refactoring.helper_naming import helper_name, helper_namesfrom repowise.core.analysis.health.refactoring.models import RefactoringContext@@ -90,217 +87,58 @@ def _py(head: str = "", effect: str = "") -> str:return _PY.format(head=head, effect=effect)-# -- sources in order ---------------------------------------------------------------def test_without_a_banner_the_single_out_value_names_an_effect_free_span():- assert _name(_py()) == "compute_average"---def test_a_banner_comment_above_the_span_names_the_helper():- assert _name(_py(head=" # Sum values above threshold\n")) == "sum_values_above_threshold"--- "head",- [- " # ---- Sum values ----\n",- " # ===========\n # Sum values\n # ===========\n",- " # 2. Sum values\n",- " # Sum values (above the bar).\n",- " # region Sum values\n",- ' # <editor-fold desc="Sum values">\n',- ],-)-def test_rules_numbering_and_asides_around_a_banner_are_dropped(head):- assert _name(_py(head=head)) == "sum_values"+def test_the_helper_is_named_with_a_placeholder():+ assert _name(_py()) == "extracted_helper"@pytest.mark.parametrize("head",- [- # Prose, not a name: too long, two lines, code in it, a tool directive,- # a one-word heading.- " # Sum every value that clears the threshold and count them here\n",- " # Sum values above\n # the threshold.\n",- " # total -> sum of values\n",- " # TODO sum values\n",- " # Totals\n",- " # endregion\n",- # Not touching the statement: it heads something else.- " # Sum values above threshold\n\n",- ],-)-def test_a_comment_that_is_not_a_banner_leaves_the_out_value_name(head):- assert _name(_py(head=head)) == "compute_average"---def test_a_trailing_comment_on_the_line_above_is_not_a_banner():- src = _py().replace(" total = 0\n", " errors = errors # Sum values\n total = 0\n")- assert _name(src) != "sum_values"---def test_a_banner_over_a_nested_statement_neither_names_nor_splits_the_span():- src = _py(head=" # Sum values\n").replace(- " total += v\n", " # Add it up\n total += v\n"- )- assert _name(src) == "sum_values"- inner_only = _py().replace(- " total += v\n", " # Add it up\n total += v\n"- )- assert _name(inner_only) == "compute_average"---def test_a_span_holding_a_second_banner_takes_neither():- src = _py(head=" # Sum values\n").replace(- " average = total", " # Average them\n average = total"- )- assert _name(src) == "compute_average"---def test_a_timed_stage_label_names_the_helper():- src = """- def persist(session, pages, timings, flags):- written = 0- for p in pages:- if p is None:- continue- written += 1- with timed(timings, "persist.pages"):- for page in pages:- if page.stale:- session.delete(page)- elif page.new:- session.add(page)- else:- session.merge(page)- if flags:- session.flush()- return written- """- assert _name(src) == "persist_pages"---# -- no compute_ for a span with effects ------------------------------------------- "effect",- [- " print(v)\n", # I/O- " records.append(v)\n", # mutates a parameter- " threshold.seen = v\n", # writes through a parameter- " sink[v] = count\n", # writes into a name the span does not bind- # A local bound from a call may be an outside object.- " log = get_logger()\n log.info(v)\n",- " f = open(v)\n f.write(v)\n",- " cur = conn.cursor()\n rows = cur.execute(v)\n",- # Mutation in expression position, on a name the span does not own.- " last = records.pop()\n",- " item = queue.get()\n",- " seen = cache.setdefault(v, [])\n",- " del records[0]\n",- ],+ [" # Sum values above threshold\n", ' with timed(t, "persist.pages"):\n pass\n'],)-def test_a_span_with_outside_effects_is_not_named_compute(effect):- # Named for its host and the value it produces, never ``compute_``.- assert _name(_py(effect=effect)) == "process_average"--- "effect",- [- " label = names.get(v)\n", # a keyed read- " key = str(v).strip().lower()\n", # string reads- " path = os.path.join(v, v)\n", # a module function- " local = {}\n local[v] = 1\n del local[v]\n", # its own dict- ],-)-def test_reads_and_writes_to_what_the_span_owns_keep_the_name(effect):- assert _name("import os\n" + _py(effect=effect)) == "compute_average"--[email protected]("verb", ["Compute", "Build", "Get", "Calculate"])-def test_a_banner_promising_a_value_does_not_name_a_span_with_effects(verb):- src = _py(head=f" # {verb} the totals\n", effect=" print(v)\n")- assert _name(src) == "process_average"---def test_a_banner_still_names_a_span_with_effects():- src = _py(head=" # Report the totals\n", effect=" print(v)\n")- assert _name(src) == "report_totals"---def test_mutating_a_list_the_span_built_is_not_an_effect():- src = (- _py()- .replace(" count = 0\n", " count = 0\n kept = []\n")- .replace(" count += 1\n", " count += 1\n kept.append(v)\n")- )- assert _name(src) == "compute_average"---def test_writing_through_self_is_an_effect():- src = """- class Stats:- def process(self, records, threshold):- results = []- for r in records:- if r is None:- continue- results.append(r)- total = 0- count = 0- for v in results:- if v > threshold:- total += v- self.count = count- else:- total -= v- average = total / count if count else 0- return average- """- assert _name(src) == "process_average"+def test_nothing_in_the_code_names_the_helper(head):+ # A banner, a stage label or the OUT value no longer name it.+ assert _name(_py(head=head)) == "extracted_helper"# -- collisions with the helper's scope ------------------------------------------[email protected]("sibling", ["compute_average", "_compute_average"])-def test_a_name_a_sibling_function_already_has_is_dropped(sibling):[email protected]("sibling", ["extracted_helper", "_extracted_helper"])+def test_a_placeholder_a_sibling_function_already_has_is_numbered(sibling):src = _py() + f"\n\ndef {sibling}(values):\n return sum(values) / len(values)\n"- assert _names(src) == [("process", "process_average")]+ assert _names(src) == [("process", "extracted_helper_2")]def test_two_plans_in_one_scope_do_not_share_a_name():second = textwrap.dedent(_py()).replace("def process(", "def process_again(")assert _names(_py() + "\n" + second) == [- ("process", "compute_average"),- ("process_again", "process_again_average"),+ ("process", "extracted_helper"),+ ("process_again", "extracted_helper_2"),]def test_a_method_does_not_collide_with_a_module_function():method = textwrap.indent(textwrap.dedent(_py()).replace("(records,", "(self, records,"), " ")- src = "def compute_average(values):\n return 0\n\n\nclass Stats:\n" + method- assert _names(src) == [("process", "compute_average")]+ src = "def extracted_helper(values):\n return 0\n\n\nclass Stats:\n" + method+ assert _names(src) == [("process", "extracted_helper")]@pytest.mark.parametrize("prefix",[- "compute_average = None\n\n", # a module-level assignment- "from stats import compute_average\n\n", # an import- "from stats import mean as compute_average\n\n",+ "extracted_helper = None\n\n", # a module-level assignment+ "from stats import extracted_helper\n\n", # an import+ "from stats import mean as extracted_helper\n\n",],)def test_module_assignments_and_imports_take_the_name(prefix):- assert _names(prefix + _py()) == [("process", "process_average")]+ assert _names(prefix + _py()) == [("process", "extracted_helper_2")]def test_the_host_functions_own_parameters_and_locals_take_the_name():- src = _py().replace("(records, threshold)", "(records, threshold, compute_average=None)")- assert _names(src) == [("process", "process_average")]+ src = _py().replace("(records, threshold)", "(records, threshold, extracted_helper=None)")+ assert _names(src) == [("process", "extracted_helper_2")]# -- casing --------------------------------------------------------------------@@ -337,107 +175,6 @@ function process(records: number[], threshold: number): number {"""-def test_a_banner_name_follows_the_files_casing():- assert _name(_TS, "typescript", "ts") == "sumValuesAboveThreshold"---def test_the_out_value_name_keeps_the_files_casing():- assert _name(_TS.replace(" // Sum values above threshold\n", ""), "typescript", "ts") == (- "computeAverage"- )---# -- the dogfood shapes -------------------------------------------------------------def _span_name(language, ext, src, start, end, params, returns, *, needs_async=False):- (fn,) = _functions(language, ext, src)- first = fn.start_line - 1- extraction = Extraction(- first + start, first + end, tuple(params), tuple(returns), 8, 2, needs_async- )- return helper_name(fn, extraction, get_language_map(language), language)---def test_status_header_span_is_not_compute_deep():- # hermes_cli/status.py:133: reads a flag, then prints the header.- src = """- def show_status(args):- deep = getattr(args, 'deep', False)- print()- print(color("Hermes Agent Status", Colors.CYAN))- line = _estop_status_line()- if line:- print()- print(color(line, Colors.YELLOW))- if deep and line:- print("deep")- return deep- """- assert _span_name("python", "py", src, 2, 10, ["args"], ["deep"]) is None---def test_run_main_span_is_not_compute_is_gateway_run_invocation():- # openclaw src/cli/run-main.ts:640: marks a trace and asserts the runtime.- src = """- async function runCli(argv: string[], startupTrace: Trace) {- const normalizedArgv = normalize(argv);- const isGatewayRunInvocation = isGatewayRunInvocationArgv(normalizedArgv);- startupTrace.mark("argv");- assertSupportedRuntime();- if (isGatewayRunInvocation || shouldLoad()) {- loadCliDotEnv({ quiet: true });- }- return isGatewayRunInvocation;- }- """- params, returns = ["normalizedArgv", "startupTrace"], ["isGatewayRunInvocation"]- name = _span_name("typescript", "ts", src, 3, 8, params, returns)- assert name is None---def test_gateway_child_span_is_not_compute_message():- # openclaw extensions/qa-lab/src/gateway-child.ts:1119: closes streams.- src = """- async function startQaGatewayChild(stdoutLog: Stream, keepTemp: boolean, error: unknown) {- await closeWriteStream(stdoutLog);- if (!keepTemp) {- await cleanupQaGatewayTempRoots({ stdoutLog });- }- const message = keepTemp ? appendRoot(format(error)) : format(error);- return message;- }- """- params = ["stdoutLog", "keepTemp", "error"]- name = _span_name("typescript", "ts", src, 2, 6, params, ["message"], needs_async=True)- assert name is None---def test_order_by_span_keeps_compute_order_by_sql():- # hermes hermes_state_search.py:1769: pure, one product.- src = """- def _search(sort):- if isinstance(sort, str):- sort_norm = sort.strip().lower()- if sort_norm not in ("newest", "oldest"):- sort_norm = None- else:- sort_norm = None- if sort_norm == "newest":- order_by_sql = "ORDER BY m.timestamp DESC, rank"- elif sort_norm == "oldest":- order_by_sql = "ORDER BY m.timestamp ASC, rank"- else:- order_by_sql = "ORDER BY rank"- return order_by_sql- """- assert _span_name("python", "py", src, 2, 13, ["sort"], ["order_by_sql"]) == (- "compute_order_by_sql"- )---# -- other grammars ---------------------------------------------------------------_GO = """package main@@ -502,234 +239,12 @@ fn process(records: &[i32], threshold: i32) -> i32 {"""-def test_go_and_rust_banner_names_keep_their_casing():- assert _name(_GO, "go", "go") == "sumValuesAboveThreshold"- assert _name(_RUST, "rust", "rs") == "sum_values_above_threshold"+def test_the_placeholder_follows_the_files_casing():+ assert _name(_TS, "typescript", "ts") == "extractedHelper"+ assert _name(_GO, "go", "go") == "extractedHelper"+ assert _name(_RUST, "rust", "rs") == "extracted_helper"def test_go_exported_and_unexported_spellings_collide():- src = _GO.replace(" // Sum values above threshold\n", "") + (- "\nfunc ComputeAverage(xs []int) int {\n return 0\n}\n"- )- assert _names(src, "go", "go") == [("process", "processAverage")]---def test_a_one_line_jsdoc_is_a_banner_and_a_block_one_is_not():- one_line = _TS.replace("// Sum values above threshold", "/** Sum values above threshold */")- assert _name(one_line, "typescript", "ts") == "sumValuesAboveThreshold"- block = _TS.replace(- " // Sum values above threshold\n",- " /**\n * Sum values above threshold\n * @returns the mean\n */\n",- )- assert _name(block, "typescript", "ts") == "computeAverage"---def test_a_ts_region_marker_is_dropped():- src = _TS.replace("// Sum values above threshold", "// #region Sum values")- assert _name(src, "typescript", "ts") == "sumValues"---_TS_EFFECT = """-let seen = 0;-function process(values: number[], cache: Record<string, number>): number {- const out = [];- let total = 0;- for (const v of values) {- if (v > 0) {- total += v;- EFFECT- }- }- return total;-}-"""--- ("effect", "acts"),- [- ("delete cache.k;", True), # deletes through a parameter- ("seen++;", True), # bumps a captured module variable- ("--seen;", True),- ("out.push(v);", False), # its own array- ("total++;", False), # a declared local- ],-)-def test_ts_deletes_and_captured_updates_are_effects(effect, acts):- src = _TS_EFFECT.replace("EFFECT", effect)- name = _span_name("typescript", "ts", src, 2, 9, ["values"], ["total"])- assert (name is None) is acts---_GO_EFFECT = """-package main--var hits = 0--func process(values []int, ch chan int, out *int) int {- total := 0- for _, v := range values {- if v > 0 {- total += v- EFFECT- }- }- return total-}-"""--- ("effect", "acts"),- [("ch <- v", True), ("hits++", True), ("*out = v", True), ("total++", False)],-)-def test_go_sends_captured_increments_and_pointer_writes_are_effects(effect, acts):- src = _GO_EFFECT.replace("EFFECT", effect)- name = _span_name("go", "go", src, 2, 8, ["values", "ch", "out"], ["total"])- assert (name is None) is acts---_RUST_EFFECT = """-fn process(values: &[i32], out: &mut i32, c: &mut i32) -> i32 {- let mut total = 0;- let mut own = Vec::new();- for v in values {- if *v > 0 {- total += v;- EFFECT- }- }- total-}-"""--- ("effect", "acts"),- [- ("*out = *v;", True),- ("*c += 1;", True),- ("bump(&mut total, c);", True),- ("own.push(*v);", False),- ],-)-def test_rust_deref_writes_and_mut_borrows_are_effects(effect, acts):- src = _RUST_EFFECT.replace("EFFECT", effect)- name = _span_name("rust", "rs", src, 2, 10, ["values", "out", "c"], ["total"])- assert (name is None) is acts---# -- the host and the span's subject, when nothing else anchors a name ---------------def _span_names(language, ext, src, start, end, returns=()):- (fn,) = _functions(language, ext, src)- first = fn.start_line - 1- extraction = Extraction(first + start, first + end, (), tuple(returns), 8, 2, False)- names = []- # The candidates never run out; read through the first unnumbered block name.- for name in helper_names(fn, extraction, get_language_map(language), language):- names.append(name)- if name.lower().endswith("block"):- return names- return names---def test_a_branch_body_is_named_for_the_branch_it_handles():- src = """- def render_plan(p, kind):- out = []- if kind == "break_cycle":- out.append("cycle")- elif kind == "split_file":- groups = p.get("groups", [])- out.append(len(groups))- return out- """- assert _span_names("python", "py", src, 6, 7)[0] == "render_plan_split_file"---def test_a_loop_is_named_for_what_it_walks_and_a_write_for_its_field():- src = """- def cmd_list(state, jobs):- for job in jobs:- print(job)- state.registry = jobs- """- assert _span_names("python", "py", src, 2, 3) == ["cmd_list_jobs", "cmd_list_job", "cmd_list_block"]- assert _span_names("python", "py", src, 4, 4) == ["cmd_list_registry", "cmd_list_block"]---def test_a_subject_repeating_the_host_is_not_a_name():- src = """- def build_rows(rows, limit):- for row in rows:- print(row)- """- assert _span_names("python", "py", src, 2, 3) == ["build_rows_row", "build_rows_block"]---def test_a_component_host_keeps_its_casing_and_starts_lowercase():- src = """- function OverviewPage(providers: Providers): number {- const active = providers.active;- track(active);- const costPer1k = active ? active.cost : 0;- return costPer1k;- }- """- names = _span_names("typescript", "ts", src, 2, 4, ["costPer1k"])- assert names[0] == "overviewPageCostPer1k"---def test_a_camel_case_host_follows_the_files_convention():- src = """- def buildRows(rows, limit):- for row in rows:- print(row)- """- assert _span_names("python", "py", src, 2, 3) == ["build_rows_row", "build_rows_block"]---def test_a_span_with_no_subject_is_a_block_of_its_host():- src = """- def report(job):- logger.info("start")- logger.info("done")- """- assert _span_names("python", "py", src, 2, 3) == ["report_block"]- anonymous = """- const run = function () {- console.log("start");- console.log("done");- };- """- # An unnamed function expression has no host name to qualify.- assert _span_names("typescript", "ts", anonymous, 2, 3) == ["handleBlock"]---def test_a_numbered_block_name_follows_when_every_candidate_is_taken():- from repowise.core.analysis.health.refactoring.helper_naming import ScopeNames-- src = """- def report(job):- logger.info("start")- logger.info("done")--- def report_block():- return 0- """- fns = _functions("python", "py", src)- (fn,) = [f for f in fns if f.name == "report"]- lmap = get_language_map("python")- first = fn.start_line - 1- extraction = Extraction(first + 2, first + 3, (), (), 8, 2, False)- names = ScopeNames(lmap)- assert names.claim_first(fn, helper_names(fn, extraction, lmap, "python")) == (- "report_block_2"- )- # The next plan in the same scope takes the next number.- assert names.claim_first(fn, helper_names(fn, extraction, lmap, "python")) == (- "report_block_3"- )+ src = _GO + "\nfunc ExtractedHelper(xs []int) int {\n return 0\n}\n"+ assert _names(src, "go", "go") == [("process", "extractedHelper2")]diff --git a/tests/unit/health/test_refactoring_naming.py b/tests/unit/health/test_refactoring_naming.pyindex 2cb8864b6..333ceaa1f 100644--- a/tests/unit/health/test_refactoring_naming.py+++ b/tests/unit/health/test_refactoring_naming.py@@ -1,48 +1,10 @@-"""The shared identifier slug both name-producing detectors run through.--It exists so ``suggested_name`` means one thing across the payload rather than-one thing per detector.+"""Identifier words: a name split into its words, and words joined in a+language's casing."""from __future__ import annotations-from repowise.core.analysis.health.refactoring.naming import (- banner_words,- identifier_slug,- join_identifier,- label_words,- split_words,-)---def test_lowercases_and_keeps_alphanumerics():- assert identifier_slug("Providers") == "providers"- assert identifier_slug("http2") == "http2"---def test_collapses_non_alphanumeric_runs_to_single_underscores():- assert identifier_slug("api-client") == "api_client"- assert identifier_slug("a..--..b") == "a_b"- assert identifier_slug("pkg/sub") == "pkg_sub"---def test_strips_leading_and_trailing_separators():- assert identifier_slug("--api--") == "api"- assert identifier_slug("_private_") == "private"---def test_leading_digit_is_made_identifier_safe():- # Not a valid identifier start in most languages.- assert identifier_slug("3d") == "_3d"- assert identifier_slug("2fa-token") == "_2fa_token"---def test_unusable_input_returns_empty_so_callers_can_pick_a_fallback():- assert identifier_slug("") == ""- assert identifier_slug(None) == ""- assert identifier_slug("---") == ""- assert identifier_slug("...") == ""-+from repowise.core.analysis.health.refactoring.naming import join_identifier, split_words# -- word splitter --------------------------------------------------------------@@ -105,39 +67,3 @@ def test_join_identifier_uses_the_first_word_as_lowercase_head():def test_join_identifier_of_no_words_is_empty():assert join_identifier([], "camelCase") == ""assert join_identifier([], "snake_case") == ""---# -- banner comments and stage labels ------------------------------------------------def test_banner_words_reads_one_short_line_between_rules():- assert banner_words(["# Build table"]) == ["build", "table"]- assert banner_words(["// Group by consumer repo"]) == ["group", "by", "consumer", "repo"]- assert banner_words(["# ---- Graph metrics ----------"]) == ["graph", "metrics"]- assert banner_words(["# ── Core runtime state ──"]) == ["core", "runtime", "state"]- assert banner_words(["# =====", "# Load edges", "# ====="]) == ["load", "edges"]- assert banner_words(["/* Load edges */"]) == ["load", "edges"]- # Step numbers, asides and articles are not part of the name.- assert banner_words(["# 3. Remove the wrapper script"]) == ["remove", "wrapper", "script"]- assert banner_words(["# Step 1: Parse git logs"]) == ["parse", "git", "logs"]- assert banner_words(["# Neighboring communities (cap at 5)"]) == ["neighboring", "communities"]---def test_banner_words_refuses_prose_code_and_directives():- assert banner_words([]) == []- assert banner_words(["# Decisions"]) == [] # a heading, not a name- assert banner_words(["# Lazy import to avoid circular dependency at load"]) == []- assert banner_words(["# Sum values", "# then count them"]) == []- assert banner_words(["# Build labels and map indices -> skill names"]) == []- assert banner_words(["# Check for image/picture"]) == []- assert banner_words(["# [3] get_running_pid()"]) == []- assert banner_words(["# Kimi: top-level reasoning effort"]) == []- assert banner_words(["// eslint-disable-next-line no-await-in-loop"]) == []- assert banner_words(["# TODO tidy this up"]) == []---def test_label_words_reads_a_timed_stage_label():- assert label_words('with timed(timings, "persist.pages"):') == ["persist", "pages"]- assert label_words("with timed(self._t, 'detect_changes'):\n x = 1") == ["detect", "changes"]- assert label_words('with span("persist.pages"):') == []- assert label_words("x = timed") == []diff --git a/tests/unit/health/test_refactoring_recipe.py b/tests/unit/health/test_refactoring_recipe.pyindex e6988d1af..fc178ca4d 100644--- a/tests/unit/health/test_refactoring_recipe.py+++ b/tests/unit/health/test_refactoring_recipe.py@@ -12,6 +12,7 @@ import pathlibfrom repowise.core.analysis.health.refactoring.recipe import (PRECONDITION_KINDS,RECIPE_ACTIONS,+ RENAME_NOTE,build_recipe,)@@ -32,8 +33,8 @@ def test_extract_method_carries_the_texts_to_copy() -> None:(step,) = recipe["steps"]assert step["action"] == "extract"assert step["span"] == {"start": 61, "end": 78}- assert step["new_symbol"]["signature_text"].startswith("async def _read_config(self")- assert step["call_site"]["new_text"] == "config = await self._read_config(path, strict)"+ assert step["new_symbol"]["signature_text"].startswith("async def _extracted_helper(self")+ assert step["call_site"]["new_text"] == "config = await self._extracted_helper(path, strict)"# A placeholder in the texts is named, so the agent fills it.assert any("<type>" in note for note in step["new_symbol"]["notes"])assert recipe["does_not"][1]["constraint"].startswith("touch anything outside lines 61-78")@@ -136,3 +137,20 @@ def test_every_plan_type_yields_steps_in_the_shared_vocabulary() -> None:"replace_with_call","replace_with_call",]+++def test_an_extract_method_plan_says_once_that_its_names_are_placeholders() -> None:+ (step,) = build_recipe(_PLANS["extract_method_typed"])["steps"]+ assert step["text"].endswith(RENAME_NOTE)+ staged = build_recipe(_PLANS["extract_method_staged_anchored"])["steps"]+ texts = " ".join(s["text"] for s in staged)+ assert texts.count("placeholder") == 1+ assert "Each stage's helper name is a placeholder" in texts++++def test_a_plan_stored_with_a_real_name_is_not_called_a_placeholder() -> None:+ detail = json.loads(json.dumps(_PLANS["extract_method_typed"]))+ detail["plan"]["suggested_name"] = "_read_config"+ (step,) = build_recipe(detail)["steps"]+ assert "placeholder: rename" not in step["text"]