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): export a plan as a recipe and render its agent prompt in core (#3364)
Raghav Chamadiya9c744bedc1c5
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 660309137..d9b42fd0d 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -322,12 +322,12 @@ Code-health scores and findings from the stored analysis, across defect risk, ma| Parameter | Type | Default | Meaning ||-----------|------|---------|---------|| `targets` | list[string] | none (dashboard) | File paths or `module:<name>`. Misses are named in `unresolved` |-| `include` | list[string] | none | Blocks: `biomarkers`, `refactoring`, `trend`, `coverage`, `accuracy`, `signals`, `churn_complexity`, `doc_drift`, `semantics`, `unverified`. Dimension filters: `performance`, `defect`, `maintainability`, `advisory` |+| `include` | list[string] | none | Blocks: `biomarkers`, `refactoring`, `trend`, `coverage`, `accuracy`, `signals`, `churn_complexity`, `doc_drift`, `semantics`, `unverified`, `recipe` (with `plan_id`). Dimension filters: `performance`, `defect`, `maintainability`, `advisory` || `only` | list[string] | none | Keep just these top-level keys; identity, totals and recovery fields always survive. An unknown key is named in `unknown_only_keys` with `unknown_only_keys_hint` || `limit` | int | `20` | Max rows in every ranked list, capped at 50; `0` for none. `fix_first` shows five unless `limit` is passed with `only=["fix_first"]`, which pages up to 25; `refactoring_plans` up to 25 || `cursor` | int | `0` | Offset into a ranked list (and into `fix_first` when named in `only`); the `recovery` block names the next call || `fix_id` | string | none | Open one `fix_first` item in full |-| `finding_id`, `plan_id` | string | none | Open one finding or refactoring plan by id |+| `finding_id`, `plan_id` | string | none | Open one finding or refactoring plan by id. With `plan_id`, `include=["recipe"]` adds `plan.recipe`: the plan's preconditions, ordered steps, postconditions and what it must not do || `opportunity_id` | string | none | Open one opportunity: `perf...` for performance, `refop...` for a refactoring || `refactoring_view` | string | `"diversified"` | `diversified`, `canonical` or `file_spread` || `refactoring_scope` | string | `fix_first` without targets, `all` with | Which open refactoring opportunities, and their plans, to list |diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.mdindex ccc63c891..9b9a704db 100644--- a/docs/layers/REFACTORING.md+++ b/docs/layers/REFACTORING.md@@ -38,6 +38,7 @@ repowise health --refactoring-targets # the stored queue, in serepowise health --refactoring-targets --format jsonrepowise health --refactoring-targets --recompute # analyze the working tree instead of the indexrepowise health --refactoring-targets --generate-code 1 # code + diff for the top plan (LLM)+repowise health --plan refac... # one plan as the prompt an agent applies```From an agent, through MCP:@@ -48,6 +49,7 @@ get_health(include=["refactoring"], only=["refactoring_opportunities"], limit=6)get_health(targets=["src/api/server.py"], include=["refactoring"]) # one fileget_health(opportunity_id="refop...") # one opportunity's stepsget_health(plan_id="refac...") # one plan+get_health(plan_id="refac...", include=["recipe"]) # ...as a recipe an agent applies```In the dashboard, the **Refactoring** page lists every type on one board, with@@ -65,6 +67,15 @@ plan detail adds a `verify` to each step whose tests differ from the plan's: thetests that reach that step's lines and the command to run them. A step withoutone is checked by the plan's own command.+Any plan can be read as a recipe: what must hold before the edit (tests that+pass, a characterization test to add, a decision to read), the edits in order,+the checks and expected improvement after, and what the edit must not do. The+dashboard's copy-prompt, `repowise health --plan`, plan detail with+`include=recipe` and code generation all read that same recipe, so an agent sees+one set of steps wherever it starts. The recipe and the prompt name the plan by+the public id `get_health(plan_id=...)` takes; REST plan detail's own `id` field+stays the storage id it has always served.+## Reading the resultsA **plan** is one detector's output for one target. An **opportunity** is one@@ -248,6 +259,7 @@ Most plans answer a health finding, so per-path marker rules in| `--refactoring-targets` | Print the stored refactoring queue in the order MCP and the dashboard serve it. || `--recompute` | Analyze the working tree in-process instead of reading the index. Slow on large repos. || `--generate-code SELECTOR` | Generate code and a diff for one plan. `SELECTOR` is a 1-based rank or a symbol name. Needs an API key. |+| `--plan ID` | Print one stored plan as the prompt an agent applies; with `--format json`, its recipe. || `--format json` | Machine-readable output. |## See alsodiff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 2bca33454..b9a80bb8d 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1123,6 +1123,7 @@ By default it reads the analysis the last `repowise init` or `repowise update` s| `--refactoring-targets` | Print the refactoring queue the index stored: one opportunity per file with its structured, graph-aware plans (Extract Class / Helper / Method, Move Method, Split File) as ordered steps and Break Cycle as advisory evidence, in the same order MCP and the web UI serve. Reads the index, so it needs `repowise init` first. See [REFACTORING.md](../layers/REFACTORING.md) || `--recompute` | Analyze the working tree in-process instead of reading the stored analysis. A whole-repo `table` run writes the result back to the index (scores, findings, a trend snapshot); `json`, `md` and `--file`/`--module` runs never write. Slow on a large repo; the only option outside an indexed one. With `--refactoring-targets`, `--scope` and `--counts` apply only here. || `--generate-code <selector>` | Generate an actual refactoring patch for one target. The only `health` flag that calls an LLM; needs a configured provider. |+| `--plan <id>` | Print one stored refactoring plan as the prompt an agent applies; with `--format json`, its recipe (preconditions, steps, postconditions). Reads the index. || `--trend` | Print the last 10 health snapshots + any active alerts (declining / predicted decline) || `--badge` | Print a shields.io-compatible badge URL/JSON for the repo's health score || `--format` | Output: `table` (default), `json`, `md` |diff --git a/packages/api-client/src/refactoring.ts b/packages/api-client/src/refactoring.tsindex 79a6851aa..ac2401292 100644--- a/packages/api-client/src/refactoring.ts+++ b/packages/api-client/src/refactoring.ts@@ -3,6 +3,7 @@* Backend: packages/server/src/repowise/server/routers/refactoring.py*/+import type { AgentPromptFlavor, AgentPromptResponse } from "@repowise-dev/types/agent-prompts";import { apiGet, apiPatch, apiPost, apiPut } from "./client";import type {GeneratedCode,@@ -96,6 +97,18 @@ export async function getRefactoringPlan(return apiGet<RefactoringPlan>(`/api/repos/${repoId}/refactoring/${suggestionId}`);}+/** One plan as the prompt an agent starts from, rendered by core for `flavor`. */+export async function getRefactoringPlanPrompt(+ repoId: string,+ suggestionId: string,+ opts: { flavor?: AgentPromptFlavor } = {},+): Promise<AgentPromptResponse> {+ return apiGet<AgentPromptResponse>(+ `/api/repos/${repoId}/refactoring/${encodeURIComponent(suggestionId)}/prompt`,+ { flavor: opts.flavor },+ );+}+/** Opt-in: generate the refactored code + a diff for one plan (Phase-5 endpoint). */export async function generateRefactoringCode(repoId: string,@@ -195,6 +208,18 @@ export async function getRefactoringOpportunity();}+/** One opportunity, its ordered steps and their plans, as an agent prompt core renders. */+export async function getRefactoringOpportunityPrompt(+ repoId: string,+ opportunityId: string,+ opts: { flavor?: AgentPromptFlavor } = {},+): Promise<AgentPromptResponse> {+ return apiGet<AgentPromptResponse>(+ `/api/repos/${repoId}/refactoring/opportunities/${encodeURIComponent(opportunityId)}/prompt`,+ { flavor: opts.flavor },+ );+}+/** The repository rollup and its one lead, by primary key. */export async function getRefactoringOpportunitySummary(repoId: string,diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/command.py b/packages/cli/src/repowise/cli/commands/health_cmd/command.pyindex eacfea9c0..94c032338 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py@@ -48,6 +48,7 @@ from .persist import (_persist_health,)from .refactoring_targets import (+ _render_plan_recipe,_render_refactoring_targets,_render_stored_refactoring_targets,)@@ -102,6 +103,16 @@ FIX_FIRST_ROWS = 3"web UI serve it."),)+ "--plan",+ "plan_id",+ default=None,+ metavar="ID",+ help=(+ "Print one stored refactoring plan as the recipe an agent applies: its "+ "preconditions, steps and checks (JSON with --format json)."+ ),+)@click.option("--recompute",is_flag=True,@@ -175,6 +186,7 @@ def health_command(repo_alias: str | None,no_workspace: bool,refactoring_targets: bool,+ plan_id: str | None,recompute: bool,generate_code: str | None,module_filter: str | None,@@ -236,6 +248,14 @@ def health_command(_render_trend(repo_path, fmt=fmt)return+ if plan_id is not None:+ if not _render_plan_recipe(repo_path, plan_id, fmt=fmt):+ raise click.ClickException(+ f"No stored refactoring plan {plan_id}. `repowise health --refactoring-targets` "+ "lists the current plans."+ )+ return+if refactoring_targets and not recompute and generate_code is None:# The stored queue is the calibrated reading, as on MCP and the web UI.if parse_scope(scope) != DEFAULT_SCOPE or parse_counts(counts) != DEFAULT_COUNTS:diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.pyindex 37f55e12d..0094c708a 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py@@ -208,6 +208,32 @@ def _render_stored_refactoring_targets(return True+def _render_plan_recipe(repo_path: Path, plan_id: str, *, fmt: str) -> bool:+ """One stored plan: its recipe as JSON, else the prompt an agent starts+ from. False when no index or no plan answers *plan_id*."""+ from repowise.cli.helpers import repo_index_session, run_async+ from repowise.core.agent_prompts import render_plan+ from repowise.core.analysis.health.refactoring.recipe import build_recipe+ from repowise.server.services.refactoring_health import RefactoringHealthService++ async def _read() -> dict[str, Any] | None:+ async with repo_index_session(Path(repo_path)) as opened:+ if opened is None:+ return None+ session, repo_id = opened+ service = RefactoringHealthService(session, repo_id, Path(repo_path).name)+ return (await service.plan_detail(plan_id)).get("plan")++ plan = run_async(_read())+ if plan is None:+ return False+ if fmt == "json":+ click.echo(json.dumps(build_recipe(plan), indent=2))+ else:+ click.echo(render_plan(plan, repo_name=Path(repo_path).name))+ return True++def _list_row(plan: dict) -> dict:"""A plan as a list row: the rendered Extract Method texts stay on plandetail, as on every other list."""diff --git a/packages/core/src/repowise/core/agent_prompts/__init__.py b/packages/core/src/repowise/core/agent_prompts/__init__.pyindex e8873d749..0d2ba8cff 100644--- a/packages/core/src/repowise/core/agent_prompts/__init__.py+++ b/packages/core/src/repowise/core/agent_prompts/__init__.py@@ -10,5 +10,14 @@ from __future__ import annotationsfrom .action import render_actionfrom .fix_first import render_fix_item, render_verify_linesfrom .preamble import FLAVORS, Flavor+from .refactoring import render_opportunity, render_plan-__all__ = ["FLAVORS", "Flavor", "render_action", "render_fix_item", "render_verify_lines"]+__all__ = [+ "FLAVORS",+ "Flavor",+ "render_action",+ "render_fix_item",+ "render_opportunity",+ "render_plan",+ "render_verify_lines",+]diff --git a/packages/core/src/repowise/core/agent_prompts/preamble.py b/packages/core/src/repowise/core/agent_prompts/preamble.pyindex 8bf44c67d..d6fb2861b 100644--- a/packages/core/src/repowise/core/agent_prompts/preamble.py+++ b/packages/core/src/repowise/core/agent_prompts/preamble.py@@ -34,6 +34,18 @@ OPENINGS: dict[str, dict[str, str]] = {"claude-code-mcp": 'Repowise ranked the change below first among the work it found. Call the MCP lookup under "Look closer" for the full record before reading files by hand, then confirm each fact against the code.',"cursor": "ranked the change below first among the work it found. Open the target with @file, confirm each fact, then make the change.",},+ "refactoring_plan": {+ "generic": "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.",+ "claude-code": "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.",+ "claude-code-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.',+ "cursor": "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.",+ },+ "refactoring_opportunity": {+ "generic": "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.",+ "claude-code": "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.",+ "claude-code-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.",+ "cursor": "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.",+ },}diff --git a/packages/core/src/repowise/core/agent_prompts/refactoring.py b/packages/core/src/repowise/core/agent_prompts/refactoring.pynew file mode 100644index 000000000..550c6b9d5--- /dev/null+++ b/packages/core/src/repowise/core/agent_prompts/refactoring.py@@ -0,0 +1,428 @@+"""A refactoring plan, or a composed opportunity of plans, handed to an agent.++Both read the plan through its recipe (:func:`build_recipe`), so the steps an+agent is told to make are the ones plan detail, the CLI and code generation+read. Takes the wire dicts the REST and MCP detail calls already serve.+"""++from __future__ import annotations++from collections.abc import Mapping+from typing import Any++from repowise.core.analysis.health.refactoring.recipe import build_recipe, label, verify_check++from .preamble import preamble+from .sections import bullet_list, closing_sections, join_sections, repo_suffix++_CONSTRAINTS = (+ "**Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.",+ "**Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.",+)++_PLAN_EXPECTED = (+ "1. The refactored code, with each step applied.",+ "2. What you named or introduced, and why.",+ "3. The Verify run, before and after, with its result.",+ "4. Any call sites or files you also had to change.",+)+++def _loc(file: Any, span: Mapping[str, int] | None) -> str:+ if not span:+ return f"`{file}`"+ end = f"-{span['end']}" if span["end"] != span["start"] else ""+ return f"`{file}:{span['start']}{end}`"+++def _symbol_lines(step: Mapping[str, Any]) -> list[str]:+ """What an Extract Method step adds: the texts to copy and the slots."""+ symbol = step.get("new_symbol") or {}+ call = step.get("call_site") or {}+ span = call.get("replace_span") or step.get("span") or {}+ out = []+ if symbol.get("signature_text"):+ out.append(f"New helper: `{symbol['signature_text']}`")+ if call.get("new_text"):+ lines = f"{span.get('start')}-{span.get('end')}"+ out.append(f"Replace lines {lines} with: `{call['new_text']}`")+ if symbol:+ out.append(f"Parameters (in): {', '.join(symbol.get('params') or []) or '(none)'}")+ out.append(f"Returns (out): {', '.join(symbol.get('returns') or []) or '(nothing)'}")+ out.extend(f"Note: {note}" for note in symbol.get("notes") or [])+ return out+++def _step_lines(step: Mapping[str, Any]) -> list[str]:+ """The sub-bullets under one step."""+ out = _symbol_lines(step)+ if step.get("applicability"):+ out.append(f"{str(step['applicability']).capitalize()} step.")+ verify = step.get("verify") or {}+ if verify.get("commands"):+ out.append("Verify this step: " + "; ".join(f"`{c}`" for c in verify["commands"]))+ return out+++def _step_entry(step: Mapping[str, Any], marker: str, pad: str) -> str:+ where = f" ({_loc(step['file'], step.get('span'))})" if step.get("file") else ""+ head = f"{pad}{marker} {step['text']}{where}"+ return "\n".join([head, *(f"{pad} - {line}" for line in _step_lines(step))])+++def _verify_lines(check: Mapping[str, Any], *, runnable: bool = True) -> list[str]:+ """The guarding tests, most direct first; with *runnable*, an instruction to+ run them and the command (a reader that cannot run anything gets neither)."""+ tests = check.get("tests") or []+ if not tests:+ return [check["text"]]+ reasons = check.get("reasons") or {}+ rows = [f"- `{t}`" + (f" ({reasons[t]})" if reasons.get(t) else "") for t in tests]+ total = check.get("tests_total") or len(tests)+ shown = [f"{len(tests)} of {total} guarding tests shown."] if total > len(tests) else []+ commands = (check.get("commands") or []) if runnable else []+ run = ["", "Run:", "", "```", *commands, "```"] if commands else []+ lead = (+ "Run these before and after the change, the most direct first:"+ if runnable+ else "The tests that guard this change, the most direct first:"+ )+ return [lead, "", *rows, *shown, *run]+++def _verify_section(recipe: Mapping[str, Any], *, runnable: bool = True) -> str:+ post = recipe["postconditions"]+ check = next(p for p in post if p["kind"] == "verify")+ expect = [p["text"] for p in post if p["kind"] == "metric"]+ return join_sections(+ [+ "## Verify",+ "",+ "\n".join(_verify_lines(check, runnable=runnable)),+ "\n" + bullet_list(f"Expect: {text}" for text in expect) if expect else "",+ "",+ ]+ )+++def _before_section(recipe: Mapping[str, Any]) -> str:+ pre = [p["text"] for p in recipe["preconditions"]]+ if not pre:+ return ""+ return join_sections(["## Before you edit", "", bullet_list(pre), ""])+++def _does_not(recipe: Mapping[str, Any]) -> list[str]:+ out = []+ for item in recipe["does_not"]:+ reason = item.get("reason")+ tail = f" {reason[0].upper()}{reason[1:]}." if reason else ""+ out.append(f"**Do not {item['constraint']}.**{tail}")+ return out+++#: The heading an advisory plan's steps sit under, unnumbered.+_ADVISORY_HEADING = {"break_cycle": "Advisory: one way to cut the cycle"}+++def _advisory_heading(recipe: Mapping[str, Any]) -> str:+ return _ADVISORY_HEADING.get(recipe["kind"] or "", "Advisory: one way to do it")+++def _steps_section(recipe: Mapping[str, Any]) -> list[str]:+ if recipe["advisory"]:+ body = "\n".join(_step_entry(s, "-", "") for s in recipe["steps"])+ return [f"## {_advisory_heading(recipe)}", "", body, ""]+ body = "\n".join(_step_entry(s, f"{s['n']}.", "") for s in recipe["steps"])+ return ["## Steps, in order", "", body, ""]+++#: Blast-radius values a code-generation prompt carries: the reach a move or a+#: class split has to keep working. Lists are cut, so one plan cannot flood it.+_BLAST_LIST_CAP = 8+++def _blast_value(value: Any) -> str | None:+ if isinstance(value, bool) or value is None:+ return None+ if isinstance(value, (int, float, str)):+ return str(value)+ if isinstance(value, list) and value:+ items = [+ f"{v['file_path']} ({v.get('commits')})" if isinstance(v, dict) and "file_path" in v+ else str(v)+ for v in value[:_BLAST_LIST_CAP]+ ]+ more = len(value) - len(items)+ return ", ".join(items) + (f", +{more} more" if more > 0 else "")+ return None+++def _blast_section(detail: Mapping[str, Any]) -> str:+ blast = detail.get("blast_radius") or {}+ rows = [+ f"{key.replace('_', ' ')}: {text}"+ for key, value in sorted(blast.items())+ if (text := _blast_value(value)) is not None+ ]+ if not rows:+ return ""+ return join_sections(["## Blast radius", "", bullet_list(rows), ""])+++def _look_closer(flavor: str, call: str) -> str:+ if flavor != "claude-code-mcp":+ return ""+ return join_sections(["## Look closer (Repowise MCP)", "", f"`{call}`", ""])+++def _plan_sections(+ recipe: Mapping[str, Any], repo_name: str | None, *, runnable: bool = True+) -> list[str]:+ """The plan itself, from its heading to Verify: what every reader of it gets."""+ target = recipe["target"]+ symbol = f" (`{target['symbol'].rsplit('::', 1)[-1]}`)" if target["symbol"] else ""+ facts = [f"Target: {_loc(target['file'], target['span'])}{symbol}"]+ if recipe["id"]:+ facts.insert(0, f"Plan: `{recipe['id']}`")+ return [+ f"## {label(recipe['kind'])}{repo_suffix(repo_name)}",+ "",+ recipe["summary"],+ "",+ bullet_list(facts),+ "",+ _before_section(recipe),+ *_steps_section(recipe),+ _verify_section(recipe, runnable=runnable),+ ]+++def render_plan(+ detail: Mapping[str, Any], flavor: str = "generic", repo_name: str | None = None+) -> str:+ """One plan (its detail dict) as the prompt an agent starts from."""+ recipe = build_recipe(detail)+ return join_sections(+ [+ preamble(flavor, "refactoring_plan"),+ "",+ *_plan_sections(recipe, repo_name),+ _look_closer(flavor, f'get_health(plan_id="{recipe["id"]}")'),+ *closing_sections([*_does_not(recipe), *_CONSTRAINTS], _PLAN_EXPECTED),+ ]+ )+++def render_plan_spec(detail: Mapping[str, Any]) -> str:+ """The plan with no harness wording: its steps, checks, reach and what it+ must not do, for a caller that frames the request itself (code generation,+ which cannot run the tests, so they are listed, not prescribed)."""+ recipe = build_recipe(detail)+ return join_sections(+ [+ *_plan_sections(recipe, None, runnable=False),+ _blast_section(detail),+ "## Hard constraints",+ "",+ bullet_list(_does_not(recipe)),+ ]+ )+++# -- a composed opportunity ----------------------------------------------------+++def _primary_problem(addresses: Any) -> str:+ # Tri-state: ``None`` means no dominant finding was recorded, not "no".+ if addresses is True:+ return "These steps address the file's dominant diagnosed problem."+ if addresses is False:+ return (+ "These steps do NOT address the file's dominant diagnosed problem: they are real "+ "work, but not the biggest cost in this file. Say so if something else should "+ "come first."+ )+ return (+ "No dominant problem was recorded for this file, so whether these steps address it "+ "is unknown."+ )+++def _opportunity_facts(o: Mapping[str, Any]) -> str:+ steps = o.get("step_count") or 0+ recover = o.get("recoverable_health") or 0+ cause = str(o.get("lead_biomarker") or "").replace("_", " ")+ return bullet_list(+ [+ f"Opportunity: `{o['opportunity_id']}`",+ f"File: `{o['file_path']}`",+ f"Leading cause: {cause}." if cause else None,+ f"{steps} step{'' if steps == 1 else 's'}: {o.get('mechanical_steps', 0)} "+ f"mechanical, {o.get('judgment_steps', 0)} judgment.",+ f"Recovers ~{recover:.2f} of health score if applied." if recover > 0 else None,+ f"Effort: {o.get('effort_bucket')} bucket. "+ f"Detector confidence: {o.get('confidence')}.",+ _primary_problem(o.get("addresses_primary_problem")),+ ]+ )+++def _applicability(step: Mapping[str, Any]) -> str:+ app = step.get("applicability") or {}+ kind = "Mechanical" if app.get("classification") == "mechanical" else "Judgment"+ reasons = "; ".join(r.replace("_", " ") for r in app.get("reasons") or [])+ unknowns = ", ".join(u.replace("_", " ") for u in app.get("unknowns") or [])+ out = f"{kind}: {reasons}." if reasons else f"{kind}."+ return f"{out} Not established: {unknowns}." if unknowns else out+++def _opportunity_step(step: Mapping[str, Any], n: int, plan: Mapping[str, Any] | None) -> str:+ start = step.get("line_start")+ span = {"start": start, "end": step.get("line_end") or start} if start else None+ symbol = f" (`{step['target_symbol']}`)" if step.get("target_symbol") else ""+ kind = label(step.get("refactoring_type"))+ lines = [+ f"{n}. **{kind}** at {_loc(step['file_path'], span)}{symbol}",+ f" - Step id: `{step['plan_id']}`",+ f" - {_applicability(step)}",+ ]+ if step.get("relocated_by"):+ lines.append(+ f" - **Locate it again first.** Step `{step['relocated_by']}` moves this symbol, "+ "so the path and lines above are where it was, not where it will be when you get "+ "here."+ )+ if plan is None:+ lines.append(+ f" - This step's plan was not in this payload; ask for it by id: `{step['plan_id']}`."+ )+ else:+ recipe = build_recipe(plan)+ if recipe["advisory"]:+ lines.append(f" - {_advisory_heading(recipe)}:")+ lines.extend(_step_entry(s, "-", " ") for s in recipe["steps"])+ return "\n".join(lines)+++def _evidence_row(item: Mapping[str, Any]) -> str:+ summary = item.get("summary") or {}+ detail = "; ".join(+ f"{k.replace('_', ' ')}: {v}" for k, v in summary.items() if v not in (None, "")+ )+ symbol = f" `{item['target_symbol']}`" if item.get("target_symbol") else ""+ return f"- {label(item.get('refactoring_type'))}{symbol}{f': {detail}' if detail else ''}"+++def _opportunity_evidence(o: Mapping[str, Any]) -> str:+ rows = [_evidence_row(item) for item in o.get("evidence") or []]+ if not rows:+ return ""+ if o.get("evidence_truncated"):+ rows.append(f"{o.get('evidence_emitted')} of {o.get('evidence_total')} shown.")+ return join_sections(+ [+ "## Evidence behind the diagnosis",+ "",+ "Supporting observations, not extra work.",+ "",+ "\n".join(rows),+ "",+ ]+ )+++def _profile_subjects(o: Mapping[str, Any], profile_id: Any) -> list[str]:+ """What the steps a validation profile checks change, for its heading."""+ return sorted(+ {+ s.get("target_symbol") or s["file_path"]+ for s in o.get("steps") or []+ if s.get("validation_profile_id") == profile_id+ }+ )+++def _opportunity_verify(o: Mapping[str, Any]) -> str:+ profiles = o.get("validation_profiles") or []+ blocks = []+ for profile in profiles:+ subjects = _profile_subjects(o, profile.get("id"))+ heading = (+ [f"### For {', '.join(f'`{s}`' for s in subjects)}", ""]+ if len(profiles) > 1 and subjects+ else []+ )+ blocks.append("\n".join([*heading, *_verify_lines(verify_check(profile))]))+ if not blocks:+ return ""+ return join_sections(["## Verify", "", "\n\n".join(blocks), ""])+++def _opportunity_handoff(o: Mapping[str, Any], flavor: str) -> str:+ oid = o["opportunity_id"]+ if flavor == "claude-code-mcp":+ return join_sections(+ [+ "## Pull this record yourself",+ "",+ f'`get_health(opportunity_id="{oid}")`',+ "",+ "It 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.",+ "",+ ]+ )+ return join_sections(+ ["## This opportunity's id", "", f"`{oid}`", "", "Quote it when you report back.", ""]+ )+++_OPPORTUNITY_CONSTRAINTS = (+ "**Apply the steps in the order given.** It is dependency-safe; reordering it is not.",+ "**Read a judgment step's code before applying it.** Its obligation is unproven.",+ "**Keep behaviour.** Run the tests (and type-checker / linter) before and after.",+ *_CONSTRAINTS,+)+++def render_opportunity(+ detail: Mapping[str, Any], flavor: str = "generic", repo_name: str | None = None+) -> str:+ """One composed opportunity (its detail dict, plans included) as a prompt."""+ oid = detail["opportunity_id"]+ plans = {p.get("id"): p for p in detail.get("plans") or []}+ steps = detail.get("steps") or []+ relocated = any(s.get("relocated_by") for s in steps)+ expected = [+ "1. The refactored code, with each step above applied in order.",+ "2. Per step: whether you applied it, and for anything you skipped, the reason.",+ "3. The Verify run, before and after, with its result.",+ f"4. The opportunity id `{oid}`, so the work can be matched back to the record.",+ ]+ heading = f"{label(detail.get('lead_refactoring_type'))} in `{detail['file_path']}`"+ return join_sections(+ [+ preamble(flavor, "refactoring_opportunity"),+ "",+ f"## {heading}{repo_suffix(repo_name)}",+ "",+ _opportunity_facts(detail),+ "",+ "## Steps, in order",+ "",+ f"{detail.get('ordering_note') or ''}\n" if relocated else "",+ "\n\n".join(+ _opportunity_step(s, n, plans.get(s.get("plan_id"))) for n, s in enumerate(steps, 1)+ ),+ "",+ _opportunity_evidence(detail),+ _opportunity_verify(detail),+ *closing_sections(_OPPORTUNITY_CONSTRAINTS, expected),+ _opportunity_handoff(detail, flavor),+ ]+ )+++__all__ = ["render_opportunity", "render_plan", "render_plan_spec"]diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.pyindex d83ac5576..0ec888e0d 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py@@ -8,9 +8,9 @@ the indexing hot path:1. Gather the real source spans the plan references (the class body, every cloneoccurrence, the method to move, the files on each cut edge) straight off theworking tree.-2. Build a behaviour-preservation prompt carrying the structured plan + that- source + the graph/co-change context the deterministic layer already- computed, and ask the configured provider for the refactored code and a+2. Build a behaviour-preservation prompt carrying the plan's recipe (the same+ steps, checks and limits the copy-prompt and plan detail read) + that+ source, and ask the configured provider for the refactored code and aunified diff.3. Self-check the result where it is cheap and meaningful: Extract Class with anLCOM4 before/after delta (re-walk the generated classes), Split File by@@ -29,12 +29,14 @@ import hashlibimport jsonimport refrom collections import defaultdict+from collections.abc import Mappingfrom dataclasses import asdict, dataclass, fieldfrom pathlib import Pathfrom typing import Anyimport structlog+from repowise.core.agent_prompts.refactoring import render_plan_specfrom repowise.core.providers.llm.base import BaseProvider, CacheHintlog = structlog.get_logger(__name__)@@ -240,6 +242,10 @@ def _gather_spans(suggestion: Any, repo_path: Path) -> list[SourceSpan]:# Prompt assembly# ---------------------------------------------------------------------------+#: Bumped when the prompt's wording changes, so a draft cached under the old+#: wording is not served for the new one.+_PROMPT_VERSION = 2+_SYSTEM_PROMPT = """\You are a senior software engineer performing a single, well-scoped refactoring.@@ -263,94 +269,16 @@ language.`+++ b/path`, `@@` hunks) covering every file you changed."""-_TYPE_INSTRUCTIONS: dict[str, str] = {- "extract_class": (- "Refactoring: EXTRACT CLASS. Split the class into the cohesive groups in "- "the plan — each group becomes a new class owning its listed methods and "- "fields. Keep the original class as a thin coordinator that delegates, so "- "all existing call sites keep working."- ),- "extract_helper": (- "Refactoring: EXTRACT HELPER. The occurrences are duplicates of the same "- "logic. Extract one shared helper (place it at the suggested site) and "- "replace every occurrence with a call to it."- ),- "move_method": (- "Refactoring: MOVE METHOD. Move the method from its current class to the "- "target class it is more cohesive with, and update the call sites. Leave a "- "thin delegating wrapper only if removing the method outright would break "- "callers you cannot see."- ),- "break_cycle": (- "Refactoring: BREAK IMPORT CYCLE. Remove the cyclic dependency by "- "inverting or abstracting the import on each cut edge (dependency "- "inversion, a shared interface/protocol module, or a local import as a "- "last resort). Do not merge the files."- ),- "extract_method": (- "Refactoring: EXTRACT METHOD. The target is one long function; the plan's "- "'span' gives the line range to lift into a new helper method in the same "- "scope. Move exactly those lines into the helper and name it: the plan's "- "'suggested_name' is a deterministic starting point derived from the "- "slice's single output value, so keep it unless the code clearly warrants a better "- "name -- and rename it if it collides with something already in the file, "- "which it can. When 'suggested_name' is null no name was anchored in the plan "- "and the texts below read '<name>': choose one that describes what the lifted "- "code does. The plan's 'new_symbol.signature_text' is the helper's header and "- "'call_site.new_text' the statement that replaces the span; use both, filling "- "any '<name>' or '<type>' placeholder, and follow 'new_symbol.notes'. "- "Without them (an older plan, or one whose helper form is unknown), pass the plan's 'params' "- "as its arguments, return the plan's 'returns' value(s), and replace the "- "original lines with a call to it. When the plan's 'needs_async' is true the span awaits: "- "declare the helper async and await the call that replaces the lines. "- "When the plan's 'new_symbol.kind' is 'method' the span uses its receiver "- "('new_symbol.receiver'): make the helper a method of the same object and "- "call it through that receiver rather than passing it as an argument. "- "Preserve behaviour exactly; change nothing outside the "- "span and the single call site."- ),- "split_file": (- "Refactoring: SPLIT FILE. The module is too large and partitions into "- "the cohesive groups in the plan. Create one new file per group at its "- "'suggested_file' path, containing exactly that group's symbols, and "- "when a group's 'suggested_file' is null pick a filename that describes "- "its symbols, in the same directory as the original, and "- "remove them from the original. Keep the residual 'core' symbols in the "- "original file. When 'shim_required' is true, leave a back-compat "- "re-export shim in the original path (import and re-export the moved "- "symbols) so existing imports keep working; when false (same-package "- "languages such as Go) no import edits are needed. Never duplicate a "- "symbol across files — each moves to exactly one place. Emit one fenced "- "code block per file you create or change."- ),-}+def _build_user_prompt(+ suggestion: Any, spans: list[SourceSpan], detail: Mapping[str, Any] | None = None+) -> str:+ """The plan as every surface words it (its recipe), then the source it names.-def _build_user_prompt(suggestion: Any, spans: list[SourceSpan]) -> str:- """Render the plan + evidence + blast radius + source into a user prompt."""- rtype = suggestion.refactoring_type- parts: list[str] = []- parts.append(_TYPE_INSTRUCTIONS.get(rtype, f"Refactoring: {rtype}."))- parts.append(f"\nTarget: {suggestion.target_symbol} ({suggestion.file_path})")-- parts.append("\n## Structured plan\n")- parts.append("```json")- parts.append(- json.dumps(- {- "type": rtype,- "plan": suggestion.plan or {},- "evidence": suggestion.evidence or {},- "blast_radius": suggestion.blast_radius or {},- "validation": getattr(suggestion, "validation", {}) or {},- },- indent=2,- sort_keys=True,- )- )- parts.append("```")-- parts.append("\n## Source spans\n")+ *detail* is the stored plan detail (risks, decisions, per-step checks) when+ the caller has it; a live suggestion stands in for it otherwise.+ """+ parts = [render_plan_spec(detail or asdict(suggestion)), "\n## Source spans\n"]if not spans:parts.append("_(no source spans were resolvable from the working tree)_")for span in spans:@@ -408,9 +336,13 @@ def _language_for(file_path: str) -> str | None:return _EXT_LANGUAGE.get(Path(file_path).suffix.lower())-def _cache_key(suggestion: Any, spans: list[SourceSpan], model: str) -> str:+def _cache_key(suggestion: Any, spans: list[SourceSpan], model: str, prompt: str) -> str:+ """*prompt* is the rendered user prompt: anything that changes it (the stored+ detail a caller passes, the recipe's wording) misses the cache."""payload = json.dumps({+ "prompt_version": _PROMPT_VERSION,+ "prompt": hashlib.sha256(prompt.encode()).hexdigest(),"type": suggestion.refactoring_type,"target": suggestion.target_symbol,"file": suggestion.file_path,@@ -671,6 +603,7 @@ async def enrich_suggestion(provider: BaseProvider,repo_path: Path,cache_dir: Path | None = None,+ detail: Mapping[str, Any] | None = None,use_cache: bool = True,validate: bool = True,max_tokens: int = 8000,@@ -680,6 +613,7 @@ async def enrich_suggestion(On-demand only. Gathers the plan's source spans off *repo_path*, prompts*provider*, parses the diff, runs the Extract Class self-check, and cachesthe result by a content hash so an unchanged plan never regenerates.+ *detail* is the stored plan detail, when the caller read one."""spans = _gather_spans(suggestion, repo_path)model = getattr(provider, "model_name", "") or ""@@ -687,14 +621,14 @@ async def enrich_suggestion(suggestion_id = getattr(suggestion, "id", None)cdir = cache_dir or _cache_dir(repo_path)- key = _cache_key(suggestion, spans, model)+ user = _build_user_prompt(suggestion, spans, detail)+ key = _cache_key(suggestion, spans, model, user)if use_cache:cached = _read_cache(cdir, key)if cached is not None:return cached- system = _SYSTEM_PROMPT + "\n" + _TYPE_INSTRUCTIONS.get(suggestion.refactoring_type, "")- user = _build_user_prompt(suggestion, spans)+ system = _SYSTEM_PROMPTresponse = await provider.generate(system,user,diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recipe.py b/packages/core/src/repowise/core/analysis/health/refactoring/recipe.pynew file mode 100644index 000000000..0736c9518--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recipe.py@@ -0,0 +1,552 @@+"""One plan as a recipe an agent applies: an id, what must hold before the edit,+the edits in order, what must hold after, and what the edit must not do.++The shape borrows the recipe idea from automated-refactoring tools (id,+preconditions, steps, postconditions) so a stored plan reads the same on plan+detail, in the CLI's JSON and in the copy-prompt+(:mod:`repowise.core.agent_prompts.refactoring`). Repowise never applies an+edit: every step is a spec an agent carries out.++Input is a plan detail dict (:meth:`Recommendation.detail_dict`, or the stored+plan payload an opportunity embeds); every field is read defensively, so an+older row yields a shorter recipe rather than an error.+"""++from __future__ import annotations++from collections.abc import Callable, Mapping+from typing import Any, Literal, get_args++from .annotations import RiskKind+from .render import NAME_PLACEHOLDER, TYPE_PLACEHOLDER++RecipeAction = Literal[+ "extract",+ "add_helper",+ "replace_with_call",+ "extract_class",+ "move",+ "cut_import",+ "keep",+ "reexport",+ "edit",+]+RECIPE_ACTIONS: tuple[str, ...] = get_args(RecipeAction)+#: What a precondition is: a test run or a test to add first, a plan risk, a plan+#: whose risks were never checked, or a plan type whose output is not yet audited.+PRECONDITION_KINDS: tuple[str, ...] = (+ "tests",+ "characterization",+ *get_args(RiskKind),+ "unchecked",+ "kind_unaudited",+)++#: The heading each plan type's prompt carries.+TYPE_LABEL: dict[str, str] = {+ "performance_fix": "Performance",+ "extract_class": "Extract Class",+ "extract_helper": "Extract Helper",+ "extract_method": "Extract Method",+ "move_method": "Move Method",+ "break_cycle": "Break Cycle",+ "split_file": "Split File",+}++_KEEP_BEHAVIOUR = {+ "constraint": "change behaviour",+ "reason": "what the code returns, raises or writes stays the same",+}+#: Types whose steps are one way to do it, not the edit to make.+_ADVISORY = frozenset({"break_cycle"})+#: Types whose plans have not been through an accuracy audit yet.+_UNAUDITED = frozenset({"move_method", "extract_class"})++_STRATEGY_SUMMARY: dict[str, str] = {+ "batch_or_prefetch_io": "Batch the repeated per-item calls",+ "parallelize_independent_awaits": "Run the independent awaits concurrently",+ "replace_membership_collection": "Probe a set instead of searching a list",+ "buffer_string_accumulation": "Join the string once instead of growing it in a loop",+ "shrink_lock_scope": "Move the I/O out of the locked section",+ "push_reduction_into_query": "Let the query do the reduction",+}++Step = dict[str, Any]++#: Types whose ``target_symbol`` is a display label (``big.py -> 3 files``), not a symbol.+_LABEL_TARGETS = frozenset({"split_file", "break_cycle", "extract_helper"})+++def label(refactoring_type: str | None) -> str:+ return TYPE_LABEL.get(refactoring_type or "", "Refactoring")+++def _dict(value: Any) -> dict[str, Any]:+ return value if isinstance(value, dict) else {}+++def _list(value: Any) -> list[Any]:+ return value if isinstance(value, list) else []+++def _strs(value: Any) -> list[str]:+ return [str(item) for item in _list(value) if item]+++def _code(items: list[str]) -> str:+ return ", ".join(f"`{item}`" for item in items)+++def _span(start: Any, end: Any = None) -> dict[str, int] | None:+ if not isinstance(start, int) or start <= 0:+ return None+ return {"start": start, "end": end if isinstance(end, int) and end >= start else start}+++def _step(+ action: RecipeAction, file: str | None, span: dict[str, int] | None, text: str, **extra: Any+) -> Step:+ return {"action": action, "file": file, "span": span, "text": text, **extra}+++def _count(value: Any) -> int:+ return value if isinstance(value, int) and not isinstance(value, bool) else 0+++def _short(symbol: str | None) -> str:+ return (symbol or "").rsplit("::", 1)[-1]+++def _s(count: int) -> str:+ return "" if count == 1 else "s"+++# -- steps, per plan type ------------------------------------------------------+++def _extract_method(d: Mapping[str, Any], plan: Mapping[str, Any]) -> list[Step]:+ span = _dict(plan.get("span"))+ where = _span(span.get("start"), span.get("end"))+ host = _short(d.get("target_symbol"))+ name = plan.get("suggested_name") or NAME_PLACEHOLDER+ if where is None:+ text = f"Extract a slice of `{host}` into a helper."+ 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)"+ )+ text = (+ f"Move lines {where['start']}-{where['end']} of `{host}` into a new helper "+ f"`{name}`{named} in the same scope, and replace them with one call to it."+ )+ return [+ _step(+ "extract",+ d.get("file_path"),+ where,+ text,+ new_symbol={+ "name": name,+ "kind": symbol.get("kind"),+ "async": is_async,+ "params": _strs(plan.get("params")),+ "returns": _strs(plan.get("returns")),+ "signature_text": symbol.get("signature_text"),+ "notes": _extract_notes(plan, symbol, is_async),+ },+ **({"call_site": plan["call_site"]} if _dict(plan.get("call_site")) else {}),+ )+ ]+++def _extract_notes(+ plan: Mapping[str, Any], symbol: Mapping[str, Any], is_async: bool+) -> list[str]:+ notes = _strs(symbol.get("notes"))+ if is_async and not symbol.get("signature_text"):+ notes.append("The lines await, so declare the helper async and await its call.")+ if symbol.get("kind") == "method" and not symbol.get("signature_text"):+ notes.append(+ "The lines use their object, so make the helper a method of the same object."+ )+ if plan.get("receiver_hazard"):+ notes.append(+ "Lifting the lines changes which object they read or write; check the helper "+ "still sees the same one."+ )+ call = _dict(plan.get("call_site")).get("new_text") or ""+ texts = f"{symbol.get('signature_text') or ''} {call}"+ if NAME_PLACEHOLDER in texts or TYPE_PLACEHOLDER in texts:+ notes.append(+ f"Fill each `{NAME_PLACEHOLDER}` / `{TYPE_PLACEHOLDER}` placeholder from the code."+ )+ return notes+++def _extract_helper(d: Mapping[str, Any], plan: Mapping[str, Any]) -> list[Step]:+ occurrences = [_dict(o) for o in _list(plan.get("occurrences"))]+ site = _dict(plan.get("suggested_site"))+ where = site.get("directory") or site.get("module")+ name = plan.get("suggested_name") or NAME_PLACEHOLDER+ lines = plan.get("duplicated_lines")+ size = f" ({lines} lines)" if isinstance(lines, int) and lines else ""+ # The site is a directory: the file the helper goes in is the agent's call.+ first = _step(+ "add_helper",+ None,+ None,+ f"Add one helper `{name}`{f' in `{where}`' if where else ''} holding the duplicated block"+ f"{size}; a difference between the sites becomes a parameter.",+ directory=where,+ )+ return [first] + [+ _step(+ "replace_with_call",+ o.get("file"),+ _span(o.get("line_start"), o.get("line_end")),+ "Replace these lines with a call to the helper.",+ )+ for o in occurrences+ ]+++def _extract_class(d: Mapping[str, Any], plan: Mapping[str, Any]) -> list[Step]:+ host = d.get("target_symbol") or "the class"+ span = _span(d.get("line_start"), d.get("line_end"))+ groups = [_dict(g) for g in _list(plan.get("groups"))]+ groups = [g for g in groups if _list(g.get("methods")) or _list(g.get("fields"))]+ steps = [+ _step(+ "extract_class",+ d.get("file_path"),+ span,+ f"Move {_members(g)} out of `{host}` into a new class "+ f"`{g.get('name') or f'NewClass{i}'}`; they only use each other.",+ )+ for i, g in enumerate(groups, 1)+ ]+ steps.append(+ _step(+ "edit",+ d.get("file_path"),+ span,+ f"Keep `{host}` as a thin facade that delegates to the new classes, so callers "+ "outside it keep working.",+ )+ )+ return steps+++def _members(group: Mapping[str, Any]) -> str:+ methods, fields = _strs(group.get("methods")), _strs(group.get("fields"))+ parts = [+ f"methods {_code(methods)}" if methods else "",+ f"fields {_code(fields)}" if fields else "",+ ]+ return " and ".join(p for p in parts if p)+++def _move_method(d: Mapping[str, Any], plan: Mapping[str, Any]) -> list[Step]:+ method = plan.get("method") or _short(d.get("target_symbol"))+ to_file = plan.get("to_file")+ dest = f"`{plan.get('to_class') or 'its target class'}`"+ dest += f" in `{to_file}`" if to_file else ""+ return [+ _step(+ "move",+ d.get("file_path"),+ _span(d.get("line_start"), d.get("line_end")),+ f"Move `{method}` from `{plan.get('from_class') or 'its class'}` to {dest}, "+ "then update every call site; keep a delegating wrapper only for callers you "+ "cannot reach.",+ to_file=to_file,+ )+ ]+++def _break_cycle(d: Mapping[str, Any], plan: Mapping[str, Any]) -> list[Step]:+ return [+ _step(+ "cut_import",+ edge.get("from"),+ None,+ f"Remove the import of `{edge.get('to')}`: invert the dependency or move what both "+ "need into a module neither imports. A function-local import only if it really "+ "breaks the cycle.",+ )+ for edge in (_dict(e) for e in _list(plan.get("cut_edges")))+ ]+++def _split_file(d: Mapping[str, Any], plan: Mapping[str, Any]) -> list[Step]:+ path = d.get("file_path")+ groups = [_dict(g) for g in _list(plan.get("groups"))]+ steps = [+ _step(+ "move",+ g.get("suggested_file"),+ None,+ f"Move {_code(_strs(g.get('symbols')))} to "+ + (f"`{g['suggested_file']}`" if g.get("suggested_file") else f"a new file (part {i})")+ + " (a starting name; follow the repo's convention).",+ symbols=_strs(g.get("symbols")),+ )+ for i, g in enumerate((g for g in groups if _list(g.get("symbols"))), 1)+ ]+ residual = _strs(_dict(plan.get("residual")).get("symbols"))+ if residual:+ text = f"Leave {_code(residual)} in `{path}`: more than one group uses them."+ steps.append(_step("keep", path, None, text))+ if plan.get("shim_required") is False:+ text = "Files in one package share scope, so no import changes are needed."+ steps.append(_step("edit", path, None, text))+ else:+ text = f"Keep `{path}` importable: re-export the moved symbols, or update every importer."+ steps.append(_step("reexport", path, None, text))+ return steps+++def _merged_verify(kept: Mapping[str, Any] | None, more: Mapping[str, Any] | None) -> Any:+ """Two checks for one edit as one: the union of their commands and tests."""+ if not kept or not more:+ return kept or more+ out = dict(kept)+ for key in ("commands", "tests"):+ out[key] = list(dict.fromkeys([*_strs(kept.get(key)), *_strs(more.get(key))]))+ return out+++def _performance_fix(d: Mapping[str, Any], plan: Mapping[str, Any]) -> list[Step]:+ out: dict[tuple[Any, ...], Step] = {}+ for index, raw in enumerate(_list(plan.get("steps"))):+ step = _dict(raw)+ symbol = _short(step.get("symbol"))+ text = str(step.get("action") or "Apply the fix")+ verify = step["verify"] if isinstance(step.get("verify"), dict) else None+ # A site the evidence lists twice is still one edit, checked by both checks.+ # Only a placed site is known to repeat; a step without a line stays its own.+ line = step.get("line")+ key = (text, symbol, step.get("file_path"), line) if line is not None else (index,)+ if key in out:+ merged = _merged_verify(out[key].get("verify"), verify)+ if merged:+ out[key]["verify"] = merged+ continue+ where = f" in `{symbol}`" if symbol and symbol not in text else ""+ out[key] = _step(+ "edit",+ step.get("file_path"),+ _span(step.get("line")),+ f"{text}{where}.",+ applicability=step.get("applicability"),+ **({"verify": verify} if verify else {}),+ )+ return list(out.values())+++_STEPS: dict[str, Callable[[Mapping[str, Any], Mapping[str, Any]], list[Step]]] = {+ "extract_method": _extract_method,+ "extract_helper": _extract_helper,+ "extract_class": _extract_class,+ "move_method": _move_method,+ "break_cycle": _break_cycle,+ "split_file": _split_file,+ "performance_fix": _performance_fix,+}+++def recipe_steps(detail: Mapping[str, Any]) -> list[Step]:+ """The plan's edits in order, numbered from 1."""+ build = _STEPS.get(str(detail.get("refactoring_type") or ""))+ plan = _dict(detail.get("plan"))+ steps = build(detail, plan) if build else []+ if not steps:+ text = "Apply the change the plan describes."+ steps = [_step("edit", detail.get("file_path"), None, text)]+ return [{"n": n, **step} for n, step in enumerate(steps, 1)]+++# -- the rest of the recipe ----------------------------------------------------+++def _summary(d: Mapping[str, Any], steps: list[Step]) -> str:+ kind, plan = d.get("refactoring_type"), _dict(d.get("plan"))+ if kind == "extract_method" and steps[0].get("span"):+ span, name = steps[0]["span"], steps[0]["new_symbol"]["name"]+ host = _short(d.get("target_symbol"))+ return f"Extract lines {span['start']}-{span['end']} of `{host}` into `{name}`."+ if kind == "extract_helper":+ return f"Replace the block duplicated at {len(steps) - 1} sites with one shared helper."+ if kind == "extract_class":+ return f"Split `{d.get('target_symbol')}` into {len(steps) - 1} cohesive classes."+ if kind == "split_file":+ moves = sum(s["action"] == "move" for s in steps)+ return f"Split `{d.get('file_path')}`: move {moves} groups of symbols into their own files."+ if kind == "break_cycle":+ size, cuts = len(_list(plan.get("cycle"))), len(steps)+ return f"Break the {size}-file import cycle by cutting {cuts} import{_s(cuts)}."+ if kind == "performance_fix":+ lead = _STRATEGY_SUMMARY.get(str(plan.get("strategy")), "Apply the performance fix")+ return f"{lead} in `{_short(d.get('target_symbol'))}`."+ return steps[0]["text"]+++def _preconditions(d: Mapping[str, Any]) -> list[dict[str, Any]]:+ validation = _dict(d.get("validation"))+ out: list[dict[str, Any]] = []+ if _strs(validation.get("tests")) or _count(validation.get("total")):+ out.append({"kind": "tests", "text": "The guarding tests pass before the edit."})+ if validation.get("prerequisite"):+ out.append({"kind": "characterization", "text": str(validation["prerequisite"])})+ if d.get("refactoring_type") in _UNAUDITED:+ text = "This plan type is not yet audited for accuracy; confirm it fits before applying."+ out.append({"kind": "kind_unaudited", "text": text})+ if "risks" not in d and "governed_by" not in d:+ # Absent is "never checked" (an older row), not "nothing found".+ text = "Risks and governing decisions were not checked for this plan."+ out.append({"kind": "unchecked", "text": text})+ risks = [_dict(r) for r in _list(d.get("risks"))]+ out.extend(+ {"kind": r["kind"], "text": r["text"], **({"ref": r["ref"]} if r.get("ref") else {})}+ for r in risks+ if r.get("kind") and r.get("text")+ )+ shown = {r.get("ref") for r in risks}+ out.extend(+ {"kind": "decision", "text": f"Decision `{ref}` also governs this file; read it.", "ref": ref}+ for ref in _strs(d.get("governed_by"))+ if ref not in shown+ )+ return out+++def verify_check(validation: Any) -> dict[str, Any]:+ """The ``verify`` postcondition for a plan's (or a shared profile's) validation."""+ validation = _dict(validation)+ if not validation:+ text = "The tests that exercise the change pass; add one if none does."+ return {"kind": "verify", "text": text}+ tests = _strs(validation.get("tests"))+ total = validation.get("total") if isinstance(validation.get("total"), int) else len(tests)+ if tests:+ text = "The guarding tests pass after the edit, unchanged."+ elif total:+ text = f"The {total} guarding tests (not listed here) pass after the edit."+ else:+ text = "No guarding test was found; the test added before the edit passes after it."+ return {+ "kind": "verify",+ "text": text,+ "tests": tests,+ "tests_total": max(total, len(tests)),+ "commands": _strs(validation.get("commands")),+ "basis": validation.get("basis"),+ **({"reasons": validation["reasons"]} if _dict(validation.get("reasons")) else {}),+ }+++def _metric(d: Mapping[str, Any]) -> str | None:+ kind, ev = d.get("refactoring_type"), _dict(d.get("evidence"))+ host = _short(d.get("target_symbol"))+ if kind == "extract_method" and ev.get("ccn_removed"):+ return f"`{host}` loses about {ev['ccn_removed']} branches of cyclomatic complexity."+ if kind == "extract_helper" and ev.get("duplicated_lines"):+ return f"The {ev['duplicated_lines']} duplicated lines exist once."+ if kind == "extract_class" and ev.get("lcom4"):+ return f"Each new class is one cohesive group (LCOM4 1; `{host}` is {ev['lcom4']} today)."+ if kind == "split_file" and ev.get("file_nloc"):+ return f"No resulting file is near the original's {ev['file_nloc']} lines."+ if kind == "break_cycle" and ev.get("cycle_size"):+ return f"The {ev['cycle_size']}-file import cycle is gone."+ if kind == "performance_fix":+ sites = _dict(d.get("blast_radius")).get("call_sites")+ if sites:+ return f"The repeated work no longer runs once per item at {sites} call site{_s(sites)}."+ return None+++def _postconditions(d: Mapping[str, Any]) -> list[dict[str, Any]]:+ out = [verify_check(d.get("validation"))]+ metric = _metric(d)+ if metric:+ out.append({"kind": "metric", "text": metric})+ impact = d.get("impact_delta")+ if isinstance(impact, (int, float)) and impact > 0:+ out.append({"kind": "metric", "text": f"File health recovers about {impact:.2f}."})+ return out+++#: Per type, what the edit must not do and, when it is not obvious, why.+_DOES_NOT: dict[str, tuple[str, str | None]] = {+ "extract_helper": ("merge sites that differ", "a difference between them becomes a parameter"),+ "extract_class": ("rename or remove anything callers outside the class use", None),+ "move_method": ("leave a call site pointing at the old class", None),+ "break_cycle": ("merge the files in the cycle", None),+ "split_file": ("put one symbol in two files", None),+ "performance_fix": (+ "change the results or errors the batched or reordered calls produce",+ None,+ ),+}+++def _does_not(d: Mapping[str, Any], steps: list[Step]) -> list[dict[str, str | None]]:+ """What the edit must not do, each a phrase read after "Do not", with its reason."""+ out: list[dict[str, str | None]] = [dict(_KEEP_BEHAVIOUR)]+ kind = str(d.get("refactoring_type") or "")+ span = steps[0].get("span")+ if kind == "extract_method" and span:+ lines = f"{span['start']}-{span['end']}"+ out.append(+ {"constraint": f"touch anything outside lines {lines} and the call that replaces them",+ "reason": None}+ )+ elif kind in _DOES_NOT:+ constraint, reason = _DOES_NOT[kind]+ out.append({"constraint": constraint, "reason": reason})+ if any(s.get("applicability") == "judgment" for s in steps):+ out.append(+ {"constraint": "apply a judgment step without reading the code it names first",+ "reason": None}+ )+ return out+++def build_recipe(detail: Mapping[str, Any]) -> dict[str, Any]:+ """*detail* as ``{id, kind, advisory, summary, target, preconditions, steps,+ postconditions, does_not}``. Pure: reads only the dict it is given."""+ steps = recipe_steps(detail)+ return {+ "id": detail.get("id"),+ "kind": detail.get("refactoring_type"),+ # The steps are one way to do it, for a person to judge, not an edit to apply.+ "advisory": detail.get("refactoring_type") in _ADVISORY,+ "summary": _summary(detail, steps),+ "target": {+ "file": detail.get("file_path"),+ "symbol": (detail.get("target_symbol") or None)+ if detail.get("refactoring_type") not in _LABEL_TARGETS+ else None,+ "span": _span(detail.get("line_start"), detail.get("line_end")),+ },+ "preconditions": _preconditions(detail),+ "steps": steps,+ "postconditions": _postconditions(detail),+ "does_not": _does_not(detail, steps),+ }+++__all__ = [+ "PRECONDITION_KINDS",+ "RECIPE_ACTIONS",+ "TYPE_LABEL",+ "RecipeAction",+ "build_recipe",+ "label",+ "recipe_steps",+ "verify_check",+]diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/details.py b/packages/server/src/repowise/server/mcp_server/tool_health/details.pyindex c44c2b103..230c463f7 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/details.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/details.py@@ -7,6 +7,7 @@ from typing import Anyfrom sqlalchemy import selectfrom repowise.core.analysis.health.counts import DEFAULT_COUNTS+from repowise.core.analysis.health.refactoring.recipe import build_recipefrom repowise.core.analysis.health.refactoring.serving import evidence_blockfrom repowise.core.analysis.health.scope import DEFAULT_SCOPEfrom repowise.core.analysis.health.worth import LOW_PRIORITY_LABEL, finding_priorities@@ -43,6 +44,7 @@ async def _detail_response(only_set: set[str],limit: int,cursor: int,+ recipe: bool = False,) -> dict[str, Any] | None:"""Answer a lookup by id, or ``None`` when no selector was passed.@@ -76,7 +78,9 @@ async def _detail_response(cursor=cursor,)if plan_id:- return await _plan_detail_response(session, repository, reference_repository, plan_id)+ return await _plan_detail_response(+ session, repository, reference_repository, plan_id, recipe=recipe+ )return None@@ -131,9 +135,10 @@ async def _fix_detail_response(session: Any, repository: Any, fix_id: str) -> diasync def _plan_detail_response(- session: Any, repository: Any, reference_repository: str, plan_id: str+ session: Any, repository: Any, reference_repository: str, plan_id: str, *, recipe: bool) -> dict[str, Any]:- """One stored plan, and the composed opportunity it is a step of, if any.+ """One stored plan, and the composed opportunity it is a step of, if any;+ with *recipe*, also the plan as the recipe an agent applies.An indexed seek and one hydration, not a scan of every open plan."""@@ -143,6 +148,8 @@ async def _plan_detail_response(if plan is not None:plan.setdefault("id", plan_id)plan["repository"] = reference_repository+ if recipe:+ plan["recipe"] = build_recipe(plan)result = {"mode": "refactoring_plan","plan_id": plan_id,diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/request.py b/packages/server/src/repowise/server/mcp_server/tool_health/request.pyindex 08e095d67..e3c18111f 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/request.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/request.py@@ -59,6 +59,8 @@ _KNOWN_INCLUDES = frozenset("unverified",# The shared legend for deficit points and percentiles, in ``_meta``."semantics",+ # With ``plan_id``: the plan as preconditions, steps and postconditions.+ "recipe",})diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/tool.py b/packages/server/src/repowise/server/mcp_server/tool_health/tool.pyindex 0eecf07a1..848951b12 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/tool.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/tool.py@@ -157,15 +157,15 @@ async def get_health(targets: file paths or ``module:<name>``; misses land in ``unresolved``.include: ``biomarkers``|``refactoring``|``trend``|``coverage``|``accuracy``|``signals``|``churn_complexity``|``doc_drift``|- ``semantics``, or a dimension incl. ``advisory``; ``performance`` and- ``refactoring`` add queues.+ ``semantics``|``recipe``, or a dimension incl. ``advisory``;+ ``performance`` and ``refactoring`` add queues.only: keys to keep; identity, totals, recovery survive.``biomarkers``/``accuracy``/``refactoring`` alias their block key;``performance``/``defect``/``maintainability``/``advisory``do not: they filter rows into ``unknown_only_keys``.repo: usually omitted.limit: max rows per ranked list (default 20), ``0`` for none.- cursor: zero-based offset into a ranked list.+ cursor: offset into a ranked list.fix_id/finding_id/plan_id: stable ``id`` of an item, finding or plan.opportunity_id: ``perf...``/``refop...``: the unit, its steps orplan, evidence paged by ``only=["*_evidence"]``.@@ -223,6 +223,7 @@ async def get_health(only_set=req.only_set,limit=req.limit,cursor=req.cursor,+ recipe="recipe" in req.include_set,)if detail is not None:_attach_semantics(detail, req)diff --git a/packages/server/src/repowise/server/mcp_server/tool_refactoring.py b/packages/server/src/repowise/server/mcp_server/tool_refactoring.pyindex 99751af93..c33b1175c 100644--- a/packages/server/src/repowise/server/mcp_server/tool_refactoring.py+++ b/packages/server/src/repowise/server/mcp_server/tool_refactoring.py@@ -89,6 +89,7 @@ async def generate_refactoring_code(suggestion_id: str, repo: str | None = None)session, repository.id, ctx.alias or repository.name).plan_recommendation(row)sug = recommendation.suggestion+ detail = {**recommendation.detail_dict(), "id": row.public_id or row.id}meta = _build_meta(repository=repository)from repowise.server.mcp_server.tool_health import _serialize_refactoring@@ -117,7 +118,7 @@ async def generate_refactoring_code(suggestion_id: str, repo: str | None = None)except ValueError as exc:return {"error": "no_provider", "detail": str(exc), "_meta": meta}- result = await enrich_suggestion(sug, provider=provider, repo_path=repo_path)+ result = await enrich_suggestion(sug, provider=provider, repo_path=repo_path, detail=detail)payload = result.to_dict()payload["suggestion_id"] = public_plan["id"]payload["resolved"] = Truediff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.pyindex f259fc4ce..6e2a517fb 100644--- a/packages/server/src/repowise/server/routers/refactoring.py+++ b/packages/server/src/repowise/server/routers/refactoring.py@@ -19,6 +19,8 @@ from fastapi import APIRouter, Depends, HTTPException, Queryfrom pydantic import BaseModel, Fieldfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.agent_prompts import Flavor, render_opportunity, render_plan+from repowise.core.analysis.health.refactoring.recipe import build_recipefrom repowise.core.analysis.health.refactoring.serving import (CANONICAL_ORDERS,CANONICAL_VIEWS,@@ -35,11 +37,16 @@ from repowise.server.schemas import (RefactoringPlanStatusResponse,RefactoringRollupResponse,)+from repowise.server.schemas.agent_prompts import AgentPromptResponsefrom repowise.server.services.refactoring_health import PlanListQuery, RefactoringHealthService_STEPS_PER_ROW = 3"""Steps carried on a queue row; the detail call pages the rest."""+_PROMPT_STEPS = 50+_PROMPT_EVIDENCE = 20+"""What an opportunity prompt inlines: the pages the web drawer reads."""+router = APIRouter(prefix="/api/repos",tags=["refactoring"],@@ -106,6 +113,9 @@ class RefactoringPlanDetailResponse(RefactoringPlanResponse):governed_by: list[str] | None = Nonerisks: list[PlanRiskResponse] | None = None+ # Only with ``include=recipe``: the plan as preconditions, steps and+ # postconditions an agent applies (``refactoring.recipe``).+ recipe: dict[str, Any] | None = Noneclass RefactoringTypeCount(BaseModel):@@ -416,6 +426,27 @@ async def get_refactoring_opportunity_detail(return detail+ "/{repo_id}/refactoring/opportunities/{opportunity_id}/prompt",+ response_model=AgentPromptResponse,+)+async def get_refactoring_opportunity_prompt(+ repo_id: str,+ opportunity_id: str,+ flavor: Flavor = Query("generic"),+ session: AsyncSession = Depends(get_db_session),+) -> AgentPromptResponse:+ """One opportunity, its ordered steps and their plans, as an agent prompt."""+ repo = await _repository(session, repo_id)+ detail = await _service(session, repo_id).detail(+ opportunity_id, step_limit=_PROMPT_STEPS, evidence_limit=_PROMPT_EVIDENCE+ )+ if not detail.get("found"):+ raise HTTPException(status_code=404, detail="Unknown opportunity id")+ text = render_opportunity(detail, flavor, repo.name)+ return AgentPromptResponse(flavor=flavor, text=text)++class RefactoringOpportunityStatusUpdate(BaseModel):"""The finding-triage vocabulary, applied to a whole opportunity."""@@ -518,14 +549,51 @@ async def update_refactoring_settings(async def get_refactoring_plan(repo_id: str,suggestion_id: str,+ include: Literal["recipe"] | None = Query(None),session: AsyncSession = Depends(get_db_session),) -> RefactoringPlanDetailResponse:"""One plan + its blast radius detail (deep-link / drill-down target)."""+ detail, public_id = await _plan_detail(session, repo_id, suggestion_id)+ if include == "recipe":+ detail["recipe"] = build_recipe({**detail, "id": public_id})+ return RefactoringPlanDetailResponse(**detail)+++async def _plan_detail(+ session: AsyncSession, repo_id: str, suggestion_id: str+) -> tuple[dict[str, Any], str]:+ """The plan's detail dict and the public id an agent quotes back (the+ detail's own ``id`` is the storage key this route has always served)."""row = await crud.get_refactoring_suggestion(session, repo_id, suggestion_id)if row is None:raise HTTPException(status_code=404, detail=f"refactoring plan not found: {suggestion_id}")recommendation = await _service(session, repo_id).plan_recommendation(row)- return RefactoringPlanDetailResponse(**recommendation.detail_dict())+ return recommendation.detail_dict(), row.public_id or row.id+++async def _repository(session: AsyncSession, repo_id: str) -> Any:+ """The repository a prompt route names in its heading; 404 when unknown."""+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")+ return repo+++ "/{repo_id}/refactoring/{suggestion_id}/prompt",+ response_model=AgentPromptResponse,+)+async def get_refactoring_plan_prompt(+ repo_id: str,+ suggestion_id: str,+ flavor: Flavor = Query("generic"),+ session: AsyncSession = Depends(get_db_session),+) -> AgentPromptResponse:+ """One plan as the prompt an agent starts from, worded for its harness."""+ repo = await _repository(session, repo_id)+ detail, public_id = await _plan_detail(session, repo_id, suggestion_id)+ text = render_plan({**detail, "id": public_id}, flavor, repo.name)+ return AgentPromptResponse(flavor=flavor, text=text)class RefactoringStatusUpdate(BaseModel):@@ -642,6 +710,7 @@ async def generate_refactoring_code(raise HTTPException(status_code=404, detail=f"refactoring plan not found: {suggestion_id}")recommendation = await _service(session, repo_id).plan_recommendation(row)sug = recommendation.suggestion+ detail = {**recommendation.detail_dict(), "id": row.public_id or row.id}body = body or GenerateCodeRequest()try:@@ -654,5 +723,5 @@ async def generate_refactoring_code(except ValueError as exc:raise HTTPException(status_code=400, detail=str(exc)) from exc- result = await enrich_suggestion(sug, provider=provider, repo_path=repo_path)+ result = await enrich_suggestion(sug, provider=provider, repo_path=repo_path, detail=detail)return GenerateCodeResponse(**result.to_dict())diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex f4d3a00fa..58ffcd5e7 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -2782,6 +2782,7 @@ export interface RefactoringPlanDetailResponse {validation?: Record<string, unknown>;governed_by?: string[] | null;risks?: PlanRiskResponse[] | null;+ recipe?: Record<string, unknown> | null;}/** Bounded product page; the legacy targets response remains unpaged. */diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.tsindex 62c810261..522186344 100644--- a/packages/types/src/refactoring.ts+++ b/packages/types/src/refactoring.ts@@ -129,6 +129,90 @@ export interface RefactoringPlan {/** Plan detail only: what to check before applying it. Absent when the* plan was never checked; empty when nothing was found. */risks?: PlanRisk[];+ /** Plan detail with `include=recipe` only: the plan as an agent applies it. */+ recipe?: RefactoringRecipe;+}++/** What one recipe step does to the code. Mirrors ``refactoring.recipe.RECIPE_ACTIONS``. */+export type RecipeAction =+ | "extract"+ | "add_helper"+ | "replace_with_call"+ | "extract_class"+ | "move"+ | "cut_import"+ | "keep"+ | "reexport"+ | "edit";++/** What must hold before the edit: tests that pass, a characterization test to+ * add, a plan risk, risks never checked (`unchecked`), or a plan type not yet+ * audited (`kind_unaudited`). Mirrors ``refactoring.recipe.PRECONDITION_KINDS``. */+export type RecipePreconditionKind =+ | "tests"+ | "characterization"+ | "decision"+ | "public_api"+ | "active_edit"+ | "dead_code"+ | "unchecked"+ | "kind_unaudited";++export interface RecipeStep {+ n: number;+ action: RecipeAction;+ file: string | null;+ span: { start: number; end: number } | null;+ /** The instruction, in one or two sentences. */+ text: string;+ /** Extract Method: the helper to write and its copyable header. */+ new_symbol?: {+ name: string;+ kind: "method" | "function" | null;+ async: boolean;+ params: string[];+ returns: string[];+ signature_text: string | null;+ notes: string[];+ };+ call_site?: ExtractCallSite;+ symbols?: string[];+ to_file?: string | null;+ /** Extract Helper: the directory the shared helper belongs in. */+ directory?: string | null;+ applicability?: "mechanical" | "judgment";+ /** This step's own checks, where they differ from the plan's. */+ verify?: { commands: string[]; tests: string[]; coverage: string };+}++/**+ * One plan as a spec an agent applies (Repowise never applies it): what must+ * hold before, the edits in order, what must hold after, and what not to do.+ * Built by ``refactoring.recipe.build_recipe``.+ */+export interface RefactoringRecipe {+ id: string | null;+ kind: RefactoringType | string;+ /** The steps are one way to do it, for a person to judge (Break Cycle). */+ advisory: boolean;+ summary: string;+ target: { file: string; symbol: string | null; span: { start: number; end: number } | null };+ preconditions: Array<{ kind: RecipePreconditionKind; text: string; ref?: string }>;+ steps: RecipeStep[];+ postconditions: Array<+ | {+ kind: "verify";+ text: string;+ tests?: string[];+ tests_total?: number;+ commands?: string[];+ basis?: string | null;+ reasons?: Record<string, string>;+ }+ | { kind: "metric"; text: string }+ >;+ /** `constraint` reads after "Do not"; `reason` says why, when it is not obvious. */+ does_not: Array<{ constraint: string; reason: string | null }>;}export interface RefactoringTypeCount {diff --git a/packages/ui/__tests__/health/performance-view.test.tsx b/packages/ui/__tests__/health/performance-view.test.tsxindex d2c880d9e..c10ef0da6 100644--- a/packages/ui/__tests__/health/performance-view.test.tsx+++ b/packages/ui/__tests__/health/performance-view.test.tsx@@ -404,6 +404,35 @@ describe("PerformanceView drawer", () => {expect(await screen.findByText("Structured plan handoff")).toBeTruthy();});+ it("shows the plan prompt the server renders when the host serves one", async () => {+ const exact: RefactoringPlan = {+ id: "plan-1",+ refactoring_type: "performance_fix",+ file_path: "src/shared.py",+ target_symbol: "src/shared.py::load",+ line_start: 8,+ line_end: 12,+ plan: { opportunity_id: "perf2_planready", strategy: "batch_or_prefetch_io" },+ evidence: {},+ impact_delta: 0,+ effort_bucket: "M",+ blast_radius: {},+ confidence: "medium",+ source_biomarker: "io_in_loop",+ rank_score: 12.5,+ };+ const served = vi.fn(async (planId: string, flavor: string) => `served ${planId} ${flavor}`);+ render(+ <PerformanceView+ adapter={adapter({ getRefactoringPlan: async () => exact, getRefactoringPlanPrompt: served })}+ />,+ );+ await openFirstRow();+ fireEvent.click(await screen.findByRole("button", { name: "Copy the plan for an agent" }));+ expect(await screen.findByText(/served plan-1 generic/)).toBeTruthy();+ expect(served).toHaveBeenCalledWith("plan-1", "generic");+ });+it("falls back to the evidence handoff when no plan was verified", async () => {render(<PerformanceView adapter={adapter()} />);await openFirstRow();diff --git a/packages/ui/src/health/ai-prompts/refactoring-prompts.ts b/packages/ui/src/health/ai-prompts/refactoring-prompts.tsindex 057644202..f1417a38a 100644--- a/packages/ui/src/health/ai-prompts/refactoring-prompts.ts+++ b/packages/ui/src/health/ai-prompts/refactoring-prompts.ts@@ -151,6 +151,11 @@ function planFacts(plan: RefactoringPlan, blurb: string): string {/*** Hand an agent ONE precomputed refactoring plan to execute and verify, with* its per-type steps, blast radius and completion contract.+ *+ * Fallback only: the server renders this prompt in core+ * (`/refactoring/{id}/prompt`). Kept for a host talking to a server older than+ * that route (the VS Code extension supports servers from 0.47); remove with+ * the opportunity builder below once no supported server lacks it.*/export function buildRefactoringPlanPrompt({plan,@@ -359,7 +364,8 @@ function opportunityFacts(opportunity: RefactoringOpportunityDetailResolved): st/*** Hand an agent ONE composed refactoring opportunity: its ordered steps with the* mechanical/judgment split, evidence, validation and stable id. The multi-step- * sibling of `buildRefactoringPlanPrompt`.+ * sibling of `buildRefactoringPlanPrompt`, and a fallback the same way: the+ * server renders it at `/refactoring/opportunities/{id}/prompt`.*/export function buildRefactoringOpportunityPrompt({opportunity,diff --git a/packages/ui/src/health/code-health-adapter.ts b/packages/ui/src/health/code-health-adapter.tsindex 3f35e20c3..a67933234 100644--- a/packages/ui/src/health/code-health-adapter.ts+++ b/packages/ui/src/health/code-health-adapter.ts@@ -17,6 +17,7 @@ import type {TestsReachingFile,} from "@repowise-dev/types/health";import type { Paginated } from "@repowise-dev/types";+import type { AiPromptFlavor } from "./ai-prompts/shared";import type { CodeHealthOverlay } from "./map/types";import type { RelatedWorkHref } from "./related-work";import type {@@ -84,6 +85,8 @@ export interface CodeHealthAdapter {): Promise<Paginated<HealthFinding>>;/** Fetch one exact canonical plan for the performance drawer. */getRefactoringPlan?(planId: string): Promise<RefactoringPlan>;+ /** One plan's agent prompt as core renders it (`/refactoring/{id}/prompt`). */+ getRefactoringPlanPrompt?(planId: string, flavor: AiPromptFlavor): Promise<string>;/*** @deprecated Unused. The repo's Files page owns the file inventory; the* health views are triage surfaces and list only what carries findings.diff --git a/packages/ui/src/health/performance-view.tsx b/packages/ui/src/health/performance-view.tsxindex 90b238f41..a23769dd6 100644--- a/packages/ui/src/health/performance-view.tsx+++ b/packages/ui/src/health/performance-view.tsx@@ -17,6 +17,7 @@ import { AiPromptModal } from "./ai-prompt-modal";import {buildPerformanceOpportunityPrompt,buildRefactoringPlanPrompt,+ type AiPromptFlavor,} from "./ai-prompt-builder";import type { PerformanceViewAdapter } from "./performance/adapter";import { capabilitiesOf } from "./performance/capabilities";@@ -113,6 +114,16 @@ export function PerformanceView({plan: RefactoringPlan | null;} | null>(null);+ // Core renders the plan prompt; held stable so the modal fetches once per flavor.+ const planId = promptFor?.plan?.id;+ const planPrompt = useMemo(+ () =>+ planId && adapter.getRefactoringPlanPrompt+ ? (flavor: AiPromptFlavor) => adapter.getRefactoringPlanPrompt!(planId, flavor)+ : undefined,+ [planId, adapter],+ );+const apply = (next: PerformanceFilterState) => {setFilters(next);onFiltersChange?.(serializeFilters(next));@@ -345,10 +356,13 @@ export function PerformanceView({onOpenChange={(open) => {if (!open) setPromptFor(null);}}+ promptSource={planPrompt}getPrompt={- promptFor?.plan+ // A host without the prompt route (an older server) builds the plan+ // prompt here instead; remove with `buildRefactoringPlanPrompt`.+ promptFor?.plan && !planPrompt? (flavor) => buildRefactoringPlanPrompt({ plan: promptFor.plan!, flavor })- : promptFor+ : promptFor && !promptFor.plan? (flavor) =>buildPerformanceOpportunityPrompt({opportunity: promptFor.opportunity,diff --git a/packages/ui/src/health/performance/adapter.ts b/packages/ui/src/health/performance/adapter.tsindex 0fd842fde..e66e20451 100644--- a/packages/ui/src/health/performance/adapter.ts+++ b/packages/ui/src/health/performance/adapter.ts@@ -14,6 +14,7 @@ export type PerformanceViewAdapter = Pick<| "getPerformanceOpportunity"| "getPerformanceOpportunityFindings"| "getRefactoringPlan"+ | "getRefactoringPlanPrompt"| "refactoringPlanHref"| "getRelatedWork"| "relatedWorkHref"diff --git a/packages/vscode/src/core/planPrompt.ts b/packages/vscode/src/core/planPrompt.tsnew file mode 100644index 000000000..18735080a--- /dev/null+++ b/packages/vscode/src/core/planPrompt.ts@@ -0,0 +1,64 @@+import {+ getRefactoringOpportunityPrompt,+ getRefactoringPlanPrompt,+} from "@repowise-dev/api-client/refactoring";+import {+ buildRefactoringOpportunityPrompt,+ buildRefactoringPlanPrompt,+ type AiPromptFlavor,+} from "@repowise-dev/ui/health/ai-prompt-builder";+import type {+ RefactoringOpportunityDetailResolved,+ RefactoringPlan,+} from "@repowise-dev/types/refactoring";+import type { RepowiseContext } from "./context";++/*+ * Core renders refactoring prompts on the server, so every surface hands an+ * agent the same text. The extension supports servers from MIN_SERVER_VERSION,+ * which predate the prompt routes: on a failed fetch it builds the prompt+ * locally instead. Drop the fallback (and the builders) once the floor passes+ * the release that serves the routes.+ */++async function served(+ ctx: RepowiseContext,+ load: (repoId: string) => Promise<{ text: string }>,+): Promise<string | null> {+ const repoId = ctx.repoId;+ if (!repoId) return null;+ try {+ return (await load(repoId)).text;+ } catch (err) {+ ctx.log.debug(`Server prompt unavailable, building it locally: ${String(err)}`);+ return null;+ }+}++function repoName(ctx: RepowiseContext): { repoName?: string } {+ return ctx.repo?.name ? { repoName: ctx.repo.name } : {};+}++/** One plan's agent prompt: the server's, else built here for an older server. */+export async function planPrompt(+ ctx: RepowiseContext,+ plan: RefactoringPlan,+ flavor: AiPromptFlavor,+): Promise<string> {+ const text = await served(ctx, (id) => getRefactoringPlanPrompt(id, plan.id, { flavor }));+ return text ?? buildRefactoringPlanPrompt({ plan, flavor, ...repoName(ctx) });+}++/** One opportunity's agent prompt; *detail* is read only for the fallback. */+export async function opportunityPrompt(+ ctx: RepowiseContext,+ opportunityId: string,+ flavor: AiPromptFlavor,+ detail: () => Promise<RefactoringOpportunityDetailResolved>,+): Promise<string> {+ const text = await served(ctx, (id) =>+ getRefactoringOpportunityPrompt(id, opportunityId, { flavor }),+ );+ if (text !== null) return text;+ return buildRefactoringOpportunityPrompt({ opportunity: await detail(), flavor, ...repoName(ctx) });+}diff --git a/packages/vscode/src/core/webviewApi.ts b/packages/vscode/src/core/webviewApi.tsindex f0ff8bcd5..7fed59c01 100644--- a/packages/vscode/src/core/webviewApi.ts+++ b/packages/vscode/src/core/webviewApi.ts@@ -30,10 +30,6 @@ import {import { listDecisions } from "@repowise-dev/api-client/decisions";import { getPageById, listAllPages } from "@repowise-dev/api-client/pages";import { getPatchCoverage, getRiskRange } from "@repowise-dev/api-client/risk";-import {- buildRefactoringOpportunityPrompt,- buildRefactoringPlanPrompt,-} from "@repowise-dev/ui/health/ai-prompt-builder";import { CONFIG_SECTION } from "../constants";import {SETTING_KEYS,@@ -47,6 +43,7 @@ import {import type { RepowiseContext } from "./context";import { analyzeChange } from "./changeAnalysis";import { commitsMatch, getCurrentBranchName, resolveLiveHead } from "./gitApi";+import { opportunityPrompt, planPrompt } from "./planPrompt";/** Thrown by the dispatcher when a request arrives while disconnected. */class NotReadyError extends Error {@@ -309,28 +306,23 @@ export function createHostApi(ctx: RepowiseContext, epoch: () => number): HostApcached(`refactor:opp:${opportunityId}`, (id) =>getRefactoringOpportunity(id, opportunityId, { stepLimit: 50, evidenceLimit: 20 }),),- refactoringOpportunityPrompt: async (opportunityId, flavor) => {- const detail = await cached(`refactor:opp:${opportunityId}`, (id) =>- getRefactoringOpportunity(id, opportunityId, { stepLimit: 50, evidenceLimit: 20 }),- );- if (!detail.found) {- throw new Error(`No refactoring opportunity resolves for ${opportunityId}.`);- }- const repoName = ctx.repo?.name;- return buildRefactoringOpportunityPrompt({- opportunity: detail,- flavor,- ...(repoName ? { repoName } : {}),- });- },+ refactoringOpportunityPrompt: (opportunityId, flavor) =>+ opportunityPrompt(ctx, opportunityId, flavor, async () => {+ const detail = await cached(`refactor:opp:${opportunityId}`, (id) =>+ getRefactoringOpportunity(id, opportunityId, { stepLimit: 50, evidenceLimit: 20 }),+ );+ if (!detail.found) {+ throw new Error(`No refactoring opportunity resolves for ${opportunityId}.`);+ }+ return detail;+ }),refactoringPlan: (suggestionId) =>cached(`refactor:plan:${suggestionId}`, (id) => getRefactoringPlan(id, suggestionId)),refactoringPrompt: async (suggestionId, flavor) => {const plan = await cached(`refactor:plan:${suggestionId}`, (id) =>getRefactoringPlan(id, suggestionId),);- const repoName = ctx.repo?.name;- return buildRefactoringPlanPrompt({ plan, flavor, ...(repoName ? { repoName } : {}) });+ return planPrompt(ctx, plan, flavor);},// Decisionsdiff --git a/packages/vscode/src/features/agentHandoff.ts b/packages/vscode/src/features/agentHandoff.tsindex 435dbf0bc..432b9fcd8 100644--- a/packages/vscode/src/features/agentHandoff.ts+++ b/packages/vscode/src/features/agentHandoff.ts@@ -1,12 +1,13 @@import { existsSync } from "node:fs";import * as path from "node:path";import * as vscode from "vscode";-import { buildRefactoringPlanPrompt, type AiPromptFlavor } from "@repowise-dev/ui/health/ai-prompt-builder";+import type { AiPromptFlavor } from "@repowise-dev/ui/health/ai-prompt-builder";import { typeMeta } from "@repowise-dev/ui/refactoring/meta";import type { RefactoringPlan } from "@repowise-dev/types/refactoring";import { CONFIG_SECTION, InternalCommands } from "../constants";import type { RepowiseContext } from "../core/context";import { repoRelativePath } from "../core/fileSignals";+import { planPrompt } from "../core/planPrompt";import { getPlansForFile } from "../core/plans";/** The Refactor sub-kinds this provider can emit, declared up front so VS Code@@ -114,11 +115,7 @@ function planActions(plan: RefactoringPlan): vscode.CodeAction[] {*/async function handPlanToCopilot(ctx: RepowiseContext, plan: RefactoringPlan): Promise<void> {if (!plan) return;- const prompt = buildRefactoringPlanPrompt({- plan,- flavor: "generic",- ...(ctx.repo?.name ? { repoName: ctx.repo.name } : {}),- });+ const prompt = await planPrompt(ctx, plan, "generic");// The chat-open command exists even without a chat provider configured; it// would open the setup view and silently drop the query. Only hand off when// Copilot Chat is actually installed, otherwise the clipboard is the payload.@@ -153,11 +150,7 @@ async function handPlanToClaudeCode(ctx: RepowiseContext, plan: RefactoringPlan)(existsSync(path.join(root, ".mcp.json")) || existsSync(path.join(root, ".vscode", "mcp.json")));const flavor: AiPromptFlavor = hasMcp ? "claude-code-mcp" : "claude-code";- const prompt = buildRefactoringPlanPrompt({- plan,- flavor,- ...(ctx.repo?.name ? { repoName: ctx.repo.name } : {}),- });+ const prompt = await planPrompt(ctx, plan, flavor);await vscode.env.clipboard.writeText(prompt);if (vscode.extensions.getExtension("anthropic.claude-code")) {diff --git a/packages/vscode/src/features/refactoringLens.ts b/packages/vscode/src/features/refactoringLens.tsindex 673ed76bc..deabdd668 100644--- a/packages/vscode/src/features/refactoringLens.ts+++ b/packages/vscode/src/features/refactoringLens.ts@@ -1,13 +1,11 @@import * as vscode from "vscode";-import {- buildRefactoringPlanPrompt,- type AiPromptFlavor,-} from "@repowise-dev/ui/health/ai-prompt-builder";+import type { AiPromptFlavor } from "@repowise-dev/ui/health/ai-prompt-builder";import { typeMeta } from "@repowise-dev/ui/refactoring/meta";import type { RefactoringPlan } from "@repowise-dev/types/refactoring";import { CONFIG_SECTION, InternalCommands } from "../constants";import type { RepowiseContext } from "../core/context";import { repoRelativePath } from "../core/fileSignals";+import { planPrompt } from "../core/planPrompt";import { getPlansForFile } from "../core/plans";import { openViewPanel } from "../core/webviews";@@ -63,7 +61,7 @@ export function registerRefactoringLens(ctx: RepowiseContext): vscode.DisposableopenRefactoringPlan(ctx, plan),),vscode.commands.registerCommand(InternalCommands.copyRefactoringPrompt, (plan: RefactoringPlan) =>- copyRefactoringPrompt(plan),+ copyRefactoringPrompt(ctx, plan),),stateSub,configSub,@@ -133,7 +131,7 @@ function openRefactoringPlan(ctx: RepowiseContext, plan: RefactoringPlan): void}/** Pick a prompt flavor and copy the shared agent prompt for this plan. */-async function copyRefactoringPrompt(plan: RefactoringPlan): Promise<void> {+async function copyRefactoringPrompt(ctx: RepowiseContext, plan: RefactoringPlan): Promise<void> {if (!plan) return;const picked = await vscode.window.showQuickPick(FLAVOR_ITEMS.map((item) => item.label),@@ -142,7 +140,7 @@ async function copyRefactoringPrompt(plan: RefactoringPlan): Promise<void> {if (!picked) return;const flavor = FLAVOR_ITEMS.find((item) => item.label === picked)?.flavor ?? "generic";- const prompt = buildRefactoringPlanPrompt({ plan, flavor });+ const prompt = await planPrompt(ctx, plan, flavor);await vscode.env.clipboard.writeText(prompt);void vscode.window.showInformationMessage(`Copied refactoring prompt (${prompt.length} characters) to the clipboard.`,diff --git a/packages/web/src/app/repos/[id]/refactoring/page.tsx b/packages/web/src/app/repos/[id]/refactoring/page.tsxindex 51589d684..7ac742001 100644--- a/packages/web/src/app/repos/[id]/refactoring/page.tsx+++ b/packages/web/src/app/repos/[id]/refactoring/page.tsx@@ -42,23 +42,19 @@ import type {OpportunityStatus,RefactoringOpportunity,RefactoringOpportunityDetail,- RefactoringOpportunityDetailResolved,RefactoringOpportunityPage,RefactoringOrder,RefactoringPlan,RefactoringScope,} from "@repowise-dev/types/refactoring";-import {- useRelatedWork,- AiPromptModal,- buildRefactoringOpportunityPrompt,- buildRefactoringPlanPrompt,-} from "@repowise-dev/ui/health";+import { useRelatedWork, AiPromptModal, type PromptSource } from "@repowise-dev/ui/health";import {generateRefactoringCode,getRefactoringOpportunities,getRefactoringOpportunity,+ getRefactoringOpportunityPrompt,getRefactoringPlan,+ getRefactoringPlanPrompt,getRefactoringSettings,updateRefactoringSettings,updateRefactoringOpportunityStatus,@@ -182,24 +178,23 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: stri{ revalidateOnFocus: false, shouldRetryOnError: false },);- const [promptFor, setPromptFor] = useState<- | { kind: "opportunity"; value: RefactoringOpportunityDetailResolved }- | { kind: "plan"; value: RefactoringPlan }- | null- >(null);-- // A row hands over its whole opportunity, which means fetching the detail the- // list deliberately does not carry. One call, on demand, rather than steps on- // every row of every page.- const onRowAiPrompt = useCallback(- async (opportunity: RefactoringOpportunity) => {- const detail = await getRefactoringOpportunity(repoId, opportunity.opportunity_id, {- stepLimit: 50,- evidenceLimit: 20,- });- if (detail.found) setPromptFor({ kind: "opportunity", value: detail });- },- [repoId],+ // Core renders both prompts from the stored plans, so a row hands over its+ // opportunity by id: the prompt route reads the steps the list does not carry.+ const [promptFor, setPromptFor] = useState<{+ kind: "opportunity" | "plan";+ id: string;+ filePath: string;+ } | null>(null);+ const promptSource = useMemo<PromptSource | undefined>(() => {+ if (!promptFor) return undefined;+ const load =+ promptFor.kind === "opportunity" ? getRefactoringOpportunityPrompt : getRefactoringPlanPrompt;+ return async (flavor) => (await load(repoId, promptFor.id, { flavor })).text;+ }, [repoId, promptFor]);+ const onOpportunityPrompt = useCallback(+ (o: Pick<RefactoringOpportunity, "opportunity_id" | "file_path">) =>+ setPromptFor({ kind: "opportunity", id: o.opportunity_id, filePath: o.file_path }),+ [],);const onStatusChange = useCallback(@@ -355,7 +350,7 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: striif (change.offset !== undefined) setOffset(change.offset);}}onOpen={(o) => void setOpenId(o.opportunity_id)}- onAiPrompt={(o) => void onRowAiPrompt(o)}+ onAiPrompt={onOpportunityPrompt}onStatusChange={onStatusChange}onSeeStructural={() => {setOffset(0);@@ -387,7 +382,7 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: strionOpenChange={(open) => {if (!open) void setOpenId(null);}}- onAiPrompt={(detail) => setPromptFor({ kind: "opportunity", value: detail })}+ onAiPrompt={onOpportunityPrompt}onStatusChange={onStatusChange}onOpenStep={(planId) => void setOpenPlanId(planId)}fileHref={fileHref}@@ -404,7 +399,7 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: strionOpenChange={(open) => {if (!open) void setOpenPlanId(null);}}- onAiPrompt={(plan) => setPromptFor({ kind: "plan", value: plan })}+ onAiPrompt={(plan) => setPromptFor({ kind: "plan", id: plan.id, filePath: plan.file_path })}onGenerateCode={onGenerateCode}settingsHref={`${prefix}/settings`}modelSetting={modelSetting}@@ -416,18 +411,9 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: strionOpenChange={(open) => {if (!open) setPromptFor(null);}}- getPrompt={- promptFor- ? (flavor) =>- promptFor.kind === "opportunity"- ? buildRefactoringOpportunityPrompt({- opportunity: promptFor.value,- flavor,- })- : buildRefactoringPlanPrompt({ plan: promptFor.value, flavor })- : null- }- filePath={promptFor?.value.file_path ?? null}+ getPrompt={null}+ promptSource={promptSource}+ filePath={promptFor?.filePath ?? null}title={t("promptTitle")}description={t("promptDescription")}/>diff --git a/packages/web/src/components/code-health/performance-tab.tsx b/packages/web/src/components/code-health/performance-tab.tsxindex 309e20162..3e7d68646 100644--- a/packages/web/src/components/code-health/performance-tab.tsx+++ b/packages/web/src/components/code-health/performance-tab.tsx@@ -10,7 +10,7 @@ import {getPerformanceOpportunityFindings,listHealthFindings,} from "@/lib/api/code-health";-import { getRefactoringPlan } from "@/lib/api/refactoring";+import { getRefactoringPlan, getRefactoringPlanPrompt } from "@/lib/api/refactoring";import { getFileContent } from "@/lib/api/files";import { getRelatedWork, relatedWorkHref } from "@/lib/api/related-work";@@ -35,6 +35,8 @@ export function PerformanceTab({ repoId }: { repoId: string }) {getPerformanceOpportunityFindings: (opportunityId, options) =>getPerformanceOpportunityFindings(repoId, opportunityId, options),getRefactoringPlan: (planId) => getRefactoringPlan(repoId, planId),+ getRefactoringPlanPrompt: async (planId, flavor) =>+ (await getRefactoringPlanPrompt(repoId, planId, { flavor })).text,refactoringPlanHref: (planId) =>`/repos/${repoId}/refactoring?type=performance_fix&plan=${encodeURIComponent(planId)}`,// Onto the one galaxy, on the performance lens, with the cause's filesdiff --git a/tests/fixtures/agent_prompts/golden.json b/tests/fixtures/agent_prompts/golden.jsonindex 5454d53aa..acf4e0e98 100644--- a/tests/fixtures/agent_prompts/golden.json+++ b/tests/fixtures/agent_prompts/golden.json@@ -49,5 +49,52 @@"no_tests_mixed_args": "No guarding tests found. Write a test that pins the current behaviour before you change anything.","tests_and_steps_over_cap": "- `tests/unit/test_a.py`: reaches the changed code through the call-graph\n- `tests/unit/test_b.py`\n- …and 1,205 more\n\nRun: `pytest tests/unit/test_a.py tests/unit/test_b.py`","exact_no_command_empty_args": "- `packages/ui/__tests__/graph-flow.test.tsx`: imports the file"+ },+ "refactoring_plan": {+ "extract_method_typed": {+ "generic": "You are a senior engineer in this repository. Repowise, a code-intelligence index, planned the refactoring below from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Read the code each step names and confirm it before you change it.\n## Extract Method (`acme/api`)\nExtract lines 61-78 of `Loader.load` into `_read_config`.\n- Plan: `refac4_aaaaaaaaaaaaaaaaaaaa`\n- Target: `src/loader.py:40-120` (`Loader.load`)\n## Before you edit\n- The guarding tests pass before the edit.\n- Decision \"Loaders stay sync-free\" governs this file; check it allows this change first.\n- Changed in 3 commits by ana in the 14 days before the last index; check nobody is mid-change.\n- Decision `dec_2` also governs this file; read it.\n## Steps, in order\n1. Move lines 61-78 of `Loader.load` into a new helper `_read_config` (a starting name; rename it if it collides) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - New helper: `async def _read_config(self, path: Path, strict) -> <type>:`\n - Replace lines 61-78 with: `config = await self._read_config(path, strict)`\n - Parameters (in): path, strict\n - Returns (out): config\n - Note: The return type is not named in the code.\n - Note: Fill each `<name>` / `<type>` placeholder from the code.\n## Verify\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py` (covers lines 61-78)\n- `tests/test_cli.py`\n2 of 3 guarding tests shown.\n\nRun:\n\n```\npytest tests/test_cli.py tests/test_loader.py\n```\n\n- Expect: `Loader.load` loses about 6 branches of cyclomatic complexity.\n- Expect: File health recovers about 1.25.\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not touch anything outside lines 61-78 and the call that replaces them.**\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step applied.\n2. What you named or introduced, and why.\n3. The Verify run, before and after, with its result.\n4. Any call sites or files you also had to change.",+ "claude-code": "You are Claude Code in this repository. Repowise, a code-intelligence index, planned the refactoring below from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Read each span with Read and Grep before editing, and track the steps with TodoWrite.\n## Extract Method (`acme/api`)\nExtract lines 61-78 of `Loader.load` into `_read_config`.\n- Plan: `refac4_aaaaaaaaaaaaaaaaaaaa`\n- Target: `src/loader.py:40-120` (`Loader.load`)\n## Before you edit\n- The guarding tests pass before the edit.\n- Decision \"Loaders stay sync-free\" governs this file; check it allows this change first.\n- Changed in 3 commits by ana in the 14 days before the last index; check nobody is mid-change.\n- Decision `dec_2` also governs this file; read it.\n## Steps, in order\n1. Move lines 61-78 of `Loader.load` into a new helper `_read_config` (a starting name; rename it if it collides) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - New helper: `async def _read_config(self, path: Path, strict) -> <type>:`\n - Replace lines 61-78 with: `config = await self._read_config(path, strict)`\n - Parameters (in): path, strict\n - Returns (out): config\n - Note: The return type is not named in the code.\n - Note: Fill each `<name>` / `<type>` placeholder from the code.\n## Verify\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py` (covers lines 61-78)\n- `tests/test_cli.py`\n2 of 3 guarding tests shown.\n\nRun:\n\n```\npytest tests/test_cli.py tests/test_loader.py\n```\n\n- Expect: `Loader.load` loses about 6 branches of cyclomatic complexity.\n- Expect: File health recovers about 1.25.\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not touch anything outside lines 61-78 and the call that replaces them.**\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step applied.\n2. What you named or introduced, and why.\n3. The Verify run, before and after, with its result.\n4. Any call sites or files you also had to change.",+ "claude-code-mcp": "You are Claude Code in this repository, which Repowise indexes and serves over MCP. Repowise planned the refactoring below from its static analysis. It does not edit code: the steps are a spec for you to apply. Use the MCP lookup under \"Look closer\" and `get_symbol` on each span before reading files by hand.\n## Extract Method (`acme/api`)\nExtract lines 61-78 of `Loader.load` into `_read_config`.\n- Plan: `refac4_aaaaaaaaaaaaaaaaaaaa`\n- Target: `src/loader.py:40-120` (`Loader.load`)\n## Before you edit\n- The guarding tests pass before the edit.\n- Decision \"Loaders stay sync-free\" governs this file; check it allows this change first.\n- Changed in 3 commits by ana in the 14 days before the last index; check nobody is mid-change.\n- Decision `dec_2` also governs this file; read it.\n## Steps, in order\n1. Move lines 61-78 of `Loader.load` into a new helper `_read_config` (a starting name; rename it if it collides) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - New helper: `async def _read_config(self, path: Path, strict) -> <type>:`\n - Replace lines 61-78 with: `config = await self._read_config(path, strict)`\n - Parameters (in): path, strict\n - Returns (out): config\n - Note: The return type is not named in the code.\n - Note: Fill each `<name>` / `<type>` placeholder from the code.\n## Verify\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py` (covers lines 61-78)\n- `tests/test_cli.py`\n2 of 3 guarding tests shown.\n\nRun:\n\n```\npytest tests/test_cli.py tests/test_loader.py\n```\n\n- Expect: `Loader.load` loses about 6 branches of cyclomatic complexity.\n- Expect: File health recovers about 1.25.\n## Look closer (Repowise MCP)\n`get_health(plan_id=\"refac4_aaaaaaaaaaaaaaaaaaaa\")`\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not touch anything outside lines 61-78 and the call that replaces them.**\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step applied.\n2. What you named or introduced, and why.\n3. The Verify run, before and after, with its result.\n4. Any call sites or files you also had to change.",+ "cursor": "Work in this repository. Repowise, a code-intelligence index, planned the refactoring below from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Open each span with @file and confirm it before editing.\n## Extract Method (`acme/api`)\nExtract lines 61-78 of `Loader.load` into `_read_config`.\n- Plan: `refac4_aaaaaaaaaaaaaaaaaaaa`\n- Target: `src/loader.py:40-120` (`Loader.load`)\n## Before you edit\n- The guarding tests pass before the edit.\n- Decision \"Loaders stay sync-free\" governs this file; check it allows this change first.\n- Changed in 3 commits by ana in the 14 days before the last index; check nobody is mid-change.\n- Decision `dec_2` also governs this file; read it.\n## Steps, in order\n1. Move lines 61-78 of `Loader.load` into a new helper `_read_config` (a starting name; rename it if it collides) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - New helper: `async def _read_config(self, path: Path, strict) -> <type>:`\n - Replace lines 61-78 with: `config = await self._read_config(path, strict)`\n - Parameters (in): path, strict\n - Returns (out): config\n - Note: The return type is not named in the code.\n - Note: Fill each `<name>` / `<type>` placeholder from the code.\n## Verify\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py` (covers lines 61-78)\n- `tests/test_cli.py`\n2 of 3 guarding tests shown.\n\nRun:\n\n```\npytest tests/test_cli.py tests/test_loader.py\n```\n\n- Expect: `Loader.load` loses about 6 branches of cyclomatic complexity.\n- Expect: File health recovers about 1.25.\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not touch anything outside lines 61-78 and the call that replaces them.**\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step applied.\n2. What you named or introduced, and why.\n3. The Verify run, before and after, with its result.\n4. Any call sites or files you also had to change."+ },+ "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.",+ "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## 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.",+ "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## 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## Look closer (Repowise MCP)\n`get_health(plan_id=\"refac4_bbbbbbbbbbbbbbbbbbbb\")`\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.",+ "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## 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."+ },+ "split_file_older_row": {+ "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## 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## 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.**\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## 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## 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.**\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## 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## Look closer (Repowise MCP)\n`get_health(plan_id=\"refac4_cccccccccccccccccccc\")`\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.**\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## 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## 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.**\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."+ },+ "break_cycle_advisory": {+ "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## 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## 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.**\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## 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## 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.**\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## 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## Look closer (Repowise MCP)\n`get_health(plan_id=\"refac4_gggggggggggggggggggg\")`\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.**\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## 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## 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.**\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."+ },+ "move_method_unaudited": {+ "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## Move Method\nMove `total_tax` from `Order` to `TaxTable` in `src/tax.py`, then update every call site; keep a delegating wrapper only for callers you cannot reach.\n- Plan: `refac4_hhhhhhhhhhhhhhhhhhhh`\n- Target: `src/order.py:20-34` (`Order.total_tax`)\n## Before you edit\n- The guarding tests pass before the edit.\n- This plan type is not yet audited for accuracy; confirm it fits before applying.\n- `Order.total_tax` has 3 callers; each has to reach it through `TaxTable` after the move.\n## Steps, in order\n1. Move `total_tax` from `Order` to `TaxTable` in `src/tax.py`, then update every call site; keep a delegating wrapper only for callers you cannot reach. (`src/order.py:20-34`)\n## Verify\nThe 4 guarding tests (not listed here) pass after the edit.\n\n- Expect: File health recovers about 0.40.\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not leave a call site pointing at the old class.**\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## Move Method\nMove `total_tax` from `Order` to `TaxTable` in `src/tax.py`, then update every call site; keep a delegating wrapper only for callers you cannot reach.\n- Plan: `refac4_hhhhhhhhhhhhhhhhhhhh`\n- Target: `src/order.py:20-34` (`Order.total_tax`)\n## Before you edit\n- The guarding tests pass before the edit.\n- This plan type is not yet audited for accuracy; confirm it fits before applying.\n- `Order.total_tax` has 3 callers; each has to reach it through `TaxTable` after the move.\n## Steps, in order\n1. Move `total_tax` from `Order` to `TaxTable` in `src/tax.py`, then update every call site; keep a delegating wrapper only for callers you cannot reach. (`src/order.py:20-34`)\n## Verify\nThe 4 guarding tests (not listed here) pass after the edit.\n\n- Expect: File health recovers about 0.40.\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not leave a call site pointing at the old class.**\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## Move Method\nMove `total_tax` from `Order` to `TaxTable` in `src/tax.py`, then update every call site; keep a delegating wrapper only for callers you cannot reach.\n- Plan: `refac4_hhhhhhhhhhhhhhhhhhhh`\n- Target: `src/order.py:20-34` (`Order.total_tax`)\n## Before you edit\n- The guarding tests pass before the edit.\n- This plan type is not yet audited for accuracy; confirm it fits before applying.\n- `Order.total_tax` has 3 callers; each has to reach it through `TaxTable` after the move.\n## Steps, in order\n1. Move `total_tax` from `Order` to `TaxTable` in `src/tax.py`, then update every call site; keep a delegating wrapper only for callers you cannot reach. (`src/order.py:20-34`)\n## Verify\nThe 4 guarding tests (not listed here) pass after the edit.\n\n- Expect: File health recovers about 0.40.\n## Look closer (Repowise MCP)\n`get_health(plan_id=\"refac4_hhhhhhhhhhhhhhhhhhhh\")`\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not leave a call site pointing at the old class.**\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## Move Method\nMove `total_tax` from `Order` to `TaxTable` in `src/tax.py`, then update every call site; keep a delegating wrapper only for callers you cannot reach.\n- Plan: `refac4_hhhhhhhhhhhhhhhhhhhh`\n- Target: `src/order.py:20-34` (`Order.total_tax`)\n## Before you edit\n- The guarding tests pass before the edit.\n- This plan type is not yet audited for accuracy; confirm it fits before applying.\n- `Order.total_tax` has 3 callers; each has to reach it through `TaxTable` after the move.\n## Steps, in order\n1. Move `total_tax` from `Order` to `TaxTable` in `src/tax.py`, then update every call site; keep a delegating wrapper only for callers you cannot reach. (`src/order.py:20-34`)\n## Verify\nThe 4 guarding tests (not listed here) pass after the edit.\n\n- Expect: File health recovers about 0.40.\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not leave a call site pointing at the old class.**\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."+ }+ },+ "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.**",+ "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.**",+ "move_method_unaudited": "## Move Method\nMove `total_tax` from `Order` to `TaxTable` in `src/tax.py`, then update every call site; keep a delegating wrapper only for callers you cannot reach.\n- Plan: `refac4_hhhhhhhhhhhhhhhhhhhh`\n- Target: `src/order.py:20-34` (`Order.total_tax`)\n## Before you edit\n- The guarding tests pass before the edit.\n- This plan type is not yet audited for accuracy; confirm it fits before applying.\n- `Order.total_tax` has 3 callers; each has to reach it through `TaxTable` after the move.\n## Steps, in order\n1. Move `total_tax` from `Order` to `TaxTable` in `src/tax.py`, then update every call site; keep a delegating wrapper only for callers you cannot reach. (`src/order.py:20-34`)\n## Verify\nThe 4 guarding tests (not listed here) pass after the edit.\n\n- Expect: File health recovers about 0.40.\n## Blast radius\n- callers: 3\n- co change partners: src/tax.py (5)\n- files: src/order.py, src/tax.py\n## Hard constraints\n- **Do not change behaviour.** What the code returns, raises or writes stays the same.\n- **Do not leave a call site pointing at the old class.**"+ },+ "refactoring_opportunity": {+ "two_steps_one_relocated": {+ "generic": "You are a senior engineer in this repository. Repowise, a code-intelligence index, composed the ordered refactoring steps below for one file from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Read the code each step names and confirm it before you change it.\n## Extract Method in `src/loader.py` (`acme/api`)\n- Opportunity: `refop4_dddddddddddddddddddd`\n- File: `src/loader.py`\n- Leading cause: complex method.\n- 2 steps: 1 mechanical, 1 judgment.\n- Recovers ~2.50 of health score if applied.\n- Effort: M bucket. Detector confidence: high.\n- No dominant problem was recorded for this file, so whether these steps address it is unknown.\n## Steps, in order\nA step carrying `relocated_by` names a symbol an earlier step moves.\n\n1. **Extract Method** at `src/loader.py:40-120` (`Loader.load`)\n - Step id: `refac4_aaaaaaaaaaaaaaaaaaaa`\n - Mechanical: dataflow proved local extraction.\n - Move lines 61-78 of `Loader.load` into a new helper `<name>` (name it for what the lines do) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - Parameters (in): path\n - Returns (out): (nothing)\n\n2. **Move Method** at `src/loader.py:130` (`Loader.parse`)\n - Step id: `refac4_eeeeeeeeeeeeeeeeeeee`\n - Judgment. Not established: call sites resolved.\n - **Locate it again first.** Step `refac4_aaaaaaaaaaaaaaaaaaaa` moves this symbol, so the path and lines above are where it was, not where it will be when you get here.\n - This step's plan was not in this payload; ask for it by id: `refac4_eeeeeeeeeeeeeeeeeeee`.\n## Evidence behind the diagnosis\nSupporting observations, not extra work.\n- Extract Helper `loader.py:10-20`: duplicated lines: 11; occurrence count: 2\n1 of 3 shown.\n## Verify\n### For `Loader.load`\n\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py`\n\nRun:\n\n```\npytest tests/test_loader.py\n```\n\n### For `Loader.parse`\n\nNo guarding test was found; the test added before the edit passes after it.\n## Hard constraints\n- **Apply the steps in the order given.** It is dependency-safe; reordering it is not.\n- **Read a judgment step's code before applying it.** Its obligation is unproven.\n- **Keep behaviour.** Run the tests (and type-checker / linter) before and after.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step above applied in order.\n2. Per step: whether you applied it, and for anything you skipped, the reason.\n3. The Verify run, before and after, with its result.\n4. The opportunity id `refop4_dddddddddddddddddddd`, so the work can be matched back to the record.\n## This opportunity's id\n`refop4_dddddddddddddddddddd`\nQuote it when you report back.",+ "claude-code": "You are Claude Code in this repository. Repowise, a code-intelligence index, composed the ordered refactoring steps below for one file from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Read each span with Read and Grep before editing, and track the steps with TodoWrite.\n## Extract Method in `src/loader.py` (`acme/api`)\n- Opportunity: `refop4_dddddddddddddddddddd`\n- File: `src/loader.py`\n- Leading cause: complex method.\n- 2 steps: 1 mechanical, 1 judgment.\n- Recovers ~2.50 of health score if applied.\n- Effort: M bucket. Detector confidence: high.\n- No dominant problem was recorded for this file, so whether these steps address it is unknown.\n## Steps, in order\nA step carrying `relocated_by` names a symbol an earlier step moves.\n\n1. **Extract Method** at `src/loader.py:40-120` (`Loader.load`)\n - Step id: `refac4_aaaaaaaaaaaaaaaaaaaa`\n - Mechanical: dataflow proved local extraction.\n - Move lines 61-78 of `Loader.load` into a new helper `<name>` (name it for what the lines do) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - Parameters (in): path\n - Returns (out): (nothing)\n\n2. **Move Method** at `src/loader.py:130` (`Loader.parse`)\n - Step id: `refac4_eeeeeeeeeeeeeeeeeeee`\n - Judgment. Not established: call sites resolved.\n - **Locate it again first.** Step `refac4_aaaaaaaaaaaaaaaaaaaa` moves this symbol, so the path and lines above are where it was, not where it will be when you get here.\n - This step's plan was not in this payload; ask for it by id: `refac4_eeeeeeeeeeeeeeeeeeee`.\n## Evidence behind the diagnosis\nSupporting observations, not extra work.\n- Extract Helper `loader.py:10-20`: duplicated lines: 11; occurrence count: 2\n1 of 3 shown.\n## Verify\n### For `Loader.load`\n\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py`\n\nRun:\n\n```\npytest tests/test_loader.py\n```\n\n### For `Loader.parse`\n\nNo guarding test was found; the test added before the edit passes after it.\n## Hard constraints\n- **Apply the steps in the order given.** It is dependency-safe; reordering it is not.\n- **Read a judgment step's code before applying it.** Its obligation is unproven.\n- **Keep behaviour.** Run the tests (and type-checker / linter) before and after.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step above applied in order.\n2. Per step: whether you applied it, and for anything you skipped, the reason.\n3. The Verify run, before and after, with its result.\n4. The opportunity id `refop4_dddddddddddddddddddd`, so the work can be matched back to the record.\n## This opportunity's id\n`refop4_dddddddddddddddddddd`\nQuote it when you report back.",+ "claude-code-mcp": "You are Claude Code in this repository, which Repowise indexes and serves over MCP. Repowise composed the ordered refactoring steps below for one file from its static analysis. It does not edit code: the steps are a spec for you to apply. Pull the record with the call at the end and `get_symbol` each span before reading files by hand.\n## Extract Method in `src/loader.py` (`acme/api`)\n- Opportunity: `refop4_dddddddddddddddddddd`\n- File: `src/loader.py`\n- Leading cause: complex method.\n- 2 steps: 1 mechanical, 1 judgment.\n- Recovers ~2.50 of health score if applied.\n- Effort: M bucket. Detector confidence: high.\n- No dominant problem was recorded for this file, so whether these steps address it is unknown.\n## Steps, in order\nA step carrying `relocated_by` names a symbol an earlier step moves.\n\n1. **Extract Method** at `src/loader.py:40-120` (`Loader.load`)\n - Step id: `refac4_aaaaaaaaaaaaaaaaaaaa`\n - Mechanical: dataflow proved local extraction.\n - Move lines 61-78 of `Loader.load` into a new helper `<name>` (name it for what the lines do) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - Parameters (in): path\n - Returns (out): (nothing)\n\n2. **Move Method** at `src/loader.py:130` (`Loader.parse`)\n - Step id: `refac4_eeeeeeeeeeeeeeeeeeee`\n - Judgment. Not established: call sites resolved.\n - **Locate it again first.** Step `refac4_aaaaaaaaaaaaaaaaaaaa` moves this symbol, so the path and lines above are where it was, not where it will be when you get here.\n - This step's plan was not in this payload; ask for it by id: `refac4_eeeeeeeeeeeeeeeeeeee`.\n## Evidence behind the diagnosis\nSupporting observations, not extra work.\n- Extract Helper `loader.py:10-20`: duplicated lines: 11; occurrence count: 2\n1 of 3 shown.\n## Verify\n### For `Loader.load`\n\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py`\n\nRun:\n\n```\npytest tests/test_loader.py\n```\n\n### For `Loader.parse`\n\nNo guarding test was found; the test added before the edit passes after it.\n## Hard constraints\n- **Apply the steps in the order given.** It is dependency-safe; reordering it is not.\n- **Read a judgment step's code before applying it.** Its obligation is unproven.\n- **Keep behaviour.** Run the tests (and type-checker / linter) before and after.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step above applied in order.\n2. Per step: whether you applied it, and for anything you skipped, the reason.\n3. The Verify run, before and after, with its result.\n4. The opportunity id `refop4_dddddddddddddddddddd`, so the work can be matched back to the record.\n## Pull this record yourself\n`get_health(opportunity_id=\"refop4_dddddddddddddddddddd\")`\nIt returns this opportunity from the index: every ordered step with its plan, the validation profiles and the evidence. Call it before you start; the steps above are a snapshot.",+ "cursor": "Work in this repository. Repowise, a code-intelligence index, composed the ordered refactoring steps below for one file from its static analysis. Repowise does not edit code: the steps are a spec for you to apply. Open each span with @file and confirm it before editing.\n## Extract Method in `src/loader.py` (`acme/api`)\n- Opportunity: `refop4_dddddddddddddddddddd`\n- File: `src/loader.py`\n- Leading cause: complex method.\n- 2 steps: 1 mechanical, 1 judgment.\n- Recovers ~2.50 of health score if applied.\n- Effort: M bucket. Detector confidence: high.\n- No dominant problem was recorded for this file, so whether these steps address it is unknown.\n## Steps, in order\nA step carrying `relocated_by` names a symbol an earlier step moves.\n\n1. **Extract Method** at `src/loader.py:40-120` (`Loader.load`)\n - Step id: `refac4_aaaaaaaaaaaaaaaaaaaa`\n - Mechanical: dataflow proved local extraction.\n - Move lines 61-78 of `Loader.load` into a new helper `<name>` (name it for what the lines do) in the same scope, and replace them with one call to it. (`src/loader.py:61-78`)\n - Parameters (in): path\n - Returns (out): (nothing)\n\n2. **Move Method** at `src/loader.py:130` (`Loader.parse`)\n - Step id: `refac4_eeeeeeeeeeeeeeeeeeee`\n - Judgment. Not established: call sites resolved.\n - **Locate it again first.** Step `refac4_aaaaaaaaaaaaaaaaaaaa` moves this symbol, so the path and lines above are where it was, not where it will be when you get here.\n - This step's plan was not in this payload; ask for it by id: `refac4_eeeeeeeeeeeeeeeeeeee`.\n## Evidence behind the diagnosis\nSupporting observations, not extra work.\n- Extract Helper `loader.py:10-20`: duplicated lines: 11; occurrence count: 2\n1 of 3 shown.\n## Verify\n### For `Loader.load`\n\nRun these before and after the change, the most direct first:\n\n- `tests/test_loader.py`\n\nRun:\n\n```\npytest tests/test_loader.py\n```\n\n### For `Loader.parse`\n\nNo guarding test was found; the test added before the edit passes after it.\n## Hard constraints\n- **Apply the steps in the order given.** It is dependency-safe; reordering it is not.\n- **Read a judgment step's code before applying it.** Its obligation is unproven.\n- **Keep behaviour.** Run the tests (and type-checker / linter) before and after.\n- **Confirm before changing.** The plan comes from stored static analysis; the code may have moved since it ran.\n- **Say when it is wrong.** If the plan does not fit the real code, stop and explain why instead of forcing it.\n## What I expect back\n1. The refactored code, with each step above applied in order.\n2. Per step: whether you applied it, and for anything you skipped, the reason.\n3. The Verify run, before and after, with its result.\n4. The opportunity id `refop4_dddddddddddddddddddd`, so the work can be matched back to the record.\n## This opportunity's id\n`refop4_dddddddddddddddddddd`\nQuote it when you report back."+ }}}diff --git a/tests/fixtures/agent_prompts/refactoring.json b/tests/fixtures/agent_prompts/refactoring.jsonnew file mode 100644index 000000000..8132b426f--- /dev/null+++ b/tests/fixtures/agent_prompts/refactoring.json@@ -0,0 +1,487 @@+{+ "plans": [+ {+ "name": "extract_method_typed",+ "repo_name": "acme/api",+ "detail": {+ "id": "refac4_aaaaaaaaaaaaaaaaaaaa",+ "refactoring_type": "extract_method",+ "file_path": "src/loader.py",+ "target_symbol": "Loader.load",+ "line_start": 40,+ "line_end": 120,+ "plan": {+ "span": {+ "start": 61,+ "end": 78+ },+ "params": [+ "path",+ "strict"+ ],+ "returns": [+ "config"+ ],+ "suggested_name": "_read_config",+ "needs_async": true,+ "async_host": true,+ "new_symbol": {+ "kind": "method",+ "async": true,+ "receiver": "self",+ "uses_receiver": true,+ "params": [+ {+ "name": "path",+ "type": "Path",+ "mode": "in"+ },+ {+ "name": "strict",+ "type": null,+ "mode": "in"+ }+ ],+ "returns": [+ {+ "name": "config",+ "type": "<type>"+ }+ ],+ "signature_text": "async def _read_config(self, path: Path, strict) -> <type>:",+ "notes": [+ "The return type is not named in the code."+ ]+ },+ "call_site": {+ "replace_span": {+ "start": 61,+ "end": 78+ },+ "new_text": "config = await self._read_config(path, strict)"+ }+ },+ "evidence": {+ "slice_nloc": 18,+ "ccn_removed": 6+ },+ "impact_delta": 1.25,+ "effort_bucket": "S",+ "blast_radius": {+ "scope": "local"+ },+ "confidence": "high",+ "source_biomarker": "complex_method",+ "validation": {+ "basis": "measured",+ "via": "coverage",+ "total": 3,+ "tests": [+ "tests/test_loader.py",+ "tests/test_cli.py"+ ],+ "truncated": true,+ "affected_files": [+ "src/loader.py"+ ],+ "affected_symbols": [+ "Loader.load"+ ],+ "commands": [+ "pytest tests/test_cli.py tests/test_loader.py"+ ],+ "targets": [],+ "reasons": {+ "tests/test_loader.py": "covers lines 61-78"+ },+ "prerequisite": null+ },+ "governed_by": [+ "dec_1",+ "dec_2"+ ],+ "risks": [+ {+ "kind": "decision",+ "text": "Decision \"Loaders stay sync-free\" governs this file; check it allows this change first.",+ "ref": "dec_1"+ },+ {+ "kind": "active_edit",+ "text": "Changed in 3 commits by ana in the 14 days before the last index; check nobody is mid-change.",+ "ref": "abc1234"+ }+ ]+ }+ },+ {+ "name": "performance_fix_steps",+ "repo_name": null,+ "detail": {+ "id": "refac4_bbbbbbbbbbbbbbbbbbbb",+ "refactoring_type": "performance_fix",+ "file_path": "src/rows.py",+ "target_symbol": "src/rows.py::load_rows",+ "line_start": 12,+ "line_end": 12,+ "plan": {+ "strategy": "batch_or_prefetch_io",+ "safety": "advisory",+ "steps": [+ {+ "order": 1,+ "action": "Add a form of fetch_row that takes every key at once",+ "symbol": "src/db.py::fetch_row",+ "file_path": "src/db.py",+ "line": null,+ "applicability": "judgment"+ },+ {+ "order": 2,+ "action": "Collect the keys before the loop and replace the per-key fetch_row call with one batched call",+ "symbol": "load_rows",+ "file_path": "src/rows.py",+ "line": 12,+ "applicability": "judgment",+ "verify": {+ "commands": [+ "pytest tests/test_rows.py"+ ],+ "tests": [+ "tests/test_rows.py"+ ],+ "coverage": "inferred"+ }+ },+ {+ "order": 3,+ "action": "Collect the keys before the loop and replace the per-key fetch_row call with one batched call",+ "symbol": "load_rows",+ "file_path": "src/rows.py",+ "line": 12,+ "applicability": "judgment"+ }+ ]+ },+ "evidence": {+ "boundary_kind": "db"+ },+ "impact_delta": 0.0,+ "effort_bucket": "M",+ "blast_radius": {+ "files": [+ "src/rows.py"+ ],+ "file_count": 1,+ "call_sites": 2+ },+ "confidence": "medium",+ "source_biomarker": "io_in_loop",+ "validation": {+ "basis": "unknown",+ "via": null,+ "total": 0,+ "tests": [],+ "truncated": false,+ "affected_files": [+ "src/rows.py"+ ],+ "affected_symbols": [],+ "commands": [],+ "targets": [],+ "reasons": {},+ "prerequisite": "No test reaches this; add a characterization test for `load_rows` before the edit."+ },+ "governed_by": [],+ "risks": []+ }+ },+ {+ "name": "split_file_older_row",+ "repo_name": null,+ "detail": {+ "id": "refac4_cccccccccccccccccccc",+ "refactoring_type": "split_file",+ "file_path": "pkg/big.py",+ "target_symbol": "big.py -> 2 files",+ "line_start": null,+ "line_end": null,+ "plan": {+ "groups": [+ {+ "name": "parsing",+ "symbols": [+ "parse_a",+ "parse_b"+ ],+ "suggested_file": "pkg/parsing.py"+ },+ {+ "name": null,+ "symbols": [+ "render"+ ],+ "suggested_file": null+ }+ ],+ "residual": {+ "symbols": [+ "Config"+ ]+ },+ "shim_required": true+ },+ "evidence": {+ "file_nloc": 900,+ "group_count": 2+ },+ "impact_delta": 0.0,+ "effort_bucket": "L",+ "blast_radius": {+ "dependent_count": 4+ },+ "confidence": "medium",+ "source_biomarker": ""+ }+ },+ {+ "name": "break_cycle_advisory",+ "repo_name": null,+ "detail": {+ "id": "refac4_gggggggggggggggggggg",+ "refactoring_type": "break_cycle",+ "file_path": "pkg/a.py",+ "target_symbol": "cycle[2]: a.py->b.py",+ "line_start": null,+ "line_end": null,+ "plan": {+ "cycle": [+ "pkg/a.py",+ "pkg/b.py"+ ],+ "cut_edges": [+ {+ "from": "pkg/a.py",+ "to": "pkg/b.py"+ }+ ]+ },+ "evidence": {+ "cycle_size": 2,+ "edge_count": 2,+ "cut_count": 1+ },+ "impact_delta": 0.0,+ "effort_bucket": "M",+ "blast_radius": {+ "files": [+ "pkg/a.py",+ "pkg/b.py"+ ],+ "file_count": 2+ },+ "confidence": "high",+ "source_biomarker": "",+ "governed_by": [],+ "risks": []+ }+ },+ {+ "name": "move_method_unaudited",+ "repo_name": null,+ "detail": {+ "id": "refac4_hhhhhhhhhhhhhhhhhhhh",+ "refactoring_type": "move_method",+ "file_path": "src/order.py",+ "target_symbol": "Order.total_tax",+ "line_start": 20,+ "line_end": 34,+ "plan": {+ "method": "total_tax",+ "from_class": "Order",+ "to_class": "TaxTable",+ "to_file": "src/tax.py"+ },+ "evidence": {+ "foreign_calls": 4,+ "own_calls": 0+ },+ "impact_delta": 0.4,+ "effort_bucket": "S",+ "blast_radius": {+ "callers": 3,+ "files": [+ "src/order.py",+ "src/tax.py"+ ],+ "co_change_partners": [+ {+ "file_path": "src/tax.py",+ "commits": 5+ }+ ]+ },+ "confidence": "high",+ "source_biomarker": "feature_envy",+ "validation": {+ "basis": "inferred",+ "via": "call-graph",+ "total": 4,+ "tests": [],+ "truncated": true,+ "affected_files": [],+ "affected_symbols": [],+ "commands": [],+ "targets": [],+ "reasons": {},+ "prerequisite": null+ },+ "governed_by": [],+ "risks": [+ {+ "kind": "public_api",+ "text": "`Order.total_tax` has 3 callers; each has to reach it through `TaxTable` after the move.",+ "ref": null+ }+ ]+ }+ }+ ],+ "opportunities": [+ {+ "name": "two_steps_one_relocated",+ "repo_name": "acme/api",+ "detail": {+ "found": true,+ "opportunity_id": "refop4_dddddddddddddddddddd",+ "file_path": "src/loader.py",+ "lead_biomarker": "complex_method",+ "lead_refactoring_type": "extract_method",+ "addresses_primary_problem": null,+ "effort_bucket": "M",+ "confidence": "high",+ "step_count": 2,+ "mechanical_steps": 1,+ "judgment_steps": 1,+ "recoverable_health": 2.5,+ "ordering_note": "A step carrying `relocated_by` names a symbol an earlier step moves.",+ "steps": [+ {+ "plan_id": "refac4_aaaaaaaaaaaaaaaaaaaa",+ "refactoring_type": "extract_method",+ "target_symbol": "Loader.load",+ "file_path": "src/loader.py",+ "line_start": 40,+ "line_end": 120,+ "relocated_by": null,+ "applicability": {+ "classification": "mechanical",+ "reasons": [+ "dataflow_proved_local_extraction"+ ],+ "unknowns": []+ },+ "validation_profile_id": "vp1"+ },+ {+ "plan_id": "refac4_eeeeeeeeeeeeeeeeeeee",+ "refactoring_type": "move_method",+ "target_symbol": "Loader.parse",+ "file_path": "src/loader.py",+ "line_start": 130,+ "line_end": null,+ "relocated_by": "refac4_aaaaaaaaaaaaaaaaaaaa",+ "applicability": {+ "classification": "judgment",+ "reasons": [],+ "unknowns": [+ "call_sites_resolved"+ ]+ },+ "validation_profile_id": "vp2"+ }+ ],+ "plans": [+ {+ "id": "refac4_aaaaaaaaaaaaaaaaaaaa",+ "refactoring_type": "extract_method",+ "file_path": "src/loader.py",+ "target_symbol": "Loader.load",+ "line_start": 40,+ "line_end": 120,+ "plan": {+ "span": {+ "start": 61,+ "end": 78+ },+ "params": [+ "path"+ ],+ "returns": [],+ "suggested_name": null+ },+ "evidence": {+ "ccn_removed": 6+ },+ "blast_radius": {+ "scope": "local"+ },+ "impact_delta": 1.25,+ "effort_bucket": "S",+ "confidence": "high",+ "source_biomarker": "complex_method",+ "status": "open"+ }+ ],+ "evidence": [+ {+ "plan_id": "refac4_ffffffffffffffffffff",+ "refactoring_type": "extract_helper",+ "target_symbol": "loader.py:10-20",+ "source_biomarker": "clone",+ "summary": {+ "duplicated_lines": 11,+ "occurrence_count": 2,+ "token_count": null+ }+ }+ ],+ "evidence_emitted": 1,+ "evidence_total": 3,+ "evidence_truncated": true,+ "validation_profiles": [+ {+ "id": "vp1",+ "basis": "measured",+ "via": "coverage",+ "total": 1,+ "tests": [+ "tests/test_loader.py"+ ],+ "truncated": false,+ "affected_files": [],+ "affected_symbols": [],+ "commands": [+ "pytest tests/test_loader.py"+ ],+ "targets": [],+ "reasons": {}+ },+ {+ "id": "vp2",+ "basis": "unknown",+ "via": null,+ "total": 0,+ "tests": [],+ "truncated": false,+ "affected_files": [],+ "affected_symbols": [],+ "commands": [],+ "targets": [],+ "reasons": {}+ }+ ]+ }+ }+ ]+}diff --git a/tests/unit/agent_prompts/test_golden.py b/tests/unit/agent_prompts/test_golden.pyindex 2f339701c..bebc7d779 100644--- a/tests/unit/agent_prompts/test_golden.py+++ b/tests/unit/agent_prompts/test_golden.py@@ -19,8 +19,11 @@ from repowise.core.agent_prompts import (FLAVORS,render_action,render_fix_item,+ render_opportunity,+ render_plan,render_verify_lines,)+from repowise.core.agent_prompts.refactoring import render_plan_spec_DIR = pathlib.Path(__file__).resolve().parents[2] / "fixtures/agent_prompts"@@ -31,6 +34,8 @@ def _load(name: str) -> dict:_ACTIONS = _load("actions.json")["cases"]_ITEMS = _load("fix_items.json")["cases"]+_PLANS = _load("refactoring.json")["plans"]+_OPPORTUNITIES = _load("refactoring.json")["opportunities"]def _render_all() -> dict:@@ -47,6 +52,17 @@ def _render_all() -> dict:for c in _ITEMS},"verify": {c["name"]: render_verify_lines(c["item"]) for c in _ITEMS},+ "refactoring_plan": {+ c["name"]: per_flavor(lambda f, c=c: render_plan(c["detail"], f, c.get("repo_name")))+ for c in _PLANS+ },+ "refactoring_plan_spec": {c["name"]: render_plan_spec(c["detail"]) for c in _PLANS},+ "refactoring_opportunity": {+ c["name"]: per_flavor(+ lambda f, c=c: render_opportunity(c["detail"], f, c.get("repo_name"))+ )+ for c in _OPPORTUNITIES+ },}@@ -79,3 +95,25 @@ def test_verify_lines_match_golden(case: dict) -> None:def test_every_case_has_a_golden() -> None:assert set(_GOLDEN["action"]) == {c["name"] for c in _ACTIONS}assert set(_GOLDEN["fix_item"]) == {c["name"] for c in _ITEMS}+ assert set(_GOLDEN["refactoring_plan"]) == {c["name"] for c in _PLANS}+ assert set(_GOLDEN["refactoring_opportunity"]) == {c["name"] for c in _OPPORTUNITIES}++[email protected]("flavor", FLAVORS)[email protected]("case", _PLANS, ids=lambda c: c["name"])+def test_refactoring_plan_matches_golden(case: dict, flavor: str) -> None:+ text = render_plan(case["detail"], flavor, case.get("repo_name"))+ assert text == _GOLDEN["refactoring_plan"][case["name"]][flavor]++[email protected]("case", _PLANS, ids=lambda c: c["name"])+def test_refactoring_plan_spec_matches_golden(case: dict) -> None:+ text = render_plan_spec(case["detail"])+ assert text == _GOLDEN["refactoring_plan_spec"][case["name"]]++[email protected]("flavor", FLAVORS)[email protected]("case", _OPPORTUNITIES, ids=lambda c: c["name"])+def test_refactoring_opportunity_matches_golden(case: dict, flavor: str) -> None:+ text = render_opportunity(case["detail"], flavor, case.get("repo_name"))+ assert text == _GOLDEN["refactoring_opportunity"][case["name"]][flavor]diff --git a/tests/unit/cli/test_refactoring_targets_stored.py b/tests/unit/cli/test_refactoring_targets_stored.pyindex 08940410f..24d20dc82 100644--- a/tests/unit/cli/test_refactoring_targets_stored.py+++ b/tests/unit/cli/test_refactoring_targets_stored.py@@ -213,3 +213,30 @@ def test_both_sources_emit_one_row_schema(repo, monkeypatch):assert set(recomputed) == set(stored)assert set(recomputed["steps"][0]) == set(stored["steps"][0])+++def test_one_plan_prints_as_a_prompt_or_its_recipe(repo, monkeypatch):+ run_async(_store(repo, _PATHS[:1]))+ _no_parse(monkeypatch)+ listed = CliRunner().invoke(+ health_command, [str(repo), "--refactoring-targets", "--format", "json", "--no-workspace"]+ )+ out = json.loads(listed.output[listed.output.index("{") :])+ plan_id = out["refactoring_opportunities"][0]["steps"][0]["plan_id"]++ as_json = CliRunner().invoke(+ health_command, [str(repo), "--plan", plan_id, "--format", "json", "--no-workspace"]+ )+ assert as_json.exit_code == 0, as_json.output+ recipe = json.loads(as_json.output[as_json.output.index("{") :])+ assert recipe["id"] == plan_id+ assert recipe["steps"][0]["span"] == {"start": 12, "end": 28}++ as_text = CliRunner().invoke(health_command, [str(repo), "--plan", plan_id, "--no-workspace"])+ assert as_text.exit_code == 0, as_text.output+ assert "## Extract Method" in as_text.output+ assert "Move lines 12-28 of `sym0`" in as_text.output++ missing = CliRunner().invoke(health_command, [str(repo), "--plan", "nope", "--no-workspace"])+ assert missing.exit_code != 0+ assert "--refactoring-targets" in missing.outputdiff --git a/tests/unit/health/test_refactoring_enrich.py b/tests/unit/health/test_refactoring_enrich.pyindex e63c73707..1dd404e3d 100644--- a/tests/unit/health/test_refactoring_enrich.py+++ b/tests/unit/health/test_refactoring_enrich.py@@ -7,6 +7,7 @@ Class LCOM4 self-check, and the config gate.from __future__ import annotations+from dataclasses import asdictfrom pathlib import Pathfrom repowise.core.analysis.health.refactoring.llm import (@@ -150,7 +151,7 @@ def test_user_prompt_split_file_carries_instruction_and_groups(tmp_path: Path) -_write_source(tmp_path, "pkg/big.py", "def parse_a():\n return 1\n")spans = _gather_spans(_split_file_suggestion(), tmp_path)prompt = _build_user_prompt(_split_file_suggestion(), spans)- assert "SPLIT FILE" in prompt+ assert prompt.startswith("## Split File")assert "parsing" in prompt and "pkg/parsing.py" in prompt@@ -166,10 +167,47 @@ def test_user_prompt_carries_plan_and_source(tmp_path: Path) -> None:sug.line_end = 2spans = _gather_spans(sug, tmp_path)prompt = _build_user_prompt(sug, spans)- assert "EXTRACT CLASS" in prompt- assert "GodClass" in prompt- assert "Structured plan" in prompt+ # The plan's recipe text, the one the copy-prompt and plan detail read.+ assert prompt.startswith("## Extract Class")+ assert "Move methods `get` and fields `x` out of `GodClass`" in prompt+ assert "## Hard constraints" in promptassert "class GodClass" in prompt+ # The reach a class split must keep working, and no instruction to run tests.+ assert "## Blast radius" in prompt and "dependents count: 0" in prompt+ assert "Run these" not in prompt+++def test_user_prompt_reads_the_stored_detail_when_given(tmp_path: Path) -> None:+ sug = _extract_class_suggestion()+ detail = {+ **asdict(sug),+ "id": "refac4_x",+ "governed_by": [],+ "risks": [{"kind": "public_api", "text": "2 files depend on this file.", "ref": None}],+ }+ prompt = _build_user_prompt(sug, [], detail)+ assert "2 files depend on this file." in prompt+ assert "were not checked" not in prompt+ assert "were not checked" in _build_user_prompt(sug, [])+++def test_the_cache_key_carries_the_prompt_version(monkeypatch) -> None:+ from repowise.core.analysis.health.refactoring.llm import enrich++ sug = _extract_class_suggestion()+ before = enrich._cache_key(sug, [], "m", "p")+ monkeypatch.setattr(enrich, "_PROMPT_VERSION", enrich._PROMPT_VERSION + 1)+ assert enrich._cache_key(sug, [], "m", "p") != before+++def test_a_draft_cached_without_the_stored_detail_is_not_reused_with_it() -> None:+ from repowise.core.analysis.health.refactoring.llm import enrich++ sug = _extract_class_suggestion()+ detail = {**asdict(sug), "id": "refac4_x", "governed_by": [], "risks": []}+ bare = enrich._cache_key(sug, [], "m", _build_user_prompt(sug, []))+ with_detail = enrich._cache_key(sug, [], "m", _build_user_prompt(sug, [], detail))+ assert bare != with_detail# ---------------------------------------------------------------------------diff --git a/tests/unit/health/test_refactoring_recipe.py b/tests/unit/health/test_refactoring_recipe.pynew file mode 100644index 000000000..e6988d1af--- /dev/null+++ b/tests/unit/health/test_refactoring_recipe.py@@ -0,0 +1,138 @@+"""A stored plan read as a recipe: preconditions, ordered steps, postconditions.++The prompt wording is pinned by ``tests/unit/agent_prompts/test_golden.py``;+these pin the structure an agent or the CLI's JSON reads.+"""++from __future__ import annotations++import json+import pathlib++from repowise.core.analysis.health.refactoring.recipe import (+ PRECONDITION_KINDS,+ RECIPE_ACTIONS,+ build_recipe,+)++_CASES = json.loads(+ (+ pathlib.Path(__file__).resolve().parents[2] / "fixtures/agent_prompts/refactoring.json"+ ).read_text(encoding="utf-8")+)+_PLANS = {case["name"]: case["detail"] for case in _CASES["plans"]}+++def _kinds(recipe: dict) -> list[str]:+ return [p["kind"] for p in recipe["preconditions"]]+++def test_extract_method_carries_the_texts_to_copy() -> None:+ recipe = build_recipe(_PLANS["extract_method_typed"])+ (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)"+ # 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")+ assert recipe["does_not"][0] == {+ "constraint": "change behaviour",+ "reason": "what the code returns, raises or writes stays the same",+ }+++def test_preconditions_list_tests_risks_and_each_governing_decision_once() -> None:+ pre = build_recipe(_PLANS["extract_method_typed"])["preconditions"]+ assert [p["kind"] for p in pre] == ["tests", "decision", "active_edit", "decision"]+ assert [p.get("ref") for p in pre if p["kind"] == "decision"] == ["dec_1", "dec_2"]+ assert {p["kind"] for p in pre} <= set(PRECONDITION_KINDS)+++def test_an_untested_plan_asks_for_a_characterization_test_first() -> None:+ recipe = build_recipe(_PLANS["performance_fix_steps"])+ assert recipe["preconditions"][0]["kind"] == "characterization"+ verify = recipe["postconditions"][0]+ assert verify["kind"] == "verify" and verify["tests"] == []+++def test_a_site_listed_twice_is_one_step_and_keeps_its_own_verify() -> None:+ steps = build_recipe(_PLANS["performance_fix_steps"])["steps"]+ assert [s["n"] for s in steps] == [1, 2]+ assert steps[1]["verify"]["commands"] == ["pytest tests/test_rows.py"]+ assert all(s["applicability"] == "judgment" for s in steps)+++def test_a_site_listed_twice_with_differing_checks_keeps_both_checks() -> None:+ site = {"order": 1, "action": "Batch it", "symbol": "f", "file_path": "a.py", "line": 3}+ check = {"commands": ["pytest t1.py"], "tests": ["t1.py"], "coverage": "inferred"}+ other = {"commands": ["pytest t2.py"], "tests": ["t2.py"], "coverage": "inferred"}+ plan = {"steps": [{**site, "verify": check}, {**site, "verify": other}]}+ (step,) = build_recipe({"refactoring_type": "performance_fix", "plan": plan})["steps"]+ assert step["verify"]["commands"] == ["pytest t1.py", "pytest t2.py"]+ assert step["verify"]["tests"] == ["t1.py", "t2.py"]+++def test_a_label_target_is_not_reported_as_a_symbol() -> None:+ recipe = build_recipe(_PLANS["split_file_older_row"])+ assert recipe["target"] == {"file": "pkg/big.py", "symbol": None, "span": None}+ assert [s["action"] for s in recipe["steps"]] == ["move", "move", "keep", "reexport"]+ # An older row with no validation still ends on a check.+ assert recipe["postconditions"][0]["kind"] == "verify"+++def test_steps_without_a_line_are_never_merged() -> None:+ unplaced = {"order": 1, "action": "Add a bulk form", "symbol": "f", "file_path": "a.py"}+ plan = {"steps": [{**unplaced, "line": None}, {**unplaced, "order": 2, "line": None}]}+ steps = build_recipe({"refactoring_type": "performance_fix", "plan": plan})["steps"]+ assert [s["n"] for s in steps] == [1, 2]+++def test_break_cycle_is_advisory_and_unaudited_types_say_so() -> None:+ cycle = build_recipe(_PLANS["break_cycle_advisory"])+ assert cycle["advisory"] is True+ assert build_recipe(_PLANS["extract_method_typed"])["advisory"] is False+ move = build_recipe(_PLANS["move_method_unaudited"])+ assert "kind_unaudited" in _kinds(move)+ assert "kind_unaudited" not in _kinds(cycle)+++def test_never_checked_annotations_say_so_and_checked_empty_does_not() -> None:+ assert "unchecked" in _kinds(build_recipe(_PLANS["split_file_older_row"]))+ # Checked, nothing found: both keys present and empty.+ assert "unchecked" not in _kinds(build_recipe(_PLANS["performance_fix_steps"]))+++def test_tests_counted_but_not_listed_still_run_before_the_edit() -> None:+ recipe = build_recipe(_PLANS["move_method_unaudited"])+ assert _kinds(recipe)[0] == "tests"+ assert recipe["postconditions"][0]["text"].startswith("The 4 guarding tests")+++def test_every_plan_type_yields_steps_in_the_shared_vocabulary() -> None:+ plans = {+ "extract_helper": {+ "occurrences": [+ {"file": "a.py", "line_start": 1, "line_end": 9},+ {"file": "b.py", "line_start": 3, "line_end": 11},+ ],+ "suggested_site": {"directory": "pkg"},+ },+ "extract_class": {"groups": [{"name": None, "methods": ["get"], "fields": ["x"]}]},+ "move_method": {"method": "m", "from_class": "A", "to_class": "B", "to_file": "b.py"},+ "break_cycle": {"cycle": ["a.py", "b.py"], "cut_edges": [{"from": "a.py", "to": "b.py"}]},+ "unknown_type": {},+ }+ for kind, plan in plans.items():+ recipe = build_recipe({"refactoring_type": kind, "file_path": "a.py", "plan": plan})+ assert recipe["steps"], kind+ assert {s["action"] for s in recipe["steps"]} <= set(RECIPE_ACTIONS), kind+ helper = build_recipe(+ {"refactoring_type": "extract_helper", "file_path": "a.py", "plan": plans["extract_helper"]}+ )+ assert [s["action"] for s in helper["steps"]] == [+ "add_helper",+ "replace_with_call",+ "replace_with_call",+ ]diff --git a/tests/unit/server/test_refactoring_opportunities.py b/tests/unit/server/test_refactoring_opportunities.pyindex 80a5a68fd..ead131785 100644--- a/tests/unit/server/test_refactoring_opportunities.py+++ b/tests/unit/server/test_refactoring_opportunities.py@@ -1332,3 +1332,81 @@ async def test_the_directive_names_no_test_file_when_only_tests_have_work(clientassert directive["status"] == "clear"assert directive["reason"] == "only_test_file_opportunities"assert directive["opportunities_total"] == 1+++# ---------------------------------------------------------------------------+# The recipe and the agent prompts core renders from it+# ---------------------------------------------------------------------------+++async def test_a_plans_recipe_is_served_only_when_asked_and_alike_on_rest_and_mcp(client, app):+ repo_id = await _seed(client, app, files=2)+ body = (await client.get(f"/api/repos/{repo_id}/refactoring/opportunities")).json()+ owner = body["items"][0]["opportunity_id"]+ detail = (await client.get(f"/api/repos/{repo_id}/refactoring/opportunities/{owner}")).json()+ plan_id = detail["steps"][0]["plan_id"]+ get_health = await _mcp(app)++ bare = (await client.get(f"/api/repos/{repo_id}/refactoring/{plan_id}")).json()+ assert "recipe" not in bare+ assert "recipe" not in (await get_health(plan_id=plan_id))["plan"]++ rest = (+ await client.get(+ f"/api/repos/{repo_id}/refactoring/{plan_id}", params={"include": "recipe"}+ )+ ).json()["recipe"]+ mcp = (await get_health(plan_id=plan_id, include=["recipe"]))["plan"]["recipe"]+ assert rest["id"] == mcp["id"] == plan_id+ assert rest["steps"] == mcp["steps"]+ (step,) = rest["steps"]+ assert step["action"] == "extract"+ assert step["span"] == {"start": 12, "end": 28}+ assert rest["postconditions"][0]["kind"] == "verify"+++async def test_the_plan_and_opportunity_prompts_are_rendered_by_the_server(client, app):+ repo_id = await _seed(client, app, files=2)+ body = (await client.get(f"/api/repos/{repo_id}/refactoring/opportunities")).json()+ owner = body["items"][0]["opportunity_id"]+ detail = (await client.get(f"/api/repos/{repo_id}/refactoring/opportunities/{owner}")).json()+ plan_id = detail["steps"][0]["plan_id"]++ plan = (+ await client.get(+ f"/api/repos/{repo_id}/refactoring/{plan_id}/prompt",+ params={"flavor": "claude-code-mcp"},+ )+ ).json()+ assert plan["flavor"] == "claude-code-mcp"+ assert "## Extract Method (`opp-repo`)" in plan["text"]+ assert f'get_health(plan_id="{plan_id}")' in plan["text"]++ opportunity = (+ await client.get(f"/api/repos/{repo_id}/refactoring/opportunities/{owner}/prompt")+ ).json()+ assert f"`{owner}`" in opportunity["text"]+ assert f"Step id: `{plan_id}`" in opportunity["text"]+ # The step's own instruction comes from its plan's recipe.+ assert "Move lines 12-28 of `" in opportunity["text"]++ missing = await client.get(f"/api/repos/{repo_id}/refactoring/opportunities/refop_nope/prompt")+ assert missing.status_code == 404+++async def test_the_opportunity_prompt_route_is_not_read_as_a_plan_id(client, app):+ """``/refactoring/{suggestion_id}/prompt`` must not swallow the opportunity+ prompt path, nor ``opportunities/{id}`` the plan prompt."""+ repo_id = await _seed(client, app, files=1)+ body = (await client.get(f"/api/repos/{repo_id}/refactoring/opportunities")).json()+ owner = body["items"][0]["opportunity_id"]++ resp = await client.get(f"/api/repos/{repo_id}/refactoring/opportunities/{owner}/prompt")+ assert resp.status_code == 200+ assert "composed the ordered refactoring steps" in resp.json()["text"]+ # "opportunities" alone is the opportunity detail route, never a plan id.+ shadow = await client.get(f"/api/repos/{repo_id}/refactoring/opportunities/prompt")+ assert shadow.json().get("detail") == "Unknown opportunity id"diff --git a/tests/unit/server/test_wire_vocabulary_parity.py b/tests/unit/server/test_wire_vocabulary_parity.pyindex 8e91bb857..edbee086b 100644--- a/tests/unit/server/test_wire_vocabulary_parity.py+++ b/tests/unit/server/test_wire_vocabulary_parity.py@@ -168,6 +168,15 @@ def test_agent_prompt_flavors_match_python() -> None:assert set(re.findall(r'"([a-z-]+)"', match.group(1))) == set(FLAVORS), alias+def test_refactoring_recipe_vocabularies_match_python() -> None:+ from repowise.core.analysis.health.refactoring.recipe import (+ PRECONDITION_KINDS,+ RECIPE_ACTIONS,+ )++ assert _union_members("RecipeAction", "refactoring.ts") == set(RECIPE_ACTIONS)+ assert _union_members("RecipePreconditionKind", "refactoring.ts") == set(PRECONDITION_KINDS)+def _interface_body(name: str, module: str) -> str:"""The text between `export interface <name> {` and its closing brace."""