Skip to content

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

feat(health): a due Fix first item carries its first step and verify command (#3369)

Raghav Chamadiyac70e7b97cfdd
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index d9b42fd0d..1543eb149 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -341,7 +341,7 @@ Code-health scores and findings from the stored analysis, across defect risk, ma
Only one of `fix_id`, `finding_id`, `plan_id`, `opportunity_id` per call; passing two returns `mode: "conflict"`.
-**Key return fields:** `mode`, `fix_first` (`lead` with its `next_call`, up to five `items`, `counts`, `totals`), `kpis`, `gap_analysis`, `worst_files`, `high_leverage_files` (ranked by `weighted_deficit`), `top_findings`, `unresolved`, and the opt-in blocks you named. `_meta.health_analysis` says whether stored analysis exists and which commit it describes.
+**Key return fields:** `mode`, `fix_first` (`lead` with its `next_call`, up to five `items`, `counts`, `totals`; a due lead carries its `first_step` and `verify` command, so it can be started without a `fix_id` call; `only=["fix_first"]` adds them to the other due items on the page), `kpis`, `gap_analysis`, `worst_files`, `high_leverage_files` (ranked by `weighted_deficit`), `top_findings`, `unresolved`, and the opt-in blocks you named. `_meta.health_analysis` says whether stored analysis exists and which commit it describes.
The response is bounded. Pair `include` with `only` to keep one block, e.g. `get_health(include=["refactoring"], only=["refactoring_opportunities"])`.
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.md
index aef09bb72..caba9c62e 100644
--- a/docs/layers/CODE_HEALTH.md
+++ b/docs/layers/CODE_HEALTH.md
@@ -121,6 +121,8 @@ worth doing.
| `next` | Worth doing, needs judgment |
| `later` | Real but can wait; the reason is shown |
+A `now` or `next` item shows its first step and the command that checks it without opening it, on the card, and over MCP for the lead and for each item of an `only=["fix_first"]` page. When no test reaches the code, Verify says to add a characterization test first. An Extract Method step shows the helper's header and the call that replaces the lines, ready to copy.
+
Findings, performance causes, refactoring plans and Fix first items are counted the
same way everywhere: open in the inventory, in scope, eligible, due (tier `now` or
`next`) and shown, with every exclusion named by its reason. The numbers on the
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index b7b9caa4d..6d73e1fae 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -326,7 +326,7 @@ One ranked queue across refactoring, performance and code-shape work, the same o
| Field | Meaning |
|-------|---------|
| `lead` | The queue's first item, whatever page `items` is, with its `next_call` |
-| `items` | Up to five. With `only=["fix_first"]` the list pages from `cursor` and `recovery.fix_first` names the next page; a passed `limit` sets the page size, up to 25. Each: `id`, `tier`, `kind`, `title`, `target`, `why`, `gain`, `effort`, `confidence`; `get_health(fix_id=...)` returns one in full, with its `next_call` |
+| `items` | Up to five. With `only=["fix_first"]` the list pages from `cursor` and `recovery.fix_first` names the next page; a passed `limit` sets the page size, up to 25. Each: `id`, `tier`, `kind`, `title`, `target`, `why`, `gain`, `effort`, `confidence`; a `now` or `next` `lead` also carries `first_step` (`action`, `line`, and `file` when it is not the target's) and `verify` (`command`, or `prerequisite` when no test reaches it); with `only=["fix_first"]` the other due items among a page's first five carry them too. `get_health(fix_id=...)` returns one in full, with its `next_call` |
| `items_total`, `cursor` | The eligible items `items` was cut from, and where the page starts |
| `counts` | `inventory` (every unit considered), `in_scope` (less units excluded for where the code lives: `test`, `tooling`, `generated`, `vendored`, `docs_example`), `eligible` (became an item), `due` (eligible items in tier `now` or `next`), `shown` (items in this response), `excluded` (every non-zero exclusion, by reason) |
| `tier` | `now` (worth doing, safe to start), `next` (worth doing, needs judgment), `later` |
diff --git a/packages/core/src/repowise/core/agent_prompts/fix_first.py b/packages/core/src/repowise/core/agent_prompts/fix_first.py
index 66434b168..ab35b10ff 100644
--- a/packages/core/src/repowise/core/agent_prompts/fix_first.py
+++ b/packages/core/src/repowise/core/agent_prompts/fix_first.py
@@ -39,7 +39,10 @@ def render_verify_lines(item: Mapping[str, Any]) -> str:
verify = item["verify"]
tests = verify["tests"]
if not tests:
- return "No guarding tests found. Write a test that pins the current behaviour before you change anything."
+ # The fallback covers items stored before Verify named its prerequisite.
+ return verify.get("prerequisite") or (
+ "No guarding tests found. Write a test that pins the current behaviour before you change anything."
+ )
listed = "\n".join(
f"- `{t['path']}`" + (f": {t['reason']}" if t.get("reason") else "") for t in tests
)
@@ -57,7 +60,12 @@ def _step(s: Mapping[str, Any]) -> str:
line = s.get("line")
loc = f"{s['file_path']}{f':{line}' if line else ''}"
tag = " [mechanical]" if s.get("mechanical") else " [judgment]"
- return f"{s['order']}. {s['text']} (`{loc}`){tag}"
+ extra = [
+ f" {label}: `{s[key]}`"
+ for key, label in (("signature", "Helper"), ("call", "Call"), ("command", "Check"))
+ if s.get(key)
+ ]
+ return "\n".join([f"{s['order']}. {s['text']} (`{loc}`){tag}", *extra])
def render_fix_item(item: Mapping[str, Any], flavor: str = "generic", repo_name: str | None = None) -> str:
diff --git a/packages/core/src/repowise/core/analysis/health/fix_first/build.py b/packages/core/src/repowise/core/analysis/health/fix_first/build.py
index 4fb00aa84..9ca9bc992 100644
--- a/packages/core/src/repowise/core/analysis/health/fix_first/build.py
+++ b/packages/core/src/repowise/core/analysis/health/fix_first/build.py
@@ -87,6 +87,7 @@ from repowise.core.analysis.health.queue.value import (
tier,
worth,
)
+from repowise.core.analysis.health.refactoring.render import NAME_PLACEHOLDER
from repowise.core.analysis.health.rows import detail_map, field, json_field
from repowise.core.analysis.health.scoring import biomarker_dimension
from repowise.core.analysis.health.suggestions import suggestion_for
@@ -223,9 +224,27 @@ def _verify(profile: Mapping[str, Any] | None) -> FixVerify:
int(profile.get("total") or len(tests)),
commands[0] if commands else None,
basis if basis in ("measured", "inferred") else "unknown",
+ None if tests else profile.get("prerequisite"),
)
+def _step_command(check: Mapping[str, Any] | None, item_command: str | None) -> str | None:
+ """A step's own command (a validation profile, or a plan step's ``verify``),
+ kept only when it differs from the item's."""
+ commands = (check or {}).get("commands") or []
+ return commands[0] if commands and commands[0] != item_command else None
+
+
+def _helper_code(body: Mapping[str, Any]) -> dict[str, str | None]:
+ """An Extract Method plan's rendered helper header and call, when it wrote them."""
+ symbol = body.get("new_symbol") or {}
+ site = body.get("call_site") or {}
+ return {
+ "signature": symbol.get("signature_text") if isinstance(symbol, dict) else None,
+ "call": site.get("new_text") if isinstance(site, dict) else None,
+ }
+
+
class _Files:
"""Per-file facts the units share: metrics, heat, history context."""
@@ -336,7 +355,13 @@ class _Files:
list(body.get("returns") or []),
is_async=bool(body.get("needs_async", False)),
)
- return FixStep(1, f"Extract lines {start}-{end} of {tail} into {into}", path, start)
+ return FixStep(
+ 1,
+ f"Extract lines {start}-{end} of {tail} into {into}",
+ path,
+ start,
+ **_helper_code(body),
+ )
shape = self.shape(path, function)
start, end = shape.get("deep_start"), shape.get("deep_end")
if start and end:
@@ -471,13 +496,17 @@ def _span(plan: Any) -> tuple[int | None, int | None]:
return None, None
-def _refactor_step(order: int, step: Mapping[str, Any], plan: Any) -> FixStep:
+def _refactor_step(
+ order: int, step: Mapping[str, Any], plan: Any, command: str | None = None
+) -> FixStep:
kind = step.get("refactoring_type") or ""
path = step.get("file_path") or ""
sym = text.short_symbol(step.get("target_symbol")) or text.basename(path)
start, end = _span(plan)
+ body = _plan_body(plan)
+ code: dict[str, str | None] = {}
if kind == "extract_method":
- body = _plan_body(plan)
+ code = _helper_code(body)
into = text.signature(
body.get("suggested_name"),
list(body.get("params") or []),
@@ -489,7 +518,7 @@ def _refactor_step(order: int, step: Mapping[str, Any], plan: Any) -> FixStep:
elif kind == "extract_helper":
line_text = f"Replace the duplicate in {sym} with a call to one shared helper"
elif kind == "extract_class":
- groups = [g for g in _plan_body(plan).get("groups") or [] if g.get("methods")]
+ groups = [g for g in body.get("groups") or [] if g.get("methods")]
members = sorted(groups, key=lambda g: len(g["methods"]))[0]["methods"] if groups else []
line_text = (
f"Move {', '.join(members[:4])}"
@@ -499,7 +528,7 @@ def _refactor_step(order: int, step: Mapping[str, Any], plan: Any) -> FixStep:
else f"Move a cohesive group of {sym}'s methods into a new class"
)
elif kind == "split_file":
- names = [g.get("name") for g in _plan_body(plan).get("groups") or [] if g.get("name")]
+ names = [g.get("name") for g in body.get("groups") or [] if g.get("name")]
line_text = (
f"Split {text.basename(path)} into {', '.join(names[:4])}"
+ (f" and {len(names) - 4} more" if len(names) > 4 else "")
@@ -515,16 +544,16 @@ def _refactor_step(order: int, step: Mapping[str, Any], plan: Any) -> FixStep:
else _uncut_cycle_text(path, plan)
)
elif kind == "move_method":
- dest = _plan_body(plan).get("to_class") or text.basename(
- _plan_body(plan).get("to_file") or ""
- )
+ dest = body.get("to_class") or text.basename(body.get("to_file") or "")
line_text = (
f"Move {sym} to {dest}" if dest else f"Move {sym} to the class it uses most"
)
else:
line_text = f"Apply the {text.humanize(kind)} step to {sym}"
mechanical = (step.get("applicability") or {}).get("classification") == "mechanical"
- return FixStep(order, line_text, path, start or step.get("line_start"), mechanical)
+ return FixStep(
+ order, line_text, path, start or step.get("line_start"), mechanical, **code, command=command
+ )
def _uncut_cycle_text(path: str, plan: Any) -> str:
@@ -643,7 +672,7 @@ def _refactor_unit(
f"Start breaking up {sym} ({text.size_brief(shape)}): first lift lines "
f"{start}-{end}"
)
- into = f" into {body.get('suggested_name') or 'a helper'}"
+ into = f" into {body.get('suggested_name') or NAME_PLACEHOLDER}"
if len(title + into) <= text.TITLE_MAX:
title += into
else:
@@ -657,13 +686,24 @@ def _refactor_unit(
file=text.basename(path),
start=start,
end=end,
- name=body.get("suggested_name") or "a helper",
+ name=body.get("suggested_name") or NAME_PLACEHOLDER,
)
if len(steps) > 1:
title += f" (+{text.plural(len(steps) - 1, 'more step')})"
dependents = deps
+ profiles = {p.get("id"): p for p in details.get("validation_profiles") or []}
+ profile = profiles.get(lead.get("validation_profile_id")) or next(
+ iter(profiles.values()), None
+ )
+ verify = _verify(profile)
fix_steps = tuple(
- _refactor_step(i + 1, s, plans.get(s.get("plan_id"))) for i, s in enumerate(steps)
+ _refactor_step(
+ i + 1,
+ s,
+ plans.get(s.get("plan_id")),
+ _step_command(profiles.get(s.get("validation_profile_id")), verify.command),
+ )
+ for i, s in enumerate(steps)
)
size_text = text.size_line(shape)
facts = [
@@ -676,10 +716,6 @@ def _refactor_unit(
nloc = files.nloc(path)
if nloc:
facts.append(FixFact("file size", f"{nloc} lines"))
- profiles = {p.get("id"): p for p in details.get("validation_profiles") or []}
- profile = profiles.get(lead.get("validation_profile_id")) or next(
- iter(profiles.values()), None
- )
plan_ids = tuple(s.get("plan_id") for s in steps if s.get("plan_id"))
return {
"title": text.clip(title),
@@ -713,7 +749,7 @@ def _refactor_unit(
f"{mechanical_n} of {text.plural(len(steps), 'step')} proven mechanical "
"by the plan",
),
- "verify": _verify(profile),
+ "verify": verify,
"context": files.context(path),
"source": FixSource(
field(row, "opportunity_id"),
@@ -893,6 +929,7 @@ def _perf_unit(
sinks = sorted({field(r, "terminal_sink") for r in rows if field(r, "terminal_sink")})
if len(sinks) > 1:
facts.append(FixFact("sinks this fix covers", str(len(sinks))))
+ verify = _verify(plan.get("validation"))
steps = tuple(
FixStep(
int(s.get("order") or i + 1),
@@ -900,6 +937,7 @@ def _perf_unit(
s.get("file_path") or path,
s.get("line") or lines.get(s.get("symbol") or ""),
s.get("applicability") == "mechanical",
+ command=_step_command(s.get("verify"), verify.command),
)
for i, s in enumerate(plan_steps)
)
@@ -938,7 +976,7 @@ def _perf_unit(
details.get("fix_rationale")
or f"{text.humanize(field(lead, 'actionability_state'))} plan",
),
- "verify": _verify(plan.get("validation")),
+ "verify": verify,
"context": files.context(path),
"source": FixSource(field(lead, "opportunity_id")),
"next_call": ActionCommand.call(
diff --git a/packages/core/src/repowise/core/analysis/health/fix_first/model.py b/packages/core/src/repowise/core/analysis/health/fix_first/model.py
index 1cb8a5f72..c9c6ef14b 100644
--- a/packages/core/src/repowise/core/analysis/health/fix_first/model.py
+++ b/packages/core/src/repowise/core/analysis/health/fix_first/model.py
@@ -106,6 +106,12 @@ class FixStep:
file_path: str
line: int | None = None
mechanical: bool = False
+ #: An Extract Method helper's header and the statement that replaces the
+ #: span, in the file's language, when the plan wrote them.
+ signature: str | None = None
+ call: str | None = None
+ #: The command that checks this step, when it differs from the item's.
+ command: str | None = None
@dataclass(frozen=True, slots=True)
@@ -155,6 +161,8 @@ class FixVerify:
tests_total: int
command: str | None
basis: FixFactBasis
+ #: What to do before the edit when no test reaches it.
+ prerequisite: str | None = None
@dataclass(frozen=True, slots=True)
@@ -210,9 +218,30 @@ class FixItem:
"gain": self.gain.text,
"effort": self.effort.bucket,
"confidence": self.confidence.level,
+ **(self._inline_plan() if self.tier in DUE_TIERS else {}),
"next_call": self.next_call.as_dict(),
}
+ def _inline_plan(self) -> dict[str, Any]:
+ """A due item's first edit and how to check it, so it can be started
+ without the lookup. ``file`` only when the step edits another file,
+ ``line`` only when it names one. ``verify`` is the item's: a step's
+ own, narrower command is on the step, in the full item."""
+ out: dict[str, Any] = {}
+ step = self.action.steps[0] if self.action.steps else None
+ if step is not None:
+ first: dict[str, Any] = {"action": step.text}
+ if step.line is not None:
+ first["line"] = step.line
+ if step.file_path != self.target.file_path:
+ first["file"] = step.file_path
+ out["first_step"] = first
+ if self.verify.command:
+ out["verify"] = {"command": self.verify.command}
+ elif self.verify.prerequisite:
+ out["verify"] = {"prerequisite": self.verify.prerequisite}
+ return out
+
def _exclusions() -> dict[str, int]:
return dict.fromkeys(FIX_EXCLUSIONS, 0)
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py b/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py
index a5dff420f..16dfaed58 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py
@@ -481,8 +481,10 @@ async def _finding_validator(
evidence=inputs.evidence,
order_tests=False,
)
- # No test found: unknown, not the bare repo-wide command a plan falls back to.
- return plan.as_dict() if plan.total else None
+ if plan.total:
+ return plan.as_dict()
+ # No test found: unknown, with only the step to take before the edit.
+ return {"prerequisite": plan.prerequisite} if plan.prerequisite else None
return validate
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py b/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py
index 0813ceedc..7b54f6838 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py
@@ -10,7 +10,7 @@ from repowise.core.analysis.health.grading import TARGET_SCORE
from repowise.core.analysis.health.grading import distribution as health_distribution
from repowise.server.mcp_server.tool_health.loading import HealthData
from repowise.server.mcp_server.tool_health.paging import Pager
-from repowise.server.mcp_server.tool_health.request import HealthRequest
+from repowise.server.mcp_server.tool_health.request import FIX_FIRST_CAP, HealthRequest
from repowise.server.mcp_server.tool_health.serialize import _serialize_finding, _serialize_metric
from repowise.server.mcp_server.tool_health.summary import _compute_kpis, _gap_analysis
from repowise.server.mcp_server.tool_health.targeted import ModeTotals
@@ -112,16 +112,23 @@ def _fix_first_block(data: HealthData, req: HealthRequest, pager: Pager) -> dict
``items_total`` is the eligible queue the items were cut from, starting at
``cursor``. Only the lead carries ``next_call``: it is the bulk of a compact
item, every item's is one ``fix_id`` call away, and without it a named page
- of 25 fits the default budget.
+ of 25 fits the default budget. A due lead carries its ``first_step`` and
+ ``verify`` on ``lead``; other due items carry theirs only on a named
+ ``fix_first`` page, within its first :data:`FIX_FIRST_CAP`, so the
+ dashboard stays near its old size.
"""
page, full = data.fix_first, data.fix_first_full
block = page.as_dict(compact=True)
- for item in block["items"]:
+ block["lead"] = full.lead.compact() if full.lead is not None else None
+ lead_id = block["lead"]["id"] if block["lead"] else None
+ for at, item in enumerate(block["items"]):
item.pop("next_call", None)
+ if not req.pages_fix_first or item["id"] == lead_id or at >= FIX_FIRST_CAP:
+ item.pop("first_step", None)
+ item.pop("verify", None)
# Zero reasons say nothing an agent reads; ``counts.excluded`` omits them too.
totals = block["totals"]
totals["excluded"] = {reason: n for reason, n in totals["excluded"].items() if n}
- block["lead"] = full.lead.compact() if full.lead is not None else None
block["counts"] = full.counts(shown=len(page.items)).as_dict()
block["items_total"] = full.totals.eligible
block["cursor"] = req.fix_first_cursor
diff --git a/packages/types/src/fix-first.ts b/packages/types/src/fix-first.ts
index 76d172fb7..d590d536c 100644
--- a/packages/types/src/fix-first.ts
+++ b/packages/types/src/fix-first.ts
@@ -69,6 +69,19 @@ export interface FixStep {
file_path: string;
line: number | null;
mechanical: boolean;
+ /** An Extract Method helper's header and the statement that replaces the span. */
+ signature?: string | null;
+ call?: string | null;
+ /** The command that checks this step, when it differs from the item's. */
+ command?: string | null;
+}
+
+/** A due item's first edit, inline in the compact projection. */
+export interface FixFirstStep {
+ action: string;
+ line?: number;
+ /** Only when the step edits a file other than the item's target. */
+ file?: string;
}
export interface FixItem {
@@ -94,6 +107,8 @@ export interface FixItem {
tests_total: number;
command: string | null;
basis: FixFactBasis;
+ /** What to do before the edit when no test reaches it. */
+ prerequisite?: string | null;
};
/** History signals: shown beside the item, never ranked on. */
context: { label: string; value: string }[];
@@ -116,6 +131,10 @@ export interface FixItemCompact {
gain: string;
effort: FixEffort;
confidence: FixLevel;
+ /** Due items only (tier `now` or `next`). */
+ first_step?: FixFirstStep;
+ /** The item's command, or the step to take first when no test reaches it. */
+ verify?: { command?: string; prerequisite?: string };
next_call: ActionCommand;
}
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 8b6696ebd..01030f9af 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -1650,6 +1650,9 @@ export interface FixStep {
file_path: string;
line?: number | null;
mechanical?: boolean;
+ signature?: string | null;
+ call?: string | null;
+ command?: string | null;
}
export interface FixTarget {
@@ -1677,6 +1680,7 @@ export interface FixVerify {
tests_total: number;
command: string | null;
basis: "measured" | "inferred" | "unknown";
+ prerequisite?: string | null;
}
/** Optional per-call provider/model overrides, as chat accepts. */
diff --git a/packages/ui/__tests__/health/fix-first.test.tsx b/packages/ui/__tests__/health/fix-first.test.tsx
index 8b0ec8002..49f7269f4 100644
--- a/packages/ui/__tests__/health/fix-first.test.tsx
+++ b/packages/ui/__tests__/health/fix-first.test.tsx
@@ -148,6 +148,38 @@ describe("Fix first items", () => {
expect(screen.getByText(/No guarding tests found/)).toBeTruthy();
});
+ it("shows a due item's first step on the closed row, and the plan's own words when open", () => {
+ const first = "No test reaches this; add a characterization test for `run` before the edit.";
+ const step = {
+ ...REFACTOR.action.steps[0]!,
+ signature: "def _<name>(repo_path):",
+ call: "info = _<name>(repo_path)",
+ command: "pytest tests/unit/cli/test_repo_scanner.py",
+ };
+ const item: FixItem = {
+ ...REFACTOR,
+ action: { ...REFACTOR.action, steps: [step] },
+ verify: { tests: [], tests_total: 0, command: null, basis: "unknown", prerequisite: first },
+ };
+ renderList({ queue: { ...FIX_FIRST_QUEUE, items: [item], lead: item } });
+ expect(screen.getByText(step.text)).toBeTruthy();
+ openRow(item);
+ // Open, the line gives way to the step itself, with what it writes and checks.
+ expect(screen.getAllByText(step.text).length).toBe(1);
+ expect(screen.getByText("New helper")).toBeTruthy();
+ expect(screen.getByText("info = _<name>(repo_path)")).toBeTruthy();
+ expect(screen.getByText(/with a name for what the lines do/)).toBeTruthy();
+ expect(screen.getByText(step.command)).toBeTruthy();
+ expect(screen.getByText(first)).toBeTruthy();
+ });
+
+ it("keeps a later item's closed row to two lines", () => {
+ const later: FixItem = { ...FINDING, tier: "later" };
+ renderList({ queue: { ...FIX_FIRST_QUEUE, items: [later], lead: later } });
+ expect(screen.queryByText("First step")).toBeNull();
+ expect(screen.queryByText(later.action.steps[0]!.text)).toBeNull();
+ });
+
it("names the plan by its unit, and offers none for a bare finding", () => {
expect(fixPlanLabel(REFACTOR)).toBe("Open the refactoring plan");
expect(fixPlanLabel(PERF)).toBe("Open the performance fix");
diff --git a/packages/ui/src/health/fix-first/fix-first-item.tsx b/packages/ui/src/health/fix-first/fix-first-item.tsx
index ce0e2de94..f16eea282 100644
--- a/packages/ui/src/health/fix-first/fix-first-item.tsx
+++ b/packages/ui/src/health/fix-first/fix-first-item.tsx
@@ -3,20 +3,23 @@
/**
* One Fix-first item: the change to make, where, why, and what it buys.
*
- * Collapsed, it is two compact lines: tier and title, then file:line and gain.
- * Expanded, it adds the why, effort, confidence and risk, then the work
- * itself: the steps in order with which ones are mechanical, how to
- * verify the change, the history around the file (muted, never ranked on), and
- * the actions. Every word and number is the payload's; this component chooses
+ * Collapsed, it is two compact lines: tier and title, then file:line and
+ * gain; a due item adds its first step. Expanded, it adds the why, effort,
+ * confidence and risk, then the work itself: the steps in order with which
+ * ones are mechanical and what each writes, how to verify the change, the
+ * history around the file (muted, never ranked on), and the actions. Every word and number is the payload's; this component chooses
* only where each one sits.
*/
import { useState, type ElementType } from "react";
import { ChevronDown } from "lucide-react";
-import type { FixItem, FixTier } from "@repowise-dev/types/fix-first";
+import type { FixItem, FixStep, FixTier } from "@repowise-dev/types/fix-first";
import type { OpportunityStatus } from "@repowise-dev/types/refactoring";
+import { getLanguageFromPath } from "../../c4/panels/CodeViewer";
+import { HighlightedCodeBlock } from "../../shared/code-block";
import { CommandLine } from "../../shared/command-line";
+import { PlaceholderHint } from "../../refactoring/placeholder-hint";
import { AiPromptButton } from "../ai-prompt-button";
import { CONFIDENCE_LABEL, EFFORT_LABEL, STATUS_LABEL } from "../labels";
import { TIER_LABEL, fixLocation, fixPlanLabel, tierReason } from "./scope";
@@ -74,6 +77,7 @@ export function FixFirstItem({
const location = fixLocation(item);
const href = fileHref?.(item.target.file_path, item.target.line_start);
const reason = tierReason(item);
+ const firstStep = item.tier !== "later" ? item.action.steps[0] : undefined;
return (
<li className="py-1.5">
@@ -122,6 +126,12 @@ export function FixFirstItem({
Gain <span className="text-[var(--color-text-secondary)]">{item.gain.text}</span>
</span>
</p>
+ {/* Open, the steps below say it in full. */}
+ {firstStep && !expanded ? (
+ <p className="mt-0.5 min-w-0 text-xs leading-4 text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">
+ First step <span className="text-[var(--color-text-secondary)]">{firstStep.text}</span>
+ </p>
+ ) : null}
{expanded ? (
<div id={panelId} className="mt-3 mb-2 flex flex-col gap-4">
@@ -224,6 +234,7 @@ function Steps({
<span className="text-[var(--color-text-tertiary)]">{where}</span>
)}
</p>
+ <StepCode step={step} />
</div>
</li>
);
@@ -238,15 +249,47 @@ function Steps({
);
}
+/** What a step writes (a helper's header, the call that replaces the span)
+ * and the command that checks it when it differs from the item's. */
+function StepCode({ step }: { step: FixStep }) {
+ const language = getLanguageFromPath(step.file_path);
+ return (
+ <>
+ {step.signature ? (
+ <HighlightedCodeBlock
+ code={step.signature}
+ language={language}
+ label="New helper"
+ compact
+ className="mb-0 mt-2"
+ />
+ ) : null}
+ {step.call ? (
+ <HighlightedCodeBlock
+ code={step.call}
+ language={language}
+ label="Call"
+ compact
+ className="mb-0 mt-2"
+ />
+ ) : null}
+ <PlaceholderHint texts={[step.signature ?? "", step.call ?? ""]} />
+ {step.command ? <CommandLine command={step.command} /> : null}
+ </>
+ );
+}
+
/** How to know the change held: the tests that guard it and the command to run them. */
export function FixVerify({ item }: { item: Pick<FixItem, "verify"> }) {
- const { tests, tests_total, command } = item.verify;
+ const { tests, tests_total, command, prerequisite } = item.verify;
return (
<section>
<h4 className={MICRO}>Verify</h4>
{tests.length === 0 ? (
<p className="mt-1.5 text-xs text-[var(--color-text-secondary)]">
- No guarding tests found. Write one that pins the current behaviour before changing it.
+ {/* The fallback covers items stored before Verify named its prerequisite. */}
+ {prerequisite ??
+ "No guarding tests found. Write one that pins the current behaviour before changing it."}
</p>
) : (
<>
diff --git a/packages/ui/src/refactoring/placeholder-hint.tsx b/packages/ui/src/refactoring/placeholder-hint.tsx
new file mode 100644
index 000000000..ea40bf466
--- /dev/null
+++ b/packages/ui/src/refactoring/placeholder-hint.tsx
@@ -0,0 +1,16 @@
+import { HELPER_NAME_PLACEHOLDER, HELPER_TYPE_PLACEHOLDER } from "./types";
+
+/** Says how to fill the `<name>` / `<type>` placeholders in a helper's
+ * header or call, when any of `texts` uses one; nothing otherwise. */
+export function PlaceholderHint({ texts }: { texts: string[] }) {
+ const used = texts.some(
+ (t) => t.includes(HELPER_NAME_PLACEHOLDER) || t.includes(HELPER_TYPE_PLACEHOLDER),
+ );
+ if (!used) return null;
+ return (
+ <p className="mt-2 text-2xs text-[var(--color-text-tertiary)]">
+ Replace {HELPER_NAME_PLACEHOLDER} with a name for what the lines do, and any{" "}
+ {HELPER_TYPE_PLACEHOLDER} with the value's type.
+ </p>
+ );
+}
diff --git a/packages/ui/src/refactoring/plan-detail.tsx b/packages/ui/src/refactoring/plan-detail.tsx
index 2cbcc7467..7188a1f9d 100644
--- a/packages/ui/src/refactoring/plan-detail.tsx
+++ b/packages/ui/src/refactoring/plan-detail.tsx
@@ -3,6 +3,7 @@
import { ArrowRight, CornerDownRight, FilePlus2, Layers, Scissors } from "lucide-react";
import { getLanguageFromPath } from "../c4/panels/CodeViewer";
import { HighlightedCodeBlock } from "../shared/code-block";
+import { PlaceholderHint } from "./placeholder-hint";
import { ProvenancePathList } from "../shared/provenance-path-list";
import {
blastFiles,
@@ -13,8 +14,6 @@ import {
extractHelperOccurrences,
extractMethodPlan,
extractMethodSignature,
- HELPER_NAME_PLACEHOLDER,
- HELPER_TYPE_PLACEHOLDER,
helperSite,
moveTarget,
performancePlanDetail,
@@ -490,14 +489,7 @@ export function PlanDetail({ plan, fileHref, hideIntro = false }: PlanDetailProp
className="mb-0 mt-2"
/>
) : null}
- {[em.signature_text, em.call_site?.new_text ?? ""].some(
- (t) => t.includes(HELPER_NAME_PLACEHOLDER) || t.includes(HELPER_TYPE_PLACEHOLDER),
- ) ? (
- <p className="mt-2 text-2xs text-[var(--color-text-tertiary)]">
- Replace {HELPER_NAME_PLACEHOLDER} with a name for what the lines do, and any{" "}
- {HELPER_TYPE_PLACEHOLDER} with the value's type.
- </p>
- ) : null}
+ <PlaceholderHint texts={[em.signature_text, em.call_site?.new_text ?? ""]} />
{em.notes.map((note) => (
<p key={note} className="mt-2 text-2xs text-[var(--color-text-tertiary)]">
{note}
diff --git a/tests/fixtures/agent_prompts/fix_items.json b/tests/fixtures/agent_prompts/fix_items.json
index 50ac0c850..d9a4e8613 100644
--- a/tests/fixtures/agent_prompts/fix_items.json
+++ b/tests/fixtures/agent_prompts/fix_items.json
@@ -135,6 +135,50 @@
},
"why_ranked": []
}
+ },
+ {
+ "name": "helper_texts_and_prerequisite",
+ "repo_name": "r",
+ "item": {
+ "id": "fix1_00000000000000000004",
+ "rank": 0,
+ "tier": "now",
+ "kind": "refactor",
+ "improves": "maintainability",
+ "title": "Extract lines 20-35 of run into <name>",
+ "target": {"file_path": "src/core.py", "symbol": "run", "line_start": 20, "line_end": 60},
+ "why": "run has many independent paths through it.",
+ "facts": [],
+ "action": {
+ "summary": "1 step, 0 mechanical",
+ "steps": [
+ {"order": 1, "text": "Extract lines 20-35 of run into <name>(rows) -> total; name it for what the lines do", "file_path": "src/core.py", "line": 20, "mechanical": false, "signature": "def _<name>(rows):", "call": "total = _<name>(rows)", "command": "pytest tests/test_core.py"}
+ ],
+ "steps_total": 1,
+ "mechanical": false
+ },
+ "gain": {"kind": "health_points", "value": 1.0, "text": "+1.0 health on this file"},
+ "effort": {"bucket": "S", "basis": "sized by the stored plan"},
+ "risk": {"level": "low", "dependents": null, "files_touched": 1, "text": "Touches 1 file."},
+ "confidence": {"level": "medium", "reason": "0 of 1 step proven mechanical by the plan"},
+ "verify": {
+ "tests": [],
+ "tests_total": 0,
+ "command": null,
+ "basis": "unknown",
+ "prerequisite": "No test reaches this; add a characterization test for `run` before the edit."
+ },
+ "context": [],
+ "source": {"opportunity_id": "refop2_core", "plan_ids": [], "finding_ids": []},
+ "next_call": {
+ "purpose": "The full plan",
+ "mcp": "get_health()",
+ "cli": null,
+ "tool": "get_health",
+ "arguments": {}
+ },
+ "why_ranked": []
+ }
}
]
}
diff --git a/tests/fixtures/agent_prompts/golden.json b/tests/fixtures/agent_prompts/golden.json
index acf4e0e98..239b5bc4e 100644
--- a/tests/fixtures/agent_prompts/golden.json
+++ b/tests/fixtures/agent_prompts/golden.json
@@ -43,12 +43,19 @@
"claude-code": "You are Claude Code in this repository. Repowise, a code-intelligence index, ranked the change below first among the work it found. Confirm each fact with Read and Grep before editing, and track the steps with TodoWrite.\n## Fix first (`r`)\n**Break up GraphFlow (CCN 260, 1,094 lines)**\nGraphFlow: CCN 260, 1,094 lines, nests 7 deep.\n## Facts\n- Target: `packages/ui/src/graph/graph-flow.tsx:198` (`GraphFlow`)\n- Gain: +0.4 health on this file\n- Effort: XL (1,094 lines)\n- Risk: Touches 1 file; 4 files import it.\n- Confidence: low. no plan proves the steps\n- finding: nested_complexity\n## Steps, in order\n1. Flatten the control flow. (`packages/ui/src/graph/graph-flow.tsx:198`) [judgment]\n## Verify\n- `packages/ui/__tests__/graph-flow.test.tsx`: imports the file\n## Hard constraints\n- **Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.\n- **Keep behaviour.** This is a structural or performance change; what the code returns must not change.\n- **Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.\n- **Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.\n## What I expect back\n1. Whether the problem held, and what you changed.\n2. The Verify run, before and after, with its result.\n3. Anything you left undone, and why.",
"claude-code-mcp": "You are Claude Code in this repository, which Repowise indexes and serves over 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.\n## Fix first (`r`)\n**Break up GraphFlow (CCN 260, 1,094 lines)**\nGraphFlow: CCN 260, 1,094 lines, nests 7 deep.\n## Facts\n- Target: `packages/ui/src/graph/graph-flow.tsx:198` (`GraphFlow`)\n- Gain: +0.4 health on this file\n- Effort: XL (1,094 lines)\n- Risk: Touches 1 file; 4 files import it.\n- Confidence: low. no plan proves the steps\n- finding: nested_complexity\n## Steps, in order\n1. Flatten the control flow. (`packages/ui/src/graph/graph-flow.tsx:198`) [judgment]\n## Verify\n- `packages/ui/__tests__/graph-flow.test.tsx`: imports the file\n## Look closer (Repowise MCP)\n`get_health()`\n## Hard constraints\n- **Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.\n- **Keep behaviour.** This is a structural or performance change; what the code returns must not change.\n- **Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.\n- **Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.\n## What I expect back\n1. Whether the problem held, and what you changed.\n2. The Verify run, before and after, with its result.\n3. Anything you left undone, and why.",
"cursor": "Work in this repository. Repowise, a code-intelligence index, ranked the change below first among the work it found. Open the target with @file, confirm each fact, then make the change.\n## Fix first (`r`)\n**Break up GraphFlow (CCN 260, 1,094 lines)**\nGraphFlow: CCN 260, 1,094 lines, nests 7 deep.\n## Facts\n- Target: `packages/ui/src/graph/graph-flow.tsx:198` (`GraphFlow`)\n- Gain: +0.4 health on this file\n- Effort: XL (1,094 lines)\n- Risk: Touches 1 file; 4 files import it.\n- Confidence: low. no plan proves the steps\n- finding: nested_complexity\n## Steps, in order\n1. Flatten the control flow. (`packages/ui/src/graph/graph-flow.tsx:198`) [judgment]\n## Verify\n- `packages/ui/__tests__/graph-flow.test.tsx`: imports the file\n## Hard constraints\n- **Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.\n- **Keep behaviour.** This is a structural or performance change; what the code returns must not change.\n- **Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.\n- **Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.\n## What I expect back\n1. Whether the problem held, and what you changed.\n2. The Verify run, before and after, with its result.\n3. Anything you left undone, and why."
+ },
+ "helper_texts_and_prerequisite": {
+ "generic": "You are a senior engineer in this repository. Repowise, a code-intelligence index, ranked the change below first among the work it found. Its facts come from stored analysis; treat them as leads to confirm against the code, not as ground truth.\n## Fix first (`r`)\n**Extract lines 20-35 of run into <name>**\nrun has many independent paths through it.\n## Facts\n- Target: `src/core.py:20` (`run`)\n- Gain: +1.0 health on this file\n- Effort: S (sized by the stored plan)\n- Risk: Touches 1 file.\n- Confidence: medium. 0 of 1 step proven mechanical by the plan\n## Steps, in order\n1. Extract lines 20-35 of run into <name>(rows) -> total; name it for what the lines do (`src/core.py:20`) [judgment]\n Helper: `def _<name>(rows):`\n Call: `total = _<name>(rows)`\n Check: `pytest tests/test_core.py`\n## Verify\nNo test reaches this; add a characterization test for `run` before the edit.\n## Hard constraints\n- **Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.\n- **Keep behaviour.** This is a structural or performance change; what the code returns must not change.\n- **Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.\n- **Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.\n## What I expect back\n1. Whether the problem held, and what you changed.\n2. The Verify run, before and after, with its result.\n3. Anything you left undone, and why.",
+ "claude-code": "You are Claude Code in this repository. Repowise, a code-intelligence index, ranked the change below first among the work it found. Confirm each fact with Read and Grep before editing, and track the steps with TodoWrite.\n## Fix first (`r`)\n**Extract lines 20-35 of run into <name>**\nrun has many independent paths through it.\n## Facts\n- Target: `src/core.py:20` (`run`)\n- Gain: +1.0 health on this file\n- Effort: S (sized by the stored plan)\n- Risk: Touches 1 file.\n- Confidence: medium. 0 of 1 step proven mechanical by the plan\n## Steps, in order\n1. Extract lines 20-35 of run into <name>(rows) -> total; name it for what the lines do (`src/core.py:20`) [judgment]\n Helper: `def _<name>(rows):`\n Call: `total = _<name>(rows)`\n Check: `pytest tests/test_core.py`\n## Verify\nNo test reaches this; add a characterization test for `run` before the edit.\n## Hard constraints\n- **Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.\n- **Keep behaviour.** This is a structural or performance change; what the code returns must not change.\n- **Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.\n- **Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.\n## What I expect back\n1. Whether the problem held, and what you changed.\n2. The Verify run, before and after, with its result.\n3. Anything you left undone, and why.",
+ "claude-code-mcp": "You are Claude Code in this repository, which Repowise indexes and serves over 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.\n## Fix first (`r`)\n**Extract lines 20-35 of run into <name>**\nrun has many independent paths through it.\n## Facts\n- Target: `src/core.py:20` (`run`)\n- Gain: +1.0 health on this file\n- Effort: S (sized by the stored plan)\n- Risk: Touches 1 file.\n- Confidence: medium. 0 of 1 step proven mechanical by the plan\n## Steps, in order\n1. Extract lines 20-35 of run into <name>(rows) -> total; name it for what the lines do (`src/core.py:20`) [judgment]\n Helper: `def _<name>(rows):`\n Call: `total = _<name>(rows)`\n Check: `pytest tests/test_core.py`\n## Verify\nNo test reaches this; add a characterization test for `run` before the edit.\n## Look closer (Repowise MCP)\n`get_health()`\n## Hard constraints\n- **Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.\n- **Keep behaviour.** This is a structural or performance change; what the code returns must not change.\n- **Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.\n- **Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.\n## What I expect back\n1. Whether the problem held, and what you changed.\n2. The Verify run, before and after, with its result.\n3. Anything you left undone, and why.",
+ "cursor": "Work in this repository. Repowise, a code-intelligence index, ranked the change below first among the work it found. Open the target with @file, confirm each fact, then make the change.\n## Fix first (`r`)\n**Extract lines 20-35 of run into <name>**\nrun has many independent paths through it.\n## Facts\n- Target: `src/core.py:20` (`run`)\n- Gain: +1.0 health on this file\n- Effort: S (sized by the stored plan)\n- Risk: Touches 1 file.\n- Confidence: medium. 0 of 1 step proven mechanical by the plan\n## Steps, in order\n1. Extract lines 20-35 of run into <name>(rows) -> total; name it for what the lines do (`src/core.py:20`) [judgment]\n Helper: `def _<name>(rows):`\n Call: `total = _<name>(rows)`\n Check: `pytest tests/test_core.py`\n## Verify\nNo test reaches this; add a characterization test for `run` before the edit.\n## Hard constraints\n- **Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.\n- **Keep behaviour.** This is a structural or performance change; what the code returns must not change.\n- **Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.\n- **Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.\n## What I expect back\n1. Whether the problem held, and what you changed.\n2. The Verify run, before and after, with its result.\n3. Anything you left undone, and why."
}
},
"verify": {
"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"
+ "exact_no_command_empty_args": "- `packages/ui/__tests__/graph-flow.test.tsx`: imports the file",
+ "helper_texts_and_prerequisite": "No test reaches this; add a characterization test for `run` before the edit."
},
"refactoring_plan": {
"extract_method_typed": {
diff --git a/tests/unit/health/test_fix_first_build.py b/tests/unit/health/test_fix_first_build.py
index a72b99d06..024a95a86 100644
--- a/tests/unit/health/test_fix_first_build.py
+++ b/tests/unit/health/test_fix_first_build.py
@@ -281,3 +281,90 @@ def test_fix_first_counts_only_in_its_own_reasons() -> None:
def _step_kind(kind: str) -> dict:
return {"plan_id": "refac2_mv", "refactoring_type": kind, "target_symbol": "src/move.py::run",
"file_path": "src/move.py", "line_start": 5}
+
+
+def test_a_due_item_carries_its_first_step_and_verify_inline() -> None:
+ by_kind = {i.kind: i for i in _build().items}
+ refactor, perf, finding = by_kind["refactor"], by_kind["perf_fix"], by_kind["finding"]
+ assert refactor.compact()["first_step"] == {
+ "action": "Extract lines 20-35 of run into sum_rows(rows, limit) -> total",
+ "line": 20,
+ }
+ assert refactor.compact()["verify"] == {"command": "pytest tests/test_core_0.py"}
+ assert perf.compact()["first_step"] == {
+ "action": "Collect the keys before the loop (load_all)",
+ "line": 12,
+ }
+ assert "verify" not in perf.compact() # the plan names no command
+ # A later item is a list row only; its plan is one lookup away.
+ assert finding.tier == "later"
+ assert not {"first_step", "verify"} & set(finding.compact())
+
+
+def test_a_step_names_its_own_command_only_when_it_differs() -> None:
+ perf = _perf("perf2_a", "s")
+ perf["details"]["plan"] = {
+ **perf["details"]["plan"],
+ "validation": {"basis": "inferred", "total": 2, "tests": ["tests/test_a.py"],
+ "commands": ["pytest tests/test_a.py"]},
+ "steps": [
+ {"order": 1, "action": "Collect the keys before the loop", "file_path": "src/repo.py",
+ "line": 12, "applicability": "judgment",
+ "verify": {"commands": ["pytest tests/test_b.py"], "tests": ["tests/test_b.py"],
+ "coverage": "inferred"}},
+ {"order": 2, "action": "Fetch them in one call", "file_path": "src/repo.py",
+ "line": 14, "applicability": "judgment"},
+ ],
+ }
+ item = next(i for i in _build(performance=[perf]).items if i.kind == "perf_fix")
+ assert item.verify.command == "pytest tests/test_a.py"
+ assert [s.command for s in item.action.steps] == ["pytest tests/test_b.py", None]
+ # Inline, the item's command: a step's own, narrower one stays on the step.
+ assert item.compact()["verify"] == {"command": "pytest tests/test_a.py"}
+
+
+def test_an_extract_method_step_carries_the_helper_header_and_call() -> None:
+ plans = copy.deepcopy(PLANS)
+ plans[0]["plan"]["new_symbol"] = {"signature_text": "def _sum_rows(rows, limit):"}
+ plans[0]["plan"]["call_site"] = {"replace_span": {"start": 20, "end": 35},
+ "new_text": "total = _sum_rows(rows, limit)"}
+ core = next(i for i in _build(plans=plans).items if i.kind == "refactor")
+ first, second = core.action.steps
+ assert (first.signature, first.call) == ("def _sum_rows(rows, limit):",
+ "total = _sum_rows(rows, limit)")
+ assert (second.signature, second.call) == (None, None)
+ # The header is on the step, in the full item; the compact row names the edit only.
+ assert set(core.compact()["first_step"]) == {"action", "line"}
+ # A finding with no plan of its own takes the same texts from the span it starts at.
+ plans[0].update(file_path="src/core.py", target_symbol="src/core.py::run")
+ lone = _build(plans=plans, refactoring=[], performance=[]).lead
+ assert lone.action.steps[0].signature == "def _sum_rows(rows, limit):"
+
+
+def test_an_unnamed_helper_reads_as_the_placeholder_in_titles() -> None:
+ plans = copy.deepcopy(PLANS)
+ del plans[0]["plan"]["suggested_name"]
+ core = next(i for i in _build(plans=plans).items if i.kind == "refactor")
+ assert core.title == "Start breaking up run (CCN 44, 50 lines): first lift lines 20-35 into <name>"
+ small = [{**FINDINGS[1], "details": {"ccn": 12, "nloc": 50}}]
+ row = copy.deepcopy(REFACTORING[0])
+ row["details"]["steps"] = row["details"]["steps"][:1]
+ core = next(i for i in _build(plans=plans, findings=small, refactoring=[row]).items
+ if i.kind == "refactor")
+ assert core.title == "Extract lines 20-35 of run into <name>"
+
+
+def test_an_item_no_test_reaches_says_to_pin_its_behaviour_first() -> None:
+ first = "No test reaches this; add a characterization test for `run` before the edit."
+ row = copy.deepcopy(REFACTORING[0])
+ row["details"]["validation_profiles"] = [
+ {"id": "validation_1", "basis": "unknown", "total": 0, "tests": [], "commands": [],
+ "prerequisite": first}
+ ]
+ core = next(i for i in _build(refactoring=[row]).items if i.kind == "refactor")
+ assert (core.verify.tests, core.verify.command, core.verify.prerequisite) == ((), None, first)
+ assert core.compact()["verify"] == {"prerequisite": first}
+ # A finding the validate callback found no test for takes the same step.
+ queue = _build(validate=lambda *_: {"prerequisite": first})
+ walk = next(i for i in queue.items if i.target.file_path == "src/plain.py")
+ assert (walk.verify.basis, walk.verify.prerequisite) == ("unknown", first)
diff --git a/tests/unit/persistence/test_fix_first_loader.py b/tests/unit/persistence/test_fix_first_loader.py
index a7bebc0d5..4d15aaa94 100644
--- a/tests/unit/persistence/test_fix_first_loader.py
+++ b/tests/unit/persistence/test_fix_first_loader.py
@@ -20,6 +20,15 @@ from tests.unit.health.fix_first_rows import FINDINGS, METRICS, PERFORMANCE, PLA
from tests.unit.persistence.helpers import insert_repo
+def no_tests(path, function, start, end) -> dict:
+ """What the loader's test lookup answers for a finding no seeded test reaches."""
+ return {
+ "prerequisite": (
+ f"No test reaches this; add a characterization test for `{function}` before the edit."
+ )
+ }
+
+
def _with_json(row: dict, name: str) -> dict:
out = {k: v for k, v in row.items() if k != name}
out[f"{name}_json"] = json.dumps(row.get(name) or {})
@@ -77,6 +86,7 @@ async def test_loader_matches_the_builder_over_rows(async_session) -> None:
refactoring=REFACTORING,
performance=PERFORMANCE,
plans=PLANS,
+ validate=no_tests,
)
assert loaded == built
# The seed exercises every kind, so equality is not over an empty queue.
@@ -130,6 +140,7 @@ async def test_loader_reads_the_stored_code_origin(async_session) -> None:
refactoring=REFACTORING,
performance=PERFORMANCE,
plans=PLANS,
+ validate=no_tests,
)
assert loaded.totals.excluded["docs_example"] == 1
# The update moved the metric's ``updated_at``, so only the basis differs.
@@ -180,6 +191,7 @@ async def test_loader_reads_verified_duplicates_as_a_fact(async_session) -> None
refactoring=REFACTORING,
performance=PERFORMANCE,
plans=[*PLANS, helper],
+ validate=no_tests,
)
loaded = await load_fix_first(async_session, rid)
assert "src/core.py" in {i.target.file_path for i in loaded.items}
@@ -218,6 +230,7 @@ async def test_loader_reads_extractions_for_a_finding_without_a_plan(async_sessi
refactoring=REFACTORING,
performance=PERFORMANCE,
plans=[*PLANS, extraction],
+ validate=no_tests,
)
assert (loaded.items, loaded.totals) == (built.items, built.totals)
@@ -237,7 +250,7 @@ async def test_every_limit_and_id_is_a_slice_of_one_build(async_session, monkeyp
monkeypatch.setattr(loader, "_build", counting)
loader.clear_fix_first_cache()
rows = {"metrics": METRICS, "findings": FINDINGS, "refactoring": REFACTORING,
- "performance": PERFORMANCE, "plans": PLANS}
+ "performance": PERFORMANCE, "plans": PLANS, "validate": no_tests}
full = await load_fix_first(async_session, rid, limit=None)
assert full == build_fix_first(**rows, limit=None)
@@ -283,7 +296,11 @@ async def test_a_finding_item_with_no_tests_stays_unknown(async_session) -> None
rid = await seed_fix_first(async_session)
loaded = await load_fix_first(async_session, rid)
walk = next(i for i in loaded.items if i.target.file_path == "src/plain.py")
- assert (walk.verify.tests, walk.verify.basis) == ((), "unknown")
+ assert (walk.verify.tests, walk.verify.basis, walk.verify.command) == ((), "unknown", None)
+ # The step to take before the edit, since no test pins today's behaviour.
+ assert walk.verify.prerequisite == (
+ "No test reaches this; add a characterization test for `walk` before the edit."
+ )
async def test_loader_counts_dormant_causes_and_dead_code(async_session) -> None:
@@ -344,7 +361,8 @@ async def test_an_unverified_read_skips_the_test_lookup(async_session, monkeypat
assert calls == 0
assert [i.id for i in bare.items] == [i.id for i in (await load_fix_first(async_session, rid)).items]
assert calls == 1
- assert (await load_fix_first(async_session, rid, limit=None, verify=False)).items == (
- await load_fix_first(async_session, rid, limit=None)
- ).items
+ unverified = await load_fix_first(async_session, rid, limit=None, verify=False)
+ assert [i.id for i in unverified.items] == [
+ i.id for i in (await load_fix_first(async_session, rid, limit=None)).items
+ ]
assert calls == 1
diff --git a/tests/unit/persistence/test_read_snapshots.py b/tests/unit/persistence/test_read_snapshots.py
index c03fa8c7f..d7e193c3a 100644
--- a/tests/unit/persistence/test_read_snapshots.py
+++ b/tests/unit/persistence/test_read_snapshots.py
@@ -252,6 +252,22 @@ def test_decode_inverts_asdict_over_every_item_kind() -> None:
assert decode_or_none(FixFirstQueue, stored) == queue
+def test_a_queue_stored_before_steps_had_code_still_decodes() -> None:
+ """A snapshot written before steps carried their helper texts and command,
+ and Verify its prerequisite, reads those as absent until it is rewritten."""
+ queue = build_fix_first(metrics=METRICS, findings=FINDINGS, refactoring=REFACTORING,
+ performance=PERFORMANCE, plans=PLANS, limit=None)
+ stored = json.loads(json.dumps(asdict(queue)))
+ for item in stored["items"]:
+ del item["verify"]["prerequisite"]
+ for step in item["action"]["steps"]:
+ for key in ("signature", "call", "command"):
+ del step[key]
+ decoded = decode_or_none(FixFirstQueue, stored)
+ assert decoded is not None and [i.id for i in decoded.items] == [i.id for i in queue.items]
+ assert all(s.command is None for i in decoded.items for s in i.action.steps)
+
+
@dataclass(frozen=True)
class Leaf:
n: int
diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.py
index 8b5241c6c..0475b7238 100644
--- a/tests/unit/server/mcp/test_health.py
+++ b/tests/unit/server/mcp/test_health.py
@@ -1603,6 +1603,54 @@ async def test_fix_first_named_page_honours_limit_and_cursor(setup_mcp, health_d
assert second["lead"] == block["lead"] == dashboard["lead"]
+async def test_due_items_carry_their_first_step_once_and_only_in_the_head(
+ setup_mcp, health_data, monkeypatch
+):
+ """The dashboard inlines a due lead's first step and verify on ``lead``
+ only; a named page inlines them on its first five other due items and
+ leaves the rest to ``fix_id``."""
+ from dataclasses import replace
+
+ from repowise.core.analysis.health.fix_first.model import FixStep
+ from repowise.server.mcp_server import get_health
+ from repowise.server.mcp_server.tool_health import loading
+
+ real = loading.load_fix_first
+
+ async def due(session, repository_id, **kwargs):
+ queue = await real(session, repository_id, **kwargs)
+ head = queue.items[0]
+ step = FixStep(1, "Extract lines 5-9 of run into _load(path)", "src/other.py", 5)
+ items = tuple(
+ replace(
+ head,
+ id=f"fix1_{index:020d}",
+ rank=index,
+ tier="next",
+ action=replace(head.action, steps=(step,)),
+ verify=replace(head.verify, command="pytest tests/test_run.py"),
+ )
+ for index in range(8)
+ )
+ return replace(queue, items=items, totals=replace(queue.totals, eligible=8, shown=8))
+
+ monkeypatch.setattr(loading, "load_fix_first", due)
+
+ block = (await get_health())["fix_first"]
+ assert block["lead"]["first_step"] == {
+ "action": "Extract lines 5-9 of run into _load(path)",
+ "line": 5,
+ "file": "src/other.py",
+ }
+ assert block["lead"]["verify"] == {"command": "pytest tests/test_run.py"}
+ assert not any({"first_step", "verify"} & set(item) for item in block["items"])
+ default = (await get_health(only=["fix_first"]))["fix_first"]["items"]
+ assert [("verify" in item) for item in default] == [False, *[True] * 4]
+ page = (await get_health(only=["fix_first"], limit=25))["fix_first"]["items"]
+ assert [("first_step" in item) for item in page] == [False, *[True] * 4, *[False] * 3]
+
+
@pytest.mark.asyncio
async def test_fix_first_page_grows_only_when_limit_is_passed(
setup_mcp, health_data, monkeypatch