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): serve long staged plans as batches to test between (#3470)
Raghav Chamadiya2a09e79ee491
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.mdindex 605e05329..21124fed3 100644--- a/docs/layers/REFACTORING.md+++ b/docs/layers/REFACTORING.md@@ -279,6 +279,10 @@ Most plans answer a health finding, so per-path marker rules inplan asks for each stage as a direct edit to the file, one at a time, never ascript that rewrites it. A staged plan whose stages cannot all be pinned downthat way falls back to a single helper, and a function with neither gets no plan.+- A staged plan with more than five stages comes in batches of at most five.+ Each batch names the tests to run before the next one, and a batch whose+ tests fail stops the plan there. The code runs after every batch, so a+ failure points at the stages just applied.- Move Method never targets a class the method only instantiates, or an ancestor ofits own class.- Split File works on any language with call resolution and suggests a split onlydiff --git a/packages/core/src/repowise/core/agent_prompts/refactoring.py b/packages/core/src/repowise/core/agent_prompts/refactoring.pyindex d7ce77a50..f874d7324 100644--- a/packages/core/src/repowise/core/agent_prompts/refactoring.py+++ b/packages/core/src/repowise/core/agent_prompts/refactoring.py@@ -157,10 +157,44 @@ 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]:+def _batch_check(batch: Mapping[str, Any]) -> list[str]:+ """What closes a batch: run its tests, and stop the plan if they fail."""+ out = [batch["text"]]+ if batch.get("tests"):+ out.append("Tests: " + ", ".join(f"`{t}`" for t in batch["tests"]))+ out.extend(f"Run: `{c}`" for c in batch.get("commands") or [])+ return out+++def _batched_entries(+ recipe: Mapping[str, Any], numbered: bool, pad: str, *, runnable: bool = True+) -> str:+ """The steps grouped by batch (``refactoring.batches``), each closed by its+ check when the reader can run tests. Under an opportunity step (*pad*) the+ batch lines are bullets with no blank line, so they stay inside the step."""+ steps = {s["n"]: s for s in recipe["steps"]}+ batches = recipe["batches"]+ lead = f"{pad}- " if pad else ""+ blocks: list[str] = []+ for batch in batches:+ first, last = batch["stages"]["first"], batch["stages"]["last"]+ entries = [_step_entry(steps[n], f"{n}." if numbered else "-", pad) for n in batch["steps"]]+ blocks += [+ f"{lead}**Batch {batch['n']} of {len(batches)}: stages {first}-{last}**",+ "\n".join(entries),+ ]+ if runnable:+ blocks.append("\n".join(f"{lead}{line}" for line in _batch_check(batch)))+ return ("\n" if pad else "\n\n").join(blocks)+++def _steps_section(recipe: Mapping[str, Any], *, runnable: bool = True) -> list[str]:if recipe["advisory"]:body = "\n".join(_step_entry(s, "-", "") for s in recipe["steps"])return [f"## {_advisory_heading(recipe)}", "", body, ""]+ if recipe.get("batches"):+ body = _batched_entries(recipe, True, "", runnable=runnable)+ return ["## Steps, in order, in batches", "", body, ""]body = "\n".join(_step_entry(s, f"{s['n']}.", "") for s in recipe["steps"])return ["## Steps, in order", "", body, ""]@@ -221,7 +255,7 @@ def _plan_sections(bullet_list(facts),"",_before_section(recipe),- *_steps_section(recipe),+ *_steps_section(recipe, runnable=runnable),_verify_section(recipe, runnable=runnable),]@@ -329,7 +363,10 @@ def _opportunity_step(step: Mapping[str, Any], n: int, plan: Mapping[str, Any] |recipe = build_recipe(plan)if recipe["advisory"]:lines.append(f" - {_advisory_heading(recipe)}:")- lines.extend(_step_entry(s, "-", " ") for s in recipe["steps"])+ if recipe.get("batches"):+ lines.append(_batched_entries(recipe, False, " "))+ else:+ lines.extend(_step_entry(s, "-", " ") for s in recipe["steps"])return "\n".join(lines)diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/batches.py b/packages/core/src/repowise/core/analysis/health/refactoring/batches.pynew file mode 100644index 000000000..c0746701b--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/refactoring/batches.py@@ -0,0 +1,98 @@+"""A staged Extract Method plan over five stages, as ordered batches to test between.++Each batch names the tests to run before the next, and a failing batch stops the+plan. Every batch end runs: a stage's call binds its outputs, the stage planner+refuses plans whose reads would change (``dataflow.stages``), the parameter object+is built in batch 1, and a local import leaves with its last reader. Derived at+serve time: nothing is stored and plan ids do not change.+"""++from __future__ import annotations++from collections.abc import Mapping, Sequence+from typing import Any++from .commands import commands_for_tests++#: The most stages one batch holds.+BATCH_MAX_STAGES = 5+#: Tests a batch lists, a size choice; the command widens to their files when more reach.+_BATCH_TESTS = 3+++def _validation(detail: Mapping[str, Any]) -> Mapping[str, Any]:+ validation = detail.get("validation")+ return validation if isinstance(validation, Mapping) else {}+++def _batch_tests(detail: Mapping[str, Any]) -> tuple[list[str], int]:+ """The tests to run after a batch, most direct first, and how many reach.++ Every stage lifts lines out of the one target function, so the tests that+ reach it guard each batch. Read from the plan's own guarding tests+ (file-level today); a function-level test map replaces this body.+ """+ validation = _validation(detail)+ tests = [str(t) for t in validation.get("tests") or [] if t]+ total = validation.get("total")+ return tests[:_BATCH_TESTS], max(total if isinstance(total, int) else 0, len(tests))+++def _sizes(count: int) -> list[int]:+ """*count* stages in as few batches as the cap allows, sizes within one."""+ batches = -(-count // BATCH_MAX_STAGES)+ small, extra = divmod(count, batches)+ return [small + (1 if k < extra else 0) for k in range(batches)]+++def _check(tests: list[str], detail: Mapping[str, Any]) -> str:+ if tests:+ return "run the tests named here"+ if _validation(detail).get("prerequisite"):+ return "run the test you added before the edit (no existing test reaches this function)"+ return "run the tests under Verify"+++def _text(n: int, total: int, check: str) -> str:+ """The batch's closing rule; its number and stages are fields of their own."""+ stop = f"do not start batch {n + 1}" if n < total else "the plan is not done"+ return f"With these stages in, {check}. If any fails, stop here and report it; {stop}."+++def stage_batches(+ detail: Mapping[str, Any], steps: Sequence[Mapping[str, Any]]+) -> list[dict[str, Any]] | None:+ """*steps* (a staged plan's numbered recipe steps) as ordered batches, or+ None when the plan is not staged or has at most :data:`BATCH_MAX_STAGES`+ stages. Each batch is ``{n, steps, stages: {first, last}, tests, commands,+ text}``; ``steps`` are recipe step numbers, the steps before stage 1 (the+ parameter object) in batch 1."""+ if detail.get("refactoring_type") != "extract_method":+ return None+ numbers = [s["n"] for s in steps if s.get("action") == "extract"]+ if len(numbers) <= BATCH_MAX_STAGES:+ return None+ lead = [s["n"] for s in steps if s["n"] < numbers[0]]+ tests, total = _batch_tests(detail)+ commands = commands_for_tests(tests, total=total)+ check = _check(tests, detail)+ sizes = _sizes(len(numbers))+ out: list[dict[str, Any]] = []+ first = 1+ for n, size in enumerate(sizes, 1):+ last = first + size - 1+ out.append(+ {+ "n": n,+ "steps": (lead if n == 1 else []) + numbers[first - 1 : last],+ "stages": {"first": first, "last": last},+ "tests": tests,+ "commands": commands,+ "text": _text(n, len(sizes), check),+ }+ )+ first = last + 1+ return out+++__all__ = ["BATCH_MAX_STAGES", "stage_batches"]diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/commands.py b/packages/core/src/repowise/core/analysis/health/refactoring/commands.pynew file mode 100644index 000000000..36dc39f19--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/refactoring/commands.py@@ -0,0 +1,34 @@+"""The command that runs a plan's tests, shared by plan validation and staged-plan batches."""++from __future__ import annotations+++def commands_for_tests(tests: list[str], *, total: int | None = None) -> list[str]:+ """A command that runs at least everything the plan says validates it.++ When the displayed list is capped, enumerating only the shown tests would+ read as a complete validation run while silently skipping the rest, so the+ selection widens to the files those tests live in: bounded by file count+ rather than test count, and never narrower than the evidence.++ An empty list means the plan has no command to suggest. Every command names+ its tests: with none found, a bare ``pytest`` or ``npm test`` would run a+ whole suite as if it guarded the change. Nothing here looks at the+ repository's tooling, so a language other than Python or JS/TS gets none in+ place of a guess that would fail when run.+ """+ if total is not None and total > len(tests):+ tests = sorted({test.split("::", 1)[0] for test in tests})+ python_tests = sorted(test for test in tests if ".py" in test)+ js_tests = sorted(+ test for test in tests if any(ext in test for ext in (".ts", ".tsx", ".js", ".jsx"))+ )+ commands: list[str] = []+ if python_tests:+ commands.append("pytest " + " ".join(python_tests))+ if js_tests:+ commands.append("npm test -- " + " ".join(js_tests))+ return commands+++__all__ = ["commands_for_tests"]diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.pyindex abe743a06..ddae51cf4 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py@@ -451,8 +451,13 @@ def _staged_fields(# Without an object (no free variable name for it) the values stay plain.context = staged.context if obj else ()imports = names.imports(analysis.fn_node)+ # The function's import goes with the last stage reading it, so the code+ # still runs when the stages before it are applied and tested alone.+ last = {+ imported: i for i, stage_imports in enumerate(staged.imports) for imported in stage_imports+ }stages = []- for x, reimports in zip(staged.stages, staged.imports, strict=True):+ for i, (x, reimports) in enumerate(zip(staged.stages, staged.imports, strict=True)):name = render.private_name(language,names.claim_first(@@ -473,7 +478,8 @@ def _staged_fields(async_host=async_fields.get("async_host", True),leading=lead,)- _add_stage_notes(symbol["new_symbol"], lead, carried, reimports, staged.moved_imports)+ moved = frozenset(m for m in staged.moved_imports if last.get(m) == i)+ _add_stage_notes(symbol["new_symbol"], lead, carried, reimports, moved)stages.append({"span": {"start": x.start_line, "end": x.end_line},diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recipe.py b/packages/core/src/repowise/core/analysis/health/refactoring/recipe.pyindex 0b00fab73..02d638e29 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/recipe.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recipe.py@@ -18,6 +18,7 @@ from collections.abc import Callable, Mappingfrom typing import Any, Literal, get_argsfrom .annotations import RiskKind+from .batches import stage_batchesfrom .render import NAME_PLACEHOLDER, TYPE_PLACEHOLDERRecipeAction = Literal[@@ -658,8 +659,10 @@ def _extract_does_not(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."""+ postconditions, does_not}``, plus ``batches`` on a staged plan over five+ stages (:mod:`.batches`). Pure: reads only the dict it is given."""steps = recipe_steps(detail)+ batches = stage_batches(detail, steps)return {"id": detail.get("id"),"kind": detail.get("refactoring_type"),@@ -677,6 +680,7 @@ def build_recipe(detail: Mapping[str, Any]) -> dict[str, Any]:"steps": steps,"postconditions": _postconditions(detail),"does_not": _does_not(detail, steps),+ **({"batches": batches} if batches else {}),}diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.pyindex 3e92fa79d..717865974 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py@@ -32,6 +32,7 @@ from repowise.core.code_origin import ship_rankfrom repowise.core.test_paths import is_test_support_path, names_test_for, paired_test_namesfrom .annotations import PlanAnnotations, partner_rows+from .commands import commands_for_testsfrom .models import RefactoringSuggestionfrom .render import list_plan@@ -620,34 +621,6 @@ def _rank_target_tests(return out-def _commands(tests: list[str], *, total: int | None = None) -> list[str]:- """A command that runs at least everything the plan says validates it.-- When the displayed list is capped, enumerating only the shown tests would- read as a complete validation run while silently skipping the rest, so the- selection widens to the files those tests live in: bounded by file count- rather than test count, and never narrower than the evidence.-- An empty list means the plan has no command to suggest. Every command names- its tests: with none found, a bare ``pytest`` or ``npm test`` would run a- whole suite as if it guarded the change. Nothing here looks at the- repository's tooling, so a language other than Python or JS/TS gets none in- place of a guess that would fail when run.- """- if total is not None and total > len(tests):- tests = sorted({test.split("::", 1)[0] for test in tests})- python_tests = sorted(test for test in tests if ".py" in test)- js_tests = sorted(- test for test in tests if any(ext in test for ext in (".ts", ".tsx", ".js", ".jsx"))- )- commands: list[str] = []- if python_tests:- commands.append("pytest " + " ".join(python_tests))- if js_tests:- commands.append("npm test -- " + " ".join(js_tests))- return commands--def _characterization_step(suggestion: RefactoringSuggestion) -> str:"""The step before an edit no test reaches: pin today's behaviour first."""symbol = suggestion.target_symbol@@ -870,7 +843,7 @@ def build_validation_plan(truncated=aggregate_total > len(ordered_tests[:cap]),affected_files=files,affected_symbols=affected_symbols(suggestion),- commands=_commands(ordered_tests[:cap], total=aggregate_total),+ commands=commands_for_tests(ordered_tests[:cap], total=aggregate_total),targets=target_rows,reasons={test: best[test][1] for test in ordered_tests[:cap]} if order_tests else {},prerequisite=(diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.tsindex 9182bb2bb..717a31e14 100644--- a/packages/types/src/refactoring.ts+++ b/packages/types/src/refactoring.ts@@ -279,6 +279,21 @@ export interface RefactoringRecipe {>;/** `constraint` reads after "Do not"; `reason` says why, when it is not obvious. */does_not: Array<{ constraint: string; reason: string | null }>;+ /** A staged plan over five stages only: its steps in ordered batches of at+ * most five, each with the tests to run before the next; a failing batch+ * stops the plan. */+ batches?: RecipeBatch[];+}++/** One batch of a long staged plan. Mirrors `stage_batches`. */+export interface RecipeBatch {+ n: number;+ /** Recipe step numbers, in order. */+ steps: number[];+ stages: { first: number; last: number };+ tests: string[];+ commands: string[];+ text: string;}export interface RefactoringTypeCount {diff --git a/tests/unit/agent_prompts/test_batched_plans.py b/tests/unit/agent_prompts/test_batched_plans.pynew file mode 100644index 000000000..801ffc4da--- /dev/null+++ b/tests/unit/agent_prompts/test_batched_plans.py@@ -0,0 +1,121 @@+"""A staged plan over five stages renders as batches, each closed by its tests."""++from __future__ import annotations++import re++import pytest++from repowise.core.agent_prompts import FLAVORS, render_opportunity, render_plan+from repowise.core.agent_prompts.preamble import preamble+from repowise.core.agent_prompts.refactoring import render_plan_spec+from repowise.core.analysis.health.refactoring.recipe import build_recipe++#: Agent tool names no prompt says (harnesses name their tools differently).+#: Read / Edit / Write are also English verbs the shared preamble uses, so the+#: whole-text scan takes the unambiguous names and the batch lines take all.+_TOOL_NAMES = re.compile(r"\b(Grep|Glob|TodoWrite|Bash|str_replace)\b|@codebase")+_VERB_TOOLS = re.compile(r"\b(Read|Edit|Write)\b")+++def _no_tool_names(text: str) -> None:+ # The flavour opening is shared by every refactoring prompt and owns its own wording.+ for flavor in FLAVORS:+ for producer in ("refactoring_plan", "refactoring_opportunity"):+ text = text.replace(preamble(flavor, producer), "")+ assert not _TOOL_NAMES.search(text)+ batch_lines = [ln for ln in text.splitlines() if "Batch " in ln or "stages in" in ln]+ assert batch_lines and not any(_VERB_TOOLS.search(ln) for ln in batch_lines)+++def _detail(stages: int) -> dict:+ return {+ "id": "rp_batched",+ "refactoring_type": "extract_method",+ "file_path": "pkg/mod.py",+ "target_symbol": "pkg/mod.py::run",+ "line_start": 1,+ "line_end": 200,+ "plan": {+ "stages": [+ {+ "span": {"start": 20 * k, "end": 20 * k + 9},+ "params": ["rows"],+ "returns": [],+ "suggested_name": f"_stage_{k}",+ "anchors": {"first": f" if rows_{k}:", "last": f" done_{k}()"},+ }+ for k in range(1, stages + 1)+ ],+ "orchestrator": {"ccn_before": 90, "ccn_after": 20},+ },+ "validation": {+ "tests": ["tests/test_mod.py::test_run", "tests/test_cli.py::test_main"],+ "total": 2,+ "commands": ["pytest tests/test_cli.py::test_main tests/test_mod.py::test_run"],+ "basis": "inferred",+ },+ }+++def test_the_recipe_carries_batches_only_over_five_stages():+ assert len(build_recipe(_detail(7))["batches"]) == 2+ assert "batches" not in build_recipe(_detail(5))+++def _stage_order(text: str, stages: int) -> list[int]:+ starts = [text.index(f"Stage {k} of {stages}:") for k in range(1, stages + 1)]+ assert starts == sorted(starts)+ return starts++[email protected]("flavor", FLAVORS)+def test_a_plan_prompt_groups_its_steps_by_batch(flavor):+ text = render_plan(_detail(7), flavor)+ assert "## Steps, in order, in batches" in text+ first, second = text.index("**Batch 1 of 2: stages 1-4**"), text.index("**Batch 2 of 2: stages 5-7**")+ starts = _stage_order(text, 7)+ assert first < starts[0] and starts[3] < second < starts[4]+ # Batch 1's check closes it, before batch 2 starts.+ assert starts[3] < text.index("do not start batch 2") < second+ assert "Run: `pytest tests/test_cli.py::test_main tests/test_mod.py::test_run`" in text+ assert text.count("If any fails, stop here") == 2+ # The header names the batch and its stages once; the check does not repeat them.+ assert text.count("Batch 1 of 2") == 1 and "stages 1-4" not in text[first + 30:second]+ _no_tool_names(text)+++def test_a_short_plan_keeps_one_step_list():+ text = render_plan(_detail(5))+ assert "## Steps, in order\n" in text and "Batch" not in text+++def test_a_spec_keeps_the_batches_but_runs_nothing():+ text = render_plan_spec(_detail(6))+ assert "**Batch 1 of 2: stages 1-3**" in text and "**Batch 2 of 2: stages 4-6**" in text+ _stage_order(text, 6)+ assert "Run: " not in text and "Tests: " not in text and "If any fails" not in text+ _no_tool_names(text)+++def test_an_opportunity_keeps_the_batches_inside_its_step():+ opportunity = {+ "opportunity_id": "ro_1",+ "file_path": "pkg/mod.py",+ "lead_refactoring_type": "extract_method",+ "steps": [+ {"plan_id": "rp_batched", "refactoring_type": "extract_method", "file_path": "pkg/mod.py",+ "line_start": 1, "line_end": 200, "target_symbol": "run", "applicability": {}}+ ],+ "plans": [_detail(6)],+ }+ text = render_opportunity(opportunity)+ first, second = text.index(" - **Batch 1 of 2: stages 1-3**"), text.index(" - **Batch 2 of 2: stages 4-6**")+ starts = _stage_order(text, 6)+ assert first < starts[0] and starts[2] < text.index("do not start batch 2") < second < starts[3]+ assert " - With these stages in, run the tests named here." in text+ assert text.count("If any fails, stop here") == 2+ # No blank line between the step's head and its last batch line: the batches stay in the item.+ step = text[text.index("1. **Extract Method**"):text.index("the plan is not done")]+ assert "\n\n" not in step+ _no_tool_names(text)diff --git a/tests/unit/health/test_refactoring_batches.py b/tests/unit/health/test_refactoring_batches.pynew file mode 100644index 000000000..02c0dde34--- /dev/null+++ b/tests/unit/health/test_refactoring_batches.py@@ -0,0 +1,162 @@+"""A staged Extract Method plan over five stages, served as batches to test between."""++from __future__ import annotations++import re+from pathlib import Path++import pytest++from repowise.core.analysis.health.refactoring.batches import (+ BATCH_MAX_STAGES,+ stage_batches,+)+from repowise.core.analysis.health.refactoring.models import RefactoringSuggestion+from repowise.core.analysis.health.refactoring.recipe import build_recipe, recipe_steps+from repowise.core.analysis.health.refactoring.recommendations import build_validation_plan++from .test_extract_method_stages import _persist, _plans++#: Agent tool names a plan never says: harnesses name their tools differently.+_TOOL_NAMES = re.compile(+ r"\b(Read|Grep|Glob|Edit|Write|TodoWrite|Bash|str_replace)\b|@codebase"+)+++def _staged_detail(+ stages: int, *, obj: bool = False, tests: list[str] | None = None, **validation+) -> dict:+ plan = {+ "stages": [+ {"span": {"start": 10 * k, "end": 10 * k + 5}, "params": [], "returns": []}+ for k in range(1, stages + 1)+ ],+ "orchestrator": {"ccn_before": 80, "ccn_after": 20},+ }+ if obj:+ plan["parameter_object"] = {"name": "_Ctx", "var": "ctx", "construct_before": 10}+ return {+ "refactoring_type": "extract_method",+ "file_path": "pkg/mod.py",+ "target_symbol": "pkg/mod.py::run",+ "plan": plan,+ "validation": {"tests": tests or [], "commands": [], **validation},+ }+++def _batches(detail: dict) -> list[dict] | None:+ return stage_batches(detail, recipe_steps(detail))+++ ("stages", "sizes"),+ [(6, [3, 3]), (10, [5, 5]), (11, [4, 4, 3]), (21, [5, 4, 4, 4, 4])],+)+def test_batches_hold_at_most_five_stages_in_order(stages, sizes):+ batches = _batches(_staged_detail(stages))+ got = [b["stages"]["last"] - b["stages"]["first"] + 1 for b in batches]+ assert got == sizes and max(got) <= BATCH_MAX_STAGES+ assert [b["n"] for b in batches] == list(range(1, len(sizes) + 1))+ # Every stage once, in source order.+ assert [n for b in batches for n in b["steps"]] == list(range(1, stages + 1))+++def test_five_stages_or_fewer_and_other_kinds_are_not_batched():+ assert _batches(_staged_detail(5)) is None+ assert _batches({**_staged_detail(8), "refactoring_type": "split_file"}) is None+ assert _batches({"refactoring_type": "extract_method", "plan": {"span": {"start": 1, "end": 9}}}) is None+++def test_the_parameter_object_is_built_in_the_first_batch():+ batches = _batches(_staged_detail(7, obj=True))+ # Step 1 adds the object, steps 2-8 are the stages.+ assert batches[0]["steps"] == [1, 2, 3, 4, 5]+ assert batches[1]["steps"] == [6, 7, 8]+ assert batches[1]["stages"] == {"first": 5, "last": 7}+++def test_each_batch_names_its_tests_and_stops_the_plan_on_failure():+ tests = ["tests/test_a.py::test_one", "tests/test_b.py", "tests/test_c.py", "tests/test_d.py"]+ batches = _batches(_staged_detail(7, tests=tests))+ for batch in batches:+ assert batch["tests"] == tests[:3]+ # A capped list widens to its files, as the plan's own command does.+ assert batch["commands"] == ["pytest tests/test_a.py tests/test_b.py tests/test_c.py"]+ assert "If any fails, stop here" in batch["text"]+ assert not _TOOL_NAMES.search(batch["text"])+ assert "do not start batch 2" in batches[0]["text"]+ assert "the plan is not done" in batches[-1]["text"]+++def test_an_uncapped_list_runs_exactly_its_tests():+ tests = ["tests/test_a.py::test_one", "tests/test_b.py::test_two"]+ batch = _batches(_staged_detail(6, tests=tests, total=2))[0]+ assert batch["commands"] == ["pytest tests/test_a.py::test_one tests/test_b.py::test_two"]+++def _no_reach_detail() -> dict:+ """A staged plan no test reaches, with the validation the ranker builds for it."""+ detail = _staged_detail(6)+ suggestion = RefactoringSuggestion(+ refactoring_type="extract_method",+ file_path=detail["file_path"],+ target_symbol="run",+ line_start=1,+ line_end=80,+ plan=detail["plan"],+ evidence={},+ impact_delta=1.0,+ effort_bucket="M",+ blast_radius={},+ confidence="medium",+ source_biomarker="complex_method",+ )+ detail["validation"] = build_validation_plan(suggestion, {}, {}).as_dict()+ return detail+++def test_a_batch_with_no_reaching_test_runs_the_characterization_test():+ detail = _no_reach_detail()+ recipe = build_recipe(detail)+ # The batch's wording leans on this precondition being in the recipe.+ assert [p for p in recipe["preconditions"] if p["kind"] == "characterization"]+ batch = stage_batches(detail, recipe["steps"])[0]+ assert batch["tests"] == [] and batch["commands"] == []+ assert "the test you added before the edit" in batch["text"]+++def test_unlisted_reaching_tests_point_at_verify():+ batch = _batches(_staged_detail(6, total=12))[0]+ assert batch["tests"] == [] and "run the tests under Verify" in batch["text"]+++def test_the_typescript_batch_shape_matches_the_engine():+ types = Path(__file__).resolve().parents[3] / "packages" / "types" / "src" / "refactoring.ts"+ match = re.search(r"interface RecipeBatch \{(.*?)\n\}", types.read_text(encoding="utf-8"), re.S)+ assert match, "RecipeBatch is not declared in refactoring.ts"+ fields = set(re.findall(r"^ (\w+)\??:", match.group(1), re.M))+ batch = _batches(_staged_detail(6))[0]+ assert fields == set(batch)+ assert set(batch["stages"]) == {"first", "last"}+ assert re.search(r"^ batches\?: RecipeBatch\[\];", types.read_text(encoding="utf-8"), re.M)+++def test_a_shared_local_import_is_dropped_only_with_its_last_reader():+ """Removing it with stage 1 would break every later stage still in the+ function when the first batch's tests run."""+ src = _persist(sections=14).replace(+ "from store import other_step_1, step_1", "from store import other_step_1, step_1, timed"+ )+ plan = _plans(src)["persist"].plan+ stages = plan["stages"]+ assert len(stages) > BATCH_MAX_STAGES+ readers = [+ k for k, s in enumerate(stages) if any("timed" in n and n.startswith("Import ") for n in s["new_symbol"].get("notes", []))+ ]+ removers = [+ k for k, s in enumerate(stages) if any("timed" in n and n.startswith("Remove ") for n in s["new_symbol"].get("notes", []))+ ]+ assert len(readers) == len(stages) and removers == [readers[-1]]+ detail = {"refactoring_type": "extract_method", "plan": plan, "validation": {}}+ batches = _batches(detail)+ assert len(batches) == 2 and batches[-1]["stages"]["last"] == len(stages)