Skip to content

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

feat(refactoring): record what happened to a plan that stops being detected (#3391)

Raghav Chamadiyaf3252bc77737
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.md
index 8e55596f3..7b93fd7f9 100644
--- a/docs/layers/REFACTORING.md
+++ b/docs/layers/REFACTORING.md
@@ -107,6 +107,14 @@ on the same lines. A governed plan's steps are `judgment`, and its
`blast_radius.co_change_partners` names the files that usually change with it.
A newly accepted decision shows here after the next index or update.
+A plan the index stops detecting is resolved, and its detail then carries a
+`payoff` with the target's size before and after and the commit that resolved
+it. `applied` means the measures are consistent with the plan being applied: the
+target lost at least half the predicted complexity and a function the size of
+the extracted span appeared beside it (Extract Method only, so far). The other
+outcomes are `file_deleted`, `superseded` (the same plan found again under a new
+id), `target_changed` (renamed or rewritten another way) and `unknown`.
+
Break Cycle is advisory. Its plan names edges to cut, not which symbols cross
them or how to move them, so an opportunity carries it as `evidence` rather than
as a numbered step: it never leads, and never reaches Fix first. The plan itself
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index 6d73e1fae..d3d43ca77 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -377,7 +377,7 @@ Provisional finding types appear only with `include=["unverified"]`, each marked
`get_health(opportunity_id="refop...")` returns full steps, member plans, the validation profile and `next_actions`; `only=["refactoring_evidence"]` with `cursor` pages the evidence. `found` says whether the id matched; `status` is `open`, `acknowledged`, `resolved` or `false_positive`. `refactoring_summary` rolls up by type, effort, confidence and lifecycle.
-`refactoring_plans`, returned only when named in `only`, lists the plans of the refactoring queue in queue order: each opportunity's steps together, in step order, under the same `refactoring_scope`, filters and view as `refactoring_opportunities`, up to 25 per page. A row is compact: `id` (for `plan_id` and `generate_refactoring_code`), `refactoring_type`, `file_path`, `target_symbol`, `line_start`, `line_end`, `effort_bucket`, `confidence`, `impact_delta`, `source_biomarker`, `opportunity_id`, `classification` (`mechanical` or `judgment`) and `relocated_by` when set; `get_health(plan_id=...)` returns the plan in full (detector detail such as cohesion `groups` or `cut_edges`, `evidence`, `blast_radius`, validation). `refactoring_plans_total` counts plans in scope, `refactoring_plans_opportunities_total` the opportunities they are steps of, `refactoring_plans_scope` names the scope and `refactoring_plans_hidden` counts what the `fix_first` scope leaves out, by reason. Performance plans are listed by `performance_opportunities`. An empty requested list has `refactoring_plans_status.reason`: `no_applicable_findings`, `plan_analysis_indeterminate`, `no_eligible_targets` or `analysis_unavailable`. See [REFACTORING.md](../layers/REFACTORING.md).
+`refactoring_plans`, returned only when named in `only`, lists the plans of the refactoring queue in queue order: each opportunity's steps together, in step order, under the same `refactoring_scope`, filters and view as `refactoring_opportunities`, up to 25 per page. A row is compact: `id` (for `plan_id` and `generate_refactoring_code`), `refactoring_type`, `file_path`, `target_symbol`, `line_start`, `line_end`, `effort_bucket`, `confidence`, `impact_delta`, `source_biomarker`, `opportunity_id`, `classification` (`mechanical` or `judgment`) and `relocated_by` when set; `get_health(plan_id=...)` returns the plan in full (detector detail such as cohesion `groups` or `cut_edges`, `evidence`, `blast_radius`, validation), and for a plan the index resolved, its `payoff`. `refactoring_plans_total` counts plans in scope, `refactoring_plans_opportunities_total` the opportunities they are steps of, `refactoring_plans_scope` names the scope and `refactoring_plans_hidden` counts what the `fix_first` scope leaves out, by reason. Performance plans are listed by `performance_opportunities`. An empty requested list has `refactoring_plans_status.reason`: `no_applicable_findings`, `plan_analysis_indeterminate`, `no_eligible_targets` or `analysis_unavailable`. See [REFACTORING.md](../layers/REFACTORING.md).
### Performance
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
index 9f5d6a82d..c479f70e8 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -1548,7 +1548,11 @@ async def _rescore_health_from_db(
# this pass just scored the working tree, and the stored column is
# written by a different step whose ordering is not guaranteed.
await save_full_health_report(
- session, repo_id, report, analyzed_commit=get_head_commit(Path(repo_path))
+ session,
+ repo_id,
+ report,
+ analyzed_commit=get_head_commit(Path(repo_path)),
+ repo_path=repo_path,
)
# That writer replaced every open finding, the governance ones too,
# and only the governance pass produces those.
diff --git a/packages/core/alembic/versions/0105_refactoring_payoffs.py b/packages/core/alembic/versions/0105_refactoring_payoffs.py
new file mode 100644
index 000000000..c17b912c9
--- /dev/null
+++ b/packages/core/alembic/versions/0105_refactoring_payoffs.py
@@ -0,0 +1,71 @@
+"""Add per-function size measures to ``function_facts`` and the ``refactoring_payoffs`` table.
+
+``function_facts`` gains CCN, code lines, parameter count and deepest nesting
+from the complexity walk. ``refactoring_payoffs`` records, for a plan the writer
+resolved as no longer detected, whether it was applied, its file deleted or
+its target changed, with the target's measures before and after.
+
+Local SQLite stores get both from ``init_db``; this migration covers managed
+Postgres. Values appear on the next analysis.
+
+Revision ID: 0105
+Revises: 0104
+Create Date: 2026-10-11
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0105"
+down_revision: str | None = "0104"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+_FACT_COLUMNS = ("ccn", "nloc", "params", "max_nesting")
+
+
+def upgrade() -> None:
+ for name in _FACT_COLUMNS:
+ op.add_column("function_facts", sa.Column(name, sa.Integer(), nullable=True))
+ op.create_table(
+ "refactoring_payoffs",
+ sa.Column(
+ "suggestion_id",
+ sa.String(32),
+ sa.ForeignKey("refactoring_suggestions.id", ondelete="CASCADE"),
+ primary_key=True,
+ ),
+ sa.Column(
+ "repository_id",
+ sa.String(32),
+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),
+ nullable=False,
+ ),
+ sa.Column("outcome", sa.String(16), nullable=False),
+ sa.Column("resolved_commit", sa.String(64), nullable=True),
+ sa.Column("resolved_at", sa.DateTime(timezone=True), nullable=False),
+ sa.Column("before_ccn", sa.Integer(), nullable=True),
+ sa.Column("before_nloc", sa.Integer(), nullable=True),
+ sa.Column("before_params", sa.Integer(), nullable=True),
+ sa.Column("after_ccn", sa.Integer(), nullable=True),
+ sa.Column("after_nloc", sa.Integer(), nullable=True),
+ sa.Column("after_params", sa.Integer(), nullable=True),
+ sa.Column("new_symbol", sa.Text(), nullable=True),
+ )
+ op.create_index(
+ "ix_refactoring_payoffs_repo_outcome",
+ "refactoring_payoffs",
+ ["repository_id", "outcome"],
+ )
+
+
+def downgrade() -> None:
+ op.drop_index("ix_refactoring_payoffs_repo_outcome", table_name="refactoring_payoffs")
+ op.drop_table("refactoring_payoffs")
+ for name in reversed(_FACT_COLUMNS):
+ op.drop_column("function_facts", name)
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/models.py b/packages/core/src/repowise/core/analysis/health/complexity/models.py
index f2b6c0ee3..b0da16b3c 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py
@@ -140,6 +140,19 @@ class FunctionComplexity:
if self.assertion_blocks is None:
self.assertion_blocks = []
+ def stored_metrics(self) -> dict[str, int | None]:
+ """The size measures the ``function_facts`` store keeps for this function.
+
+ ``params`` is ``None`` for 0: the walk counts 0 both for no parameters
+ and for a list it could not find, and the store keeps unknown as NULL.
+ """
+ return {
+ "ccn": self.ccn,
+ "nloc": self.nloc,
+ "params": self.param_count or None,
+ "max_nesting": self.max_nesting,
+ }
+
@dataclass
class CohesionGroup:
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 9e154c243..8dc2633fa 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -1425,6 +1425,7 @@ class HealthAnalyzer:
facts.receiver_assigns is not None if facts else None
),
"early_exits": facts.early_exits if facts else None,
+ **fc.stored_metrics(),
}
)
return rows
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/payoff.py b/packages/core/src/repowise/core/analysis/health/refactoring/payoff.py
new file mode 100644
index 000000000..6e12cf9c3
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/payoff.py
@@ -0,0 +1,163 @@
+"""What happened to a plan that stopped being detected.
+
+The writer resolves a plan nobody detects any more as ``no_longer_detected``,
+which on its own conflates a plan someone applied with a file that was deleted,
+a function that was rewritten another way, and an edit that moved the plan's
+span so it is detected again under a new id. :func:`classify_payoff` tells
+them apart from the target function's stored measures before and after the
+resolving run, read off ``function_facts`` rather than measured again.
+
+Only Extract Method is judged as applied so far: its target is one function
+and its prediction (decision points and code lines moved out) is a measure the
+store keeps. Other kinds get ``file_deleted``, ``superseded`` or ``unknown``.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Iterable, Mapping
+from dataclasses import dataclass
+from typing import Any
+
+from ...execution_graph import file_of_symbol
+
+# Wire vocabulary, mirrored in ``packages/types/src/refactoring.ts``.
+APPLIED = "applied"
+FILE_DELETED = "file_deleted"
+SUPERSEDED = "superseded"
+TARGET_CHANGED = "target_changed"
+UNKNOWN = "unknown"
+PAYOFF_OUTCOMES = (APPLIED, FILE_DELETED, SUPERSEDED, TARGET_CHANGED, UNKNOWN)
+
+_JUDGED_TYPES = frozenset({"extract_method"})
+# A helper the plan produced holds about the slice: its code lines plus a
+# signature and a return, or somewhat less when the edit tidied the span.
+_HELPER_MIN_SHARE = 0.5
+_HELPER_MAX_SHARE = 2.0
+_HELPER_SLACK_LINES = 3
+
+
+@dataclass(frozen=True)
+class FunctionMeasures:
+ """One function's stored size measures; ``None`` is unknown, never 0."""
+
+ symbol_id: str
+ ccn: int | None = None
+ nloc: int | None = None
+ params: int | None = None
+
+
+@dataclass(frozen=True)
+class Payoff:
+ outcome: str
+ before: FunctionMeasures | None = None
+ after: FunctionMeasures | None = None
+ new_symbol: str | None = None
+
+
+def measures_by_file(
+ rows: Iterable[Mapping[str, Any]],
+) -> dict[str, dict[str, FunctionMeasures]]:
+ """``function_facts``-shaped rows as each file's functions by symbol id."""
+ out: dict[str, dict[str, FunctionMeasures]] = {}
+ for row in rows:
+ symbol = row["symbol_id"]
+ out.setdefault(file_of_symbol(symbol), {})[symbol] = FunctionMeasures(
+ symbol, row.get("ccn"), row.get("nloc"), row.get("params")
+ )
+ return out
+
+
+def target_symbol(
+ functions: Mapping[str, FunctionMeasures], name: str
+) -> FunctionMeasures | None:
+ """The one function in a file's *functions* named *name*, or ``None``.
+
+ Symbol ids are ``path::Outer::name``; two functions sharing a last name
+ (methods of two classes) are ambiguous and answer ``None``.
+ """
+ hits = [m for sid, m in functions.items() if sid.rsplit("::", 1)[-1] == name]
+ return hits[0] if len(hits) == 1 else None
+
+
+def classify_payoff(
+ *,
+ refactoring_type: str,
+ target: str,
+ evidence: Mapping[str, Any],
+ file_live: bool | None,
+ before: Mapping[str, FunctionMeasures],
+ after: Mapping[str, FunctionMeasures],
+ suggested_name: str | None = None,
+ redetected: bool = False,
+) -> Payoff:
+ """Classify one resolved plan.
+
+ *before* and *after* are the target file's functions by symbol id as the
+ store held them before the resolving run and as that run measured them.
+ *file_live* is ``False`` only when the file is gone from disk and git, and
+ ``None`` when nobody could tell. *redetected* says the run emitted a plan
+ of the same kind on the same target under a new id: short of applied, that
+ plan was superseded rather than gone.
+ """
+ was = target_symbol(before, target)
+ if file_live is False:
+ return Payoff(FILE_DELETED, before=was)
+ fallback = SUPERSEDED if redetected else UNKNOWN
+ if refactoring_type not in _JUDGED_TYPES or not after:
+ # No measures after the run (an excluded or unscored file, or a run
+ # with no graph to key them on) say nothing about the target.
+ return Payoff(fallback, before=was)
+ now = target_symbol(after, target)
+ if now is None:
+ # Renamed, removed or split past recognition while the file stayed.
+ return Payoff(TARGET_CHANGED if was is not None else fallback, before=was)
+ helper = _helper(before, after, suggested_name, evidence.get("slice_nloc"))
+ outcome = _measured_outcome(was, now, evidence.get("ccn_removed"), helper is not None)
+ if outcome != APPLIED and redetected:
+ outcome = SUPERSEDED
+ return Payoff(outcome, before=was, after=now, new_symbol=helper)
+
+
+def _fits_slice(nloc: int | None, slice_nloc: Any) -> bool:
+ if nloc is None or not isinstance(slice_nloc, int | float) or slice_nloc <= 0:
+ return False
+ high = _HELPER_MAX_SHARE * slice_nloc + _HELPER_SLACK_LINES
+ return _HELPER_MIN_SHARE * slice_nloc <= nloc <= high
+
+
+def _helper(
+ before: Mapping[str, FunctionMeasures],
+ after: Mapping[str, FunctionMeasures],
+ suggested_name: str | None,
+ slice_nloc: Any,
+) -> str | None:
+ """The function the file gained that the plan would have produced.
+
+ The plan's suggested name, else the new function whose size fits the
+ extracted slice most closely. Any new function is not enough.
+ """
+ fresh = [after[sid] for sid in sorted(set(after) - set(before))]
+ for m in fresh:
+ if suggested_name and m.symbol_id.rsplit("::", 1)[-1] == suggested_name:
+ return m.symbol_id
+ fitting = [m for m in fresh if _fits_slice(m.nloc, slice_nloc)]
+ if not fitting:
+ return None
+ return min(fitting, key=lambda m: abs((m.nloc or 0) - slice_nloc)).symbol_id
+
+
+def _measured_outcome(
+ was: FunctionMeasures | None, now: FunctionMeasures, ccn_removed: Any, has_helper: bool
+) -> str:
+ """Applied when a helper that fits the slice appeared and the target shed at
+ least half the decision points the plan moves out (at least 1)."""
+ if was is None or was.ccn is None or now.ccn is None:
+ return UNKNOWN
+ predicted = ccn_removed if isinstance(ccn_removed, int | float) else None
+ if has_helper and predicted and was.ccn - now.ccn >= max(1, math.ceil(predicted / 2)):
+ return APPLIED
+ if (was.ccn, was.nloc, was.params) == (now.ccn, now.nloc, now.params):
+ # Nothing measured moved: the detector, not the code, changed its mind.
+ return UNKNOWN
+ return TARGET_CHANGED
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
index d4ec71854..7470b8952 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
@@ -17,6 +17,7 @@ from . import ( # noqa: F401
health,
performance,
refactoring,
+ refactoring_payoff,
)
from .coverage import (
coverage_by_module,
@@ -129,12 +130,14 @@ from .refactoring_opportunities import (
refactoring_facet_counts,
update_refactoring_opportunity_status,
)
+from .refactoring_payoff import PayoffContext, plan_payoff
__all__ = [
"FILE_TREND_SNAPSHOT_WINDOW",
"HEALTH_SNAPSHOT_RETENTION",
"HealthSnapshotHeadline",
"HealthSnapshotScalars",
+ "PayoffContext",
"backfill_is_test",
"backfill_module_attribution",
"clear_unanalysed_scores",
@@ -196,6 +199,7 @@ __all__ = [
"opportunity_details",
"performance_facet_counts",
"performance_file_rollups",
+ "plan_payoff",
"prune_unscored_health_rows",
"ranked_refactoring_suggestions",
"refactoring_facet_counts",
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/function_facts.py b/packages/core/src/repowise/core/persistence/crud/analysis/function_facts.py
index e024920db..5bad6a91f 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/function_facts.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/function_facts.py
@@ -8,7 +8,7 @@ moves it, so every run restamps every row's role from its own role map.
from __future__ import annotations
import json
-from collections.abc import Iterable, Mapping
+from collections.abc import Iterable, Iterator, Mapping
from typing import TYPE_CHECKING, Any
from sqlalchemy import and_, delete, insert, or_, select, update
@@ -37,6 +37,10 @@ def _row(repository_id: str, row: Mapping[str, Any]) -> dict[str, Any]:
"receiver_assigns_known": row.get("receiver_assigns_known"),
"receiver_assigns_json": json.dumps(list(assigns)) if assigns else None,
"early_exits": row.get("early_exits"),
+ "ccn": row.get("ccn"),
+ "nloc": row.get("nloc"),
+ "params": row.get("params"),
+ "max_nesting": row.get("max_nesting"),
}
@@ -51,24 +55,38 @@ def key_range(path: str) -> tuple[str, str]:
return f"{path}::", f"{path}:;"
-async def delete_file_rows(session: AsyncSession, repository_id: str, paths: Iterable[str]) -> None:
- """Delete the rows of *paths*, a chunk of key ranges per statement."""
+def _file_range_chunks(repository_id: str, paths: Iterable[str]) -> Iterator[Any]:
+ """The rows of *paths* as WHERE clauses, a chunk of key ranges each."""
ranges = sorted({key_range(path) for path in paths})
for i in range(0, len(ranges), _RANGES_PER_DELETE):
chunk = ranges[i : i + _RANGES_PER_DELETE]
- await session.execute(
- delete(FunctionFact).where(
- FunctionFact.repository_id == repository_id,
- or_(
- *(
- and_(FunctionFact.symbol_id >= low, FunctionFact.symbol_id < high)
- for low, high in chunk
- )
- ),
- )
+ yield and_(
+ FunctionFact.repository_id == repository_id,
+ or_(
+ *(
+ and_(FunctionFact.symbol_id >= low, FunctionFact.symbol_id < high)
+ for low, high in chunk
+ )
+ ),
)
+async def delete_file_rows(session: AsyncSession, repository_id: str, paths: Iterable[str]) -> None:
+ """Delete the rows of *paths*, a chunk of key ranges per statement."""
+ for clause in _file_range_chunks(repository_id, paths):
+ await session.execute(delete(FunctionFact).where(clause))
+
+
+async def get_file_facts(
+ session: AsyncSession, repository_id: str, paths: Iterable[str]
+) -> list[FunctionFact]:
+ """The stored rows of the functions in *paths*."""
+ out: list[FunctionFact] = []
+ for clause in _file_range_chunks(repository_id, paths):
+ out.extend((await session.execute(select(FunctionFact).where(clause))).scalars())
+ return out
+
+
async def write_function_facts(
session: AsyncSession,
repository_id: str,
@@ -87,8 +105,10 @@ async def write_function_facts(
# order fills the clustered pages instead of splitting them half empty.
by_symbol = {row["symbol_id"]: _row(repository_id, row) for row in reversed(list(rows))}
fresh = [by_symbol[symbol] for symbol in sorted(by_symbol)]
+ # On the table, not the mapper: the ORM bulk path splits a batch wherever a
+ # column flips between NULL and a value, which doubled this write.
for i in range(0, len(fresh), _CHUNK):
- await session.execute(insert(FunctionFact), fresh[i : i + _CHUNK])
+ await session.execute(insert(FunctionFact.__table__), fresh[i : i + _CHUNK])
if roles is not None:
await _restamp_roles(session, repository_id, roles)
return len(fresh)
@@ -126,4 +146,10 @@ async def get_function_facts(
return out
-__all__ = ["delete_file_rows", "get_function_facts", "key_range", "write_function_facts"]
+__all__ = [
+ "delete_file_rows",
+ "get_file_facts",
+ "get_function_facts",
+ "key_range",
+ "write_function_facts",
+]
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py
index cc6055e0d..85af31c9c 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py
@@ -13,7 +13,7 @@ from __future__ import annotations
import json
from collections.abc import Mapping
-from typing import Any
+from typing import TYPE_CHECKING, Any
from sqlalchemy import (
Select,
@@ -31,6 +31,9 @@ from ...models import RefactoringSuggestion, _new_uuid, _now_utc
from ...sql import rule_predicate
from .._shared import _BATCH_SIZE, _finding_file_path
+if TYPE_CHECKING:
+ from .refactoring_payoff import PayoffContext
+
# The finding-triage vocabulary, shared with health findings so Code Health has
# one triage system rather than one per layer.
ALLOWED_STATUSES = ("open", "acknowledged", "resolved", "false_positive")
@@ -135,22 +138,30 @@ def _scope_predicates(
return predicates
+def _field(item: Any, name: str) -> Any:
+ """*name* off a ``RefactoringSuggestion`` dataclass or a plain dict."""
+ return item.get(name) if isinstance(item, dict) else getattr(item, name, None)
+
+
+def _target_of(item: Any) -> tuple[str, str, str]:
+ return (
+ _field(item, "refactoring_type"),
+ _finding_file_path(item),
+ _field(item, "target_symbol"),
+ )
+
+
def _scope_suggestions(
suggestions: list[Any],
*,
allowed: set[str] | None,
refactoring_type: str | None,
) -> list[Any]:
- def _type_of(item: Any) -> Any:
- if hasattr(item, "refactoring_type"):
- return item.refactoring_type
- return item.get("refactoring_type")
-
return [
item
for item in suggestions
if (allowed is None or _finding_file_path(item) in allowed)
- and (refactoring_type is None or _type_of(item) == refactoring_type)
+ and (refactoring_type is None or _field(item, "refactoring_type") == refactoring_type)
]
@@ -161,6 +172,7 @@ async def finalize_refactoring_suggestions(
*,
file_paths: list[str] | None = None,
refactoring_type: str | None = None,
+ payoff: PayoffContext | None = None,
) -> int:
"""Reconcile a detector run against the stored plans. Returns rows left open.
@@ -185,6 +197,9 @@ async def finalize_refactoring_suggestions(
answering and stops reading as current;
- a row from an older model, or one written before public ids existed, is
resolved for the same reason. Ids are not translated across models.
+
+ With *payoff*, each current-model plan this call resolves gets a payoff row
+ (``refactoring_payoff``), and a reopened plan loses its own.
"""
from ....analysis.health.refactoring.identity import (
REFACTORING_MODEL_VERSION,
@@ -237,6 +252,8 @@ async def finalize_refactoring_suggestions(
now = _now_utc()
seen: set[str] = set()
pending: list[RefactoringSuggestion] = []
+ reopened: list[str] = []
+ resolved: list[RefactoringSuggestion] = []
for suggestion, public_id in zip(scoped, public_ids, strict=True):
if public_id in seen:
# Two plans reaching one id would violate the uniqueness readers rely
@@ -265,6 +282,7 @@ async def finalize_refactoring_suggestions(
row.status = "open"
row.status_reason = None
row.status_changed_at = now
+ reopened.append(row.id)
row.updated_at = now
for row in stored_rows:
@@ -272,6 +290,9 @@ async def finalize_refactoring_suggestions(
continue
if row.status in ("resolved", "false_positive"):
continue
+ # An older model's row resolves because its id changed, not its code.
+ if row.public_id and row.model_version == REFACTORING_MODEL_VERSION:
+ resolved.append(row)
row.status = "resolved"
row.status_reason = "no_longer_detected"
row.status_changed_at = now
@@ -282,6 +303,17 @@ async def finalize_refactoring_suggestions(
session.add(row)
await session.flush()
await session.flush()
+ if payoff is not None:
+ from .refactoring_payoff import settle_refactoring_payoffs
+
+ await settle_refactoring_payoffs(
+ session,
+ repository_id,
+ resolved=resolved,
+ reopened=reopened,
+ detected={_target_of(item) for item in scoped},
+ ctx=payoff,
+ )
return sum(1 for row in stored_rows if row.status == "open") + len(pending)
@@ -290,13 +322,15 @@ async def save_refactoring_suggestions(
session: AsyncSession,
repository_id: str,
suggestions: list[Any],
+ *,
+ payoff: PayoffContext | None = None,
) -> None:
"""Reconcile every refactoring suggestion for *repository_id*.
The full-reindex entry point. Accepts ``RefactoringSuggestion`` dataclasses
or plain dicts.
"""
- await finalize_refactoring_suggestions(session, repository_id, suggestions)
+ await finalize_refactoring_suggestions(session, repository_id, suggestions, payoff=payoff)
async def upsert_refactoring_suggestions(
@@ -306,6 +340,7 @@ async def upsert_refactoring_suggestions(
*,
file_paths: list[str],
refactoring_type: str | None = None,
+ payoff: PayoffContext | None = None,
) -> None:
"""Reconcile suggestions **only for the given file paths**.
@@ -322,6 +357,7 @@ async def upsert_refactoring_suggestions(
suggestions,
file_paths=list(file_paths),
refactoring_type=refactoring_type,
+ payoff=payoff,
)
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_payoff.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_payoff.py
new file mode 100644
index 000000000..a1db94dd8
--- /dev/null
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_payoff.py
@@ -0,0 +1,169 @@
+"""Payoff rows: what happened to a plan the writer resolved as no longer detected.
+
+Written by :func:`~.refactoring.finalize_refactoring_suggestions` in the same
+call that resolves the plans, before the run's ``function_facts`` replace the
+stored ones: the stored rows are then still the measures the plan was detected
+against, and the run's own fact rows are the measures after.
+"""
+
+from __future__ import annotations
+
+import json
+from collections.abc import Callable, Iterable, Mapping
+from dataclasses import dataclass
+from typing import Any
+
+from sqlalchemy import delete, insert, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from ....analysis.execution_graph import file_of_symbol
+from ...models import RefactoringPayoff, RefactoringSuggestion, _now_utc
+from .._shared import _BATCH_SIZE
+from .function_facts import get_file_facts
+
+_MEASURES = ("ccn", "nloc", "params")
+
+
+@dataclass(frozen=True)
+class PayoffContext:
+ """What the resolving run knows.
+
+ *fact_rows* are its ``function_facts`` rows (``None`` when it had no graph to
+ key them on); *is_live* says whether a path is still on disk or tracked by
+ git, and without it no plan reads as ``file_deleted``; *commit* is the
+ commit the run analysed.
+ """
+
+ fact_rows: Iterable[Mapping[str, Any]] | None
+ is_live: Callable[[str], bool] | None = None
+ commit: str | None = None
+
+
+def _loads(text: str | None) -> dict:
+ try:
+ value = json.loads(text or "{}")
+ except (TypeError, ValueError):
+ return {}
+ return value if isinstance(value, dict) else {}
+
+
+def _payoff_row(row: RefactoringSuggestion, payoff: Any, ctx: PayoffContext, now: Any) -> dict:
+ out = {
+ "suggestion_id": row.id,
+ "repository_id": row.repository_id,
+ "outcome": payoff.outcome,
+ "resolved_commit": ctx.commit,
+ "resolved_at": now,
+ "new_symbol": payoff.new_symbol,
+ }
+ for side in ("before", "after"):
+ measures = getattr(payoff, side)
+ for key in _MEASURES:
+ out[f"{side}_{key}"] = getattr(measures, key) if measures else None
+ return out
+
+
+async def settle_refactoring_payoffs(
+ session: AsyncSession,
+ repository_id: str,
+ *,
+ resolved: list[RefactoringSuggestion],
+ reopened: list[str],
+ detected: set[tuple[str, str, str]],
+ ctx: PayoffContext,
+) -> None:
+ """Drop the payoffs of *reopened* plans and record those of *resolved* ones.
+
+ *detected* is ``(refactoring_type, file_path, target_symbol)`` of every plan
+ the run emitted, so a plan re-detected under a new id reads as superseded.
+ """
+ # Deferred: the refactoring package imports the persistence layer.
+ from ....analysis.health.refactoring.payoff import classify_payoff, measures_by_file
+
+ await clear_refactoring_payoffs(session, reopened + [row.id for row in resolved])
+ if not resolved:
+ return
+ paths = {row.file_path for row in resolved}
+ stored = await get_file_facts(session, repository_id, paths)
+ # ORM rows become plain rows here, the one shape the classifier reads.
+ before = measures_by_file(
+ {"symbol_id": fact.symbol_id, **{key: getattr(fact, key) for key in _MEASURES}}
+ for fact in stored
+ )
+ after = measures_by_file(
+ r for r in (ctx.fact_rows or ()) if file_of_symbol(r["symbol_id"]) in paths
+ )
+ now = _now_utc()
+ values = []
+ for row in resolved:
+ payoff = classify_payoff(
+ refactoring_type=row.refactoring_type,
+ target=row.target_symbol,
+ evidence=_loads(row.evidence_json),
+ file_live=ctx.is_live(row.file_path) if ctx.is_live else None,
+ before=before.get(row.file_path, {}),
+ after=after.get(row.file_path, {}),
+ suggested_name=_loads(row.plan_json).get("suggested_name"),
+ redetected=(row.refactoring_type, row.file_path, row.target_symbol) in detected,
+ )
+ values.append(_payoff_row(row, payoff, ctx, now))
+ for index in range(0, len(values), _BATCH_SIZE):
+ await session.execute(
+ insert(RefactoringPayoff.__table__), values[index : index + _BATCH_SIZE]
+ )
+
+
+async def clear_refactoring_payoffs(session: AsyncSession, suggestion_ids: list[str]) -> None:
+ """Drop the payoff of each plan in *suggestion_ids*."""
+ for index in range(0, len(suggestion_ids), _BATCH_SIZE):
+ await session.execute(
+ delete(RefactoringPayoff).where(
+ RefactoringPayoff.suggestion_id.in_(suggestion_ids[index : index + _BATCH_SIZE])
+ )
+ )
+
+
+def _side(payoff: RefactoringPayoff, side: str) -> dict[str, int]:
+ values = ((key, getattr(payoff, f"{side}_{key}")) for key in _MEASURES)
+ return {key: value for key, value in values if value is not None}
+
+
+async def plan_payoff(session: AsyncSession, row: RefactoringSuggestion) -> dict | None:
+ """The stored payoff of a plan the writer resolved, for its detail.
+
+ ``None`` for any other plan, a person's resolution included. ``realised``
+ is what left the target, beside the plan's own prediction in its
+ ``evidence`` (``ccn_removed``, ``slice_nloc``).
+ """
+ if row.status != "resolved" or row.status_reason != "no_longer_detected":
+ return None
+ payoff = (
+ await session.execute(
+ select(RefactoringPayoff).where(RefactoringPayoff.suggestion_id == row.id)
+ )
+ ).scalar_one_or_none()
+ if payoff is None:
+ return None
+ before, after = _side(payoff, "before"), _side(payoff, "after")
+ out: dict[str, Any] = {
+ "outcome": payoff.outcome,
+ "resolved_commit": payoff.resolved_commit,
+ "resolved_at": payoff.resolved_at.isoformat() if payoff.resolved_at else None,
+ "before": before,
+ "after": after,
+ "realised": {
+ f"{key}_removed": before[key] - after[key]
+ for key in ("ccn", "nloc")
+ if key in before and key in after
+ },
+ "new_symbol": payoff.new_symbol,
+ }
+ return {key: value for key, value in out.items() if value not in (None, {})}
+
+
+__all__ = [
+ "PayoffContext",
+ "clear_refactoring_payoffs",
+ "plan_payoff",
+ "settle_refactoring_payoffs",
+]
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 71ff01531..5f03bf3c7 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -2108,10 +2108,57 @@ class FunctionFact(Base):
receiver_assigns_known: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
receiver_assigns_json: Mapped[str | None] = mapped_column(Text, nullable=True)
early_exits: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ # The complexity walk's size measures (``FunctionComplexity.stored_metrics``).
+ # NULL where the walk did not measure them; ``params`` is NULL rather than 0
+ # when no parameter was found, since the walk cannot tell that from none.
+ ccn: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ nloc: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ params: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ max_nesting: Mapped[int | None] = mapped_column(Integer, nullable=True)
__table_args__ = ({"sqlite_with_rowid": False},)
+class RefactoringPayoff(Base):
+ """What happened to a plan the writer resolved as no longer detected.
+
+ One row per plan, written when the writer resolves it and removed when it
+ reopens. ``before_*`` come from the stored ``function_facts`` row of the
+ plan's target, ``after_*`` from the run that resolved it, so nothing is
+ measured again when the plan is read. The prediction stays on the plan row.
+ """
+
+ __tablename__ = "refactoring_payoffs"
+
+ suggestion_id: Mapped[str] = mapped_column(
+ String(32),
+ ForeignKey("refactoring_suggestions.id", ondelete="CASCADE"),
+ primary_key=True,
+ )
+ repository_id: Mapped[str] = mapped_column(
+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False
+ )
+ # ``refactoring.payoff.PAYOFF_OUTCOMES``.
+ outcome: Mapped[str] = mapped_column(String(16), nullable=False)
+ # The commit the resolving run analysed; NULL when it was not recorded.
+ resolved_commit: Mapped[str | None] = mapped_column(String(64), nullable=True)
+ resolved_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), nullable=False, default=_now_utc
+ )
+ before_ccn: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ before_nloc: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ before_params: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ after_ccn: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ after_nloc: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ after_params: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ # A function the resolving run found in the target's file and the run
+ # before did not, sized like the plan's slice or carrying its suggested
+ # name: the helper, when the plan was applied.
+ new_symbol: Mapped[str | None] = mapped_column(Text, nullable=True)
+
+ __table_args__ = (Index("ix_refactoring_payoffs_repo_outcome", "repository_id", "outcome"),)
+
+
class RefactoringOpportunity(QueueVerdict, Base):
"""One file's composed refactoring work, materialized for serving.
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index 7e963ebf1..90881954d 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -1278,6 +1278,7 @@ async def persist_partial_health(
and metrics across an incremental ``repowise update``.
"""
from repowise.core.persistence.crud import (
+ PayoffContext,
finalize_performance_opportunities,
finalize_refactoring_opportunities,
upsert_health_findings,
@@ -1285,7 +1286,7 @@ async def persist_partial_health(
upsert_refactoring_suggestions,
write_function_facts,
)
- from repowise.core.pipeline.persist import _analyzed_commit
+ from repowise.core.pipeline.persist import _analyzed_commit, path_liveness
changed_paths = sorted(
set(getattr(report, "authoritative_paths", None) or ())
@@ -1337,6 +1338,13 @@ async def persist_partial_health(
if suggestion.refactoring_type != "performance_fix"
],
file_paths=changed_paths,
+ # Before the facts below replace the stored ones: those are the
+ # measures a resolved plan was detected against.
+ payoff=PayoffContext(
+ fact_rows=getattr(report, "function_facts", None),
+ is_live=path_liveness(repo_path),
+ commit=analyzed_commit,
+ ),
)
# A partial run sees a subset of the findings, so the plans and the
# queue it would derive are a subset too. Both are rebuilt here instead,
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index cb5bf3f1a..9897db446 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -9,7 +9,7 @@ from __future__ import annotations
import dataclasses
import json
import logging
-from collections.abc import Iterable
+from collections.abc import Callable, Iterable
from pathlib import Path
from typing import Any
@@ -1072,6 +1072,38 @@ class _FileLiveness:
return path in self._tracked
+def path_liveness(repo_path: Any) -> Callable[[str], bool] | None:
+ """Whether a repo-relative path is still on disk or tracked by git; ``None``
+ without a checkout to ask, so no caller reads a path as deleted on no evidence."""
+ return _FileLiveness(repo_path).is_live if repo_path else None
+
+
+async def _resolve_plans_of_deleted_files(
+ session: Any, repo_id: str, dead: Callable[[set[str], str], list[str]], liveness: Any
+) -> None:
+ from sqlalchemy import select
+
+ from repowise.core.persistence.crud import PayoffContext, upsert_refactoring_suggestions
+ from repowise.core.persistence.models import RefactoringSuggestion
+
+ live_plan_paths = await session.execute(
+ select(RefactoringSuggestion.file_path)
+ .where(
+ RefactoringSuggestion.repository_id == repo_id,
+ RefactoringSuggestion.status.in_(("open", "acknowledged")),
+ )
+ .distinct()
+ )
+ gone = dead(set(live_plan_paths.scalars().all()), "refactoring_suggestions")
+ if gone:
+ payoff = PayoffContext(
+ fact_rows=None,
+ is_live=liveness.is_live,
+ commit=await _analyzed_commit(session, repo_id),
+ )
+ await upsert_refactoring_suggestions(session, repo_id, [], file_paths=gone, payoff=payoff)
+
+
async def prune_deleted_file_rows(
session: Any,
repo_id: str,
@@ -1219,6 +1251,11 @@ async def prune_deleted_file_rows(
await _prune_table(WikiSymbol, WikiSymbol.file_path, "wiki_symbols")
await _prune_table(SecurityFinding, SecurityFinding.file_path, "security_findings")
await _prune_table(DeadCodeFinding, DeadCodeFinding.file_path, "dead_code_findings")
+ # Plans are resolved, not deleted, so a held id keeps answering. A scoped
+ # run never names a deleted file (or a renamed file's old path) again, so
+ # this is the one place they resolve. Before the facts below go: those are
+ # the target's measures the payoff keeps.
+ await _resolve_plans_of_deleted_files(session, repo_id, _dead, liveness)
# Keyed on the symbol: a deleted file's rows are one key range of the id.
await delete_file_rows(session, repo_id, dead_paths)
# Keyed on the DOCUMENT. The incremental drift pass scopes its write to the
@@ -1895,6 +1932,7 @@ async def save_full_health_report(
health_report: Any,
*,
analyzed_commit: str | None,
+ repo_path: Any = None,
) -> None:
"""Full-replace a repository's health rows and everything derived from them.
@@ -1906,9 +1944,11 @@ async def save_full_health_report(
``analyzed_commit`` stamps the metric rows and the read models with the
commit these scores were computed against; ``None`` reads as "not
- recorded", which is honest, while a wrong sha would not be.
+ recorded", which is honest, while a wrong sha would not be. ``repo_path``
+ lets a plan whose file is gone read as deleted.
"""
from repowise.core.persistence.crud import (
+ PayoffContext,
finalize_performance_opportunities,
finalize_refactoring_opportunities,
save_health_findings,
@@ -1949,6 +1989,13 @@ async def save_full_health_report(
for suggestion in (getattr(hr, "refactoring_suggestions", None) or [])
if getattr(suggestion, "refactoring_type", None) != "performance_fix"
],
+ # Before the facts below replace the stored ones: those are the
+ # measures a resolved plan was detected against.
+ payoff=PayoffContext(
+ fact_rows=getattr(hr, "function_facts", None),
+ is_live=path_liveness(repo_path),
+ commit=analyzed_commit,
+ ),
)
# Group the stored performance findings into the materialized causal
# read model, then reconcile lifecycle and plans.
@@ -2071,7 +2118,13 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
# metric rows, so a reader can tell how far the health pass lags the
# index instead of assuming the two moved together.
head_sha = await _analyzed_commit(session, repo_id)
- await save_full_health_report(session, repo_id, hr, analyzed_commit=head_sha)
+ await save_full_health_report(
+ session,
+ repo_id,
+ hr,
+ analyzed_commit=head_sha,
+ repo_path=getattr(result, "repo_path", None),
+ )
# Resolved coverage rows, when a report was ingested this run.
coverage_files = getattr(hr, "coverage_files", None)
if coverage_files:
diff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.py
index 6962463e5..7dfc5eac4 100644
--- a/packages/server/src/repowise/server/routers/refactoring.py
+++ b/packages/server/src/repowise/server/routers/refactoring.py
@@ -364,8 +364,8 @@ async def _plan_detail(
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 recommendation.detail_dict(), row.public_id or row.id
+ detail = await _service(session, repo_id).plan_detail_dict(row)
+ return detail, row.public_id or row.id
async def _repository(session: AsyncSession, repo_id: str) -> Any:
diff --git a/packages/server/src/repowise/server/schemas/refactoring.py b/packages/server/src/repowise/server/schemas/refactoring.py
index 1af59daf2..797531be8 100644
--- a/packages/server/src/repowise/server/schemas/refactoring.py
+++ b/packages/server/src/repowise/server/schemas/refactoring.py
@@ -152,6 +152,35 @@ class PlanRiskResponse(BaseModel):
ref: str | None = None
+class PlanMeasuresResponse(BaseModel):
+ """A function's stored size measures; an absent one was not measured."""
+
+ ccn: int | None = None
+ nloc: int | None = None
+ params: int | None = None
+
+
+class PlanPayoffResponse(BaseModel):
+ """What happened to a plan the index resolved as no longer detected.
+
+ ``applied`` means the measures are consistent with the plan being applied:
+ the target shed at least half the predicted decision points and a function
+ fitting the extracted slice appeared beside it.
+ """
+
+ #: ``refactoring.payoff.PAYOFF_OUTCOMES``.
+ outcome: str
+ resolved_commit: str | None = None
+ resolved_at: str | None = None
+ before: PlanMeasuresResponse | None = None
+ after: PlanMeasuresResponse | None = None
+ #: Measured drop, beside the plan's predicted ``evidence``.
+ realised: dict[str, int] | None = None
+ #: The function that appeared beside the target, sized like the plan's
+ #: slice or carrying its suggested name.
+ new_symbol: str | None = None
+
+
class RefactoringPlanDetailResponse(RefactoringPlanResponse):
"""One plan read alone: what other layers say about its target. Lists stay
on :class:`RefactoringPlanResponse` and never carry these; both are absent
@@ -162,6 +191,10 @@ class RefactoringPlanDetailResponse(RefactoringPlanResponse):
# Only with ``include=recipe``: the plan as preconditions, steps and
# postconditions an agent applies (``refactoring.recipe``).
recipe: dict[str, Any] | None = None
+ # Only on a plan the index resolved as no longer detected: applied, file
+ # deleted or target changed, with the target's measures before and after
+ # (``crud.plan_payoff``).
+ payoff: PlanPayoffResponse | None = None
class RefactoringTypeCount(BaseModel):
diff --git a/packages/server/src/repowise/server/services/refactoring_health.py b/packages/server/src/repowise/server/services/refactoring_health.py
index 13d8dc78c..7e1a9dbed 100644
--- a/packages/server/src/repowise/server/services/refactoring_health.py
+++ b/packages/server/src/repowise/server/services/refactoring_health.py
@@ -61,6 +61,7 @@ from repowise.core.persistence.crud.analysis.refactoring_opportunities import (
refactoring_reason_counts,
refactoring_step_counts,
)
+from repowise.core.persistence.crud.analysis.refactoring_payoff import plan_payoff
from repowise.core.persistence.crud.analysis.refactoring_recommendations import (
hydrate_recommendations,
plan_rank_inputs,
@@ -399,7 +400,7 @@ class RefactoringHealthService:
owner = await owning_refactoring_opportunity(
self._session, self._repository_id, row.public_id, row.file_path
)
- payload = (await self.plan_recommendation(row, owner=owner)).detail_dict()
+ payload = await self.plan_detail_dict(row, owner=owner)
payload["id"] = row.public_id or row.id
payload["status"] = row.status
result: dict[str, Any] = {"resolved": True, "plan_id": plan_id, "plan": payload}
@@ -451,6 +452,15 @@ class RefactoringHealthService:
plans = [item.as_dict() for item in ranked]
return {"summary": {"total": chips["total"], "by_type": chips["by_type"]}, "plans": plans}
+ async def plan_detail_dict(self, row: Any, *, owner: Any = None) -> dict[str, Any]:
+ """One stored plan's detail, as REST and MCP serve it: the ranked plan,
+ and what happened to it when the index resolved it."""
+ detail = (await self.plan_recommendation(row, owner=owner)).detail_dict()
+ payoff = await plan_payoff(self._session, row)
+ if payoff is not None:
+ detail["payoff"] = payoff
+ return detail
+
async def plan_recommendation(self, row: Any, *, owner: Any = None) -> Any:
"""One stored plan as a ranked recommendation, without the repository.
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 5541c7cbc..0a0b0c663 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -2626,6 +2626,30 @@ export interface PatchCoverageTestHint {
total: number;
}
+/** A function's stored size measures; an absent one was not measured. */
+export interface PlanMeasuresResponse {
+ ccn?: number | null;
+ nloc?: number | null;
+ params?: number | null;
+}
+
+/**
+ * What happened to a plan the index resolved as no longer detected.
+ *
+ * ``applied`` means the measures are consistent with the plan being applied:
+ * the target shed at least half the predicted decision points and a function
+ * fitting the extracted slice appeared beside it.
+ */
+export interface PlanPayoffResponse {
+ outcome: string;
+ resolved_commit?: string | null;
+ resolved_at?: string | null;
+ before?: PlanMeasuresResponse | null;
+ after?: PlanMeasuresResponse | null;
+ realised?: Record<string, number> | null;
+ new_symbol?: string | null;
+}
+
export interface PlanRiskResponse {
kind: string;
text: string;
@@ -2792,6 +2816,7 @@ export interface RefactoringPlanDetailResponse {
governed_by?: string[] | null;
risks?: PlanRiskResponse[] | null;
recipe?: Record<string, unknown> | null;
+ payoff?: PlanPayoffResponse | null;
}
/**
diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.ts
index 1f5bd5d6b..449f1ebab 100644
--- a/packages/types/src/refactoring.ts
+++ b/packages/types/src/refactoring.ts
@@ -130,6 +130,35 @@ export interface RefactoringPlan {
risks?: PlanRisk[];
/** Plan detail with `include=recipe` only: the plan as an agent applies it. */
recipe?: RefactoringRecipe;
+ /** Plan detail only, on a plan the index resolved as no longer detected. */
+ payoff?: RefactoringPlanPayoff;
+}
+
+/** What happened to a resolved plan. Mirrors ``refactoring.payoff.PAYOFF_OUTCOMES``. */
+export type RefactoringPayoffOutcome =
+ | "applied"
+ | "file_deleted"
+ | "superseded"
+ | "target_changed"
+ | "unknown";
+
+/** A function's stored size measures; an absent one was not measured. */
+export interface PlanMeasures {
+ ccn?: number;
+ nloc?: number;
+ params?: number;
+}
+
+export interface RefactoringPlanPayoff {
+ outcome: RefactoringPayoffOutcome;
+ resolved_commit?: string;
+ resolved_at?: string;
+ before?: PlanMeasures;
+ after?: PlanMeasures;
+ /** Measured drop (`ccn_removed`, `nloc_removed`), beside the plan's predicted `evidence`. */
+ realised?: Record<string, number>;
+ /** The function that appeared beside the target, sized like the plan's slice. */
+ new_symbol?: string;
}
/** What one recipe step does to the code. Mirrors ``refactoring.recipe.RECIPE_ACTIONS``. */
diff --git a/tests/unit/health/test_function_facts_store.py b/tests/unit/health/test_function_facts_store.py
index 77e3be294..faa0d77fc 100644
--- a/tests/unit/health/test_function_facts_store.py
+++ b/tests/unit/health/test_function_facts_store.py
@@ -245,3 +245,35 @@ fn tail() -> Result<(), E> {
facts = _facts("check.rs", "rust", source)
assert facts["check"] is not None and facts["check"].early_exits == 2
assert facts["tail"] is not None and facts["tail"].early_exits == 0
+
+
+def test_a_fresh_analysis_fills_the_size_measures(tmp_path: Path) -> None:
+ from types import SimpleNamespace
+
+ (tmp_path / "store.py").write_bytes(_PY)
+ graph = nx.DiGraph()
+ graph.add_node("store.py", node_type="file")
+ for fc in walk_file("store.py", "python", _PY).functions:
+ graph.add_node(
+ f"store.py::{fc.name}",
+ node_type="symbol",
+ kind="function",
+ name=fc.name,
+ file_path="store.py",
+ start_line=fc.start_line,
+ end_line=fc.end_line,
+ )
+ parsed = SimpleNamespace(
+ file_info=SimpleNamespace(
+ path="store.py", abs_path=str(tmp_path / "store.py"), language="python", is_test=False
+ ),
+ symbols=[],
+ )
+ report = HealthAnalyzer(graph=graph, parsed_files=[parsed], repo_root=tmp_path).analyze()
+
+ by_id = {row["symbol_id"]: row for row in report.function_facts or []}
+ plain = by_id["store.py::plain"]
+ assert (plain["ccn"], plain["max_nesting"], plain["params"]) == (2, 1, 1)
+ assert plain["nloc"] > 0
+ # No parameter besides the receiver: unknown, never 0.
+ assert by_id["store.py::each"]["params"] is None
diff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.py
index 98a5adac8..8849bf352 100644
--- a/tests/unit/persistence/test_models.py
+++ b/tests/unit/persistence/test_models.py
@@ -332,6 +332,7 @@ def test_base_includes_all_models():
"performance_opportunities",
"performance_summaries",
"function_facts",
+ "refactoring_payoffs",
"coverage_files",
"coverage_ingests",
"action_states",
diff --git a/tests/unit/persistence/test_refactoring_payoff.py b/tests/unit/persistence/test_refactoring_payoff.py
new file mode 100644
index 000000000..b1b9fb9e1
--- /dev/null
+++ b/tests/unit/persistence/test_refactoring_payoff.py
@@ -0,0 +1,466 @@
+"""A plan that stops being detected says what happened to it.
+
+Applied, file deleted, superseded or target changed, from the target's stored
+measures before the resolving run and the run's own measures after, with the
+commit.
+"""
+
+from __future__ import annotations
+
+import sqlite3
+from pathlib import Path
+
+import pytest
+from sqlalchemy import select
+
+from repowise.core.analysis.health.complexity.models import FunctionComplexity
+from repowise.core.analysis.health.refactoring import RefactoringSuggestion
+from repowise.core.analysis.health.refactoring.identity import REFACTORING_MODEL_VERSION
+from repowise.core.analysis.health.refactoring.payoff import (
+ APPLIED,
+ FILE_DELETED,
+ SUPERSEDED,
+ TARGET_CHANGED,
+ UNKNOWN,
+ FunctionMeasures,
+ classify_payoff,
+)
+from repowise.core.persistence.crud.analysis import (
+ PayoffContext,
+ finalize_refactoring_suggestions,
+ get_refactoring_suggestion,
+ plan_payoff,
+ save_refactoring_suggestions,
+ update_refactoring_suggestion_status,
+ upsert_refactoring_suggestions,
+ write_function_facts,
+)
+from repowise.core.persistence.models import FunctionFact, RefactoringPayoff
+from repowise.core.persistence.models import RefactoringSuggestion as SuggestionRow
+from tests.unit.persistence.helpers import insert_repo
+
+
+def _plan(path: str = "a.py", target: str = "run", **overrides) -> RefactoringSuggestion:
+ base = dict(
+ refactoring_type="extract_method",
+ file_path=path,
+ target_symbol=target,
+ line_start=1,
+ line_end=60,
+ plan={"span": {"start": 10, "end": 30}, "suggested_name": "_load_rows"},
+ evidence={"slice_nloc": 18, "ccn_removed": 6},
+ impact_delta=3.0,
+ effort_bucket="S",
+ blast_radius={"scope": "local"},
+ confidence="high",
+ source_biomarker="complex_method",
+ )
+ base.update(overrides)
+ return RefactoringSuggestion(**base)
+
+
+def _fact(symbol: str, ccn: int | None, nloc: int | None, params: int | None = 2) -> dict:
+ return {"symbol_id": symbol, "ccn": ccn, "nloc": nloc, "params": params}
+
+
+def _measures(*rows: dict) -> dict[str, FunctionMeasures]:
+ return {
+ r["symbol_id"]: FunctionMeasures(r["symbol_id"], r["ccn"], r["nloc"], r["params"])
+ for r in rows
+ }
+
+
+def _classify(before, after, *, file_live=True, kind="extract_method", redetected=False):
+ return classify_payoff(
+ redetected=redetected,
+ refactoring_type=kind,
+ target="run",
+ evidence={"slice_nloc": 18, "ccn_removed": 6},
+ file_live=file_live,
+ before=before,
+ after=after,
+ suggested_name="_load_rows",
+ )
+
+
+# --- the classifier ---------------------------------------------------------
+
+
+def test_an_extract_that_moved_the_predicted_complexity_out_is_applied() -> None:
+ before = _measures(_fact("a.py::Job::run", 14, 50))
+ after = _measures(_fact("a.py::Job::run", 9, 34), _fact("a.py::Job::_load_rows", 6, 18))
+ payoff = _classify(before, after)
+ assert payoff.outcome == APPLIED
+ assert payoff.new_symbol == "a.py::Job::_load_rows"
+ assert (payoff.before.ccn, payoff.after.ccn) == (14, 9)
+
+
+def test_a_new_function_the_size_of_the_slice_counts_as_the_helper() -> None:
+ before = _measures(_fact("a.py::run", 14, 50))
+ after = _measures(
+ _fact("a.py::run", 8, 30), _fact("a.py::_anchor", 1, 2), _fact("a.py::rows", 5, 20)
+ )
+ payoff = _classify(before, after)
+ assert (payoff.outcome, payoff.new_symbol) == (APPLIED, "a.py::rows")
+
+
+def test_any_new_function_is_not_enough_for_applied() -> None:
+ before = _measures(_fact("a.py::run", 14, 50))
+ # Shed the complexity, but the only new function is far smaller than the slice.
+ after = _measures(_fact("a.py::run", 8, 30), _fact("a.py::_anchor", 1, 2))
+ payoff = _classify(before, after)
+ assert payoff.outcome == TARGET_CHANGED
+ assert payoff.new_symbol is None
+
+
+def test_lines_alone_do_not_make_it_applied() -> None:
+ before = _measures(_fact("a.py::run", 14, 50))
+ after = _measures(_fact("a.py::run", 13, 30), _fact("a.py::_load_rows", 1, 18))
+ assert _classify(before, after).outcome == TARGET_CHANGED
+
+
+def test_a_deleted_file_is_file_deleted_and_keeps_the_before_measures() -> None:
+ before = _measures(_fact("a.py::run", 14, 50))
+ payoff = _classify(before, {}, file_live=False)
+ assert payoff.outcome == FILE_DELETED
+ assert payoff.before.ccn == 14
+
+
+def test_without_liveness_a_missing_file_is_never_called_deleted() -> None:
+ before = _measures(_fact("a.py::run", 14, 50))
+ assert _classify(before, {}, file_live=None).outcome == UNKNOWN
+
+
+def test_a_renamed_target_is_target_changed() -> None:
+ before = _measures(_fact("a.py::run", 14, 50))
+ after = _measures(_fact("a.py::execute", 14, 50))
+ assert _classify(before, after).outcome == TARGET_CHANGED
+
+
+def test_a_rewrite_that_left_no_helper_is_target_changed() -> None:
+ before = _measures(_fact("a.py::run", 14, 50))
+ after = _measures(_fact("a.py::run", 8, 30))
+ assert _classify(before, after).outcome == TARGET_CHANGED
+
+
+def test_too_small_a_drop_is_not_applied() -> None:
+ before = _measures(_fact("a.py::run", 14, 50))
+ after = _measures(_fact("a.py::run", 13, 49), _fact("a.py::_load_rows", 2, 18))
+ assert _classify(before, after).outcome == TARGET_CHANGED
+
+
+def test_a_file_with_no_measures_after_the_run_is_unknown() -> None:
+ before = _measures(_fact("a.py::run", 14, 50))
+ # Unscored, excluded, or a run with no graph to key facts on.
+ assert _classify(before, {}).outcome == UNKNOWN
+ assert _classify(before, {}, redetected=True).outcome == SUPERSEDED
+
+
+def test_unmeasured_sides_are_unknown_never_a_guess() -> None:
+ before = _measures(_fact("a.py::run", None, None))
+ after = _measures(_fact("a.py::run", 9, 34), _fact("a.py::_load_rows", 6, 18))
+ assert _classify(before, after).outcome == UNKNOWN
+ # Nothing measured moved: the detector changed its mind, not the code.
+ same = _measures(_fact("a.py::run", 14, 50))
+ assert _classify(same, same).outcome == UNKNOWN
+
+
+def test_an_edited_target_detected_again_under_a_new_id_is_superseded() -> None:
+ before = _measures(_fact("a.py::run", 14, 50))
+ after = _measures(_fact("a.py::run", 15, 53))
+ assert _classify(before, after, redetected=True).outcome == SUPERSEDED
+ # Applied still wins: the plan moved what it said, another extract remains.
+ applied = _measures(_fact("a.py::run", 8, 30), _fact("a.py::_load_rows", 6, 18))
+ assert _classify(before, applied, redetected=True).outcome == APPLIED
+ assert _classify({}, {}, kind="split_file", redetected=True).outcome == SUPERSEDED
+
+
+def test_kinds_without_a_function_target_are_unknown_unless_deleted() -> None:
+ assert _classify({}, {}, kind="split_file").outcome == UNKNOWN
+ assert _classify({}, {}, kind="split_file", file_live=False).outcome == FILE_DELETED
+
+
+def test_two_functions_sharing_the_name_are_ambiguous() -> None:
+ before = _measures(_fact("a.py::A::run", 14, 50), _fact("a.py::B::run", 3, 5))
+ after = _measures(_fact("a.py::A::run", 9, 34), _fact("a.py::B::run", 3, 5))
+ assert _classify(before, after).outcome == UNKNOWN
+
+
+def test_stored_metrics_keep_an_unfound_parameter_list_unknown() -> None:
+ fc = FunctionComplexity(
+ name="f", start_line=1, end_line=9, ccn=4, max_nesting=2, cognitive=3, nloc=8
+ )
+ assert fc.stored_metrics() == {"ccn": 4, "nloc": 8, "params": None, "max_nesting": 2}
+
+
+# --- the writer ---------------------------------------------------------------
+
+
+def _live(*paths: str):
+ return lambda path: path in paths
+
+
+async def _resolve_all(session, repo_id: str, facts: list[dict] | None, *, live: set[str]):
+ await save_refactoring_suggestions(
+ session,
+ repo_id,
+ [],
+ payoff=PayoffContext(fact_rows=facts, is_live=_live(*live), commit="abc123"),
+ )
+
+
+async def _payoffs(session, repo_id: str) -> dict[str, RefactoringPayoff]:
+ rows = await session.execute(
+ select(RefactoringPayoff).where(RefactoringPayoff.repository_id == repo_id)
+ )
+ return {row.suggestion_id: row for row in rows.scalars()}
+
+
+async def test_resolving_an_applied_plan_stores_before_after_and_the_commit(async_session):
+ repo = await insert_repo(async_session)
+ await save_refactoring_suggestions(async_session, repo.id, [_plan()])
+ await write_function_facts(async_session, repo.id, [_fact("a.py::run", 14, 50)])
+
+ after = [_fact("a.py::run", 8, 32), _fact("a.py::_load_rows", 7, 18, params=1)]
+ await _resolve_all(async_session, repo.id, after, live={"a.py"})
+
+ (row,) = (await async_session.execute(select(SuggestionRow))).scalars()
+ assert (row.status, row.status_reason) == ("resolved", "no_longer_detected")
+ stored = (await _payoffs(async_session, repo.id))[row.id]
+ assert stored.outcome == APPLIED
+ assert stored.resolved_commit == "abc123"
+ assert (stored.before_ccn, stored.after_ccn, stored.before_nloc, stored.after_nloc) == (
+ 14,
+ 8,
+ 50,
+ 32,
+ )
+ assert stored.new_symbol == "a.py::_load_rows"
+
+ detail = await plan_payoff(async_session, row)
+ assert detail["outcome"] == APPLIED
+ assert detail["realised"] == {"ccn_removed": 6, "nloc_removed": 18}
+ assert detail["before"] == {"ccn": 14, "nloc": 50, "params": 2}
+
+
+async def test_a_plan_in_a_deleted_file_is_file_deleted(async_session):
+ repo = await insert_repo(async_session)
+ await save_refactoring_suggestions(async_session, repo.id, [_plan("gone.py")])
+ await _resolve_all(async_session, repo.id, [], live=set())
+ (stored,) = (await _payoffs(async_session, repo.id)).values()
+ assert stored.outcome == FILE_DELETED
+
+
+async def test_a_present_but_unscored_file_is_unknown_not_deleted(async_session):
+ repo = await insert_repo(async_session)
+ await save_refactoring_suggestions(async_session, repo.id, [_plan()])
+ await write_function_facts(async_session, repo.id, [_fact("a.py::run", 14, 50)])
+ # The run kept the file (excluded, or scored nothing) but measured none of it.
+ await _resolve_all(async_session, repo.id, [_fact("b.py::other", 1, 1)], live={"a.py"})
+ (stored,) = (await _payoffs(async_session, repo.id)).values()
+ assert stored.outcome == UNKNOWN
+ assert stored.before_ccn == 14
+
+
+async def test_a_rewritten_target_is_target_changed(async_session):
+ repo = await insert_repo(async_session)
+ await save_refactoring_suggestions(async_session, repo.id, [_plan()])
+ await write_function_facts(async_session, repo.id, [_fact("a.py::run", 14, 50)])
+ await _resolve_all(async_session, repo.id, [_fact("a.py::execute", 5, 20)], live={"a.py"})
+ (stored,) = (await _payoffs(async_session, repo.id)).values()
+ assert stored.outcome == TARGET_CHANGED
+ assert stored.before_ccn == 14 and stored.after_ccn is None
+
+
+async def test_a_plan_detected_again_after_an_edit_is_superseded(async_session):
+ repo = await insert_repo(async_session)
+ await save_refactoring_suggestions(async_session, repo.id, [_plan()])
+ await write_function_facts(async_session, repo.id, [_fact("a.py::run", 14, 50)])
+ # The edit grew the function, so the same plan has a new id.
+ moved = _plan(line_end=63)
+ await save_refactoring_suggestions(
+ async_session,
+ repo.id,
+ [moved],
+ payoff=PayoffContext(fact_rows=[_fact("a.py::run", 15, 53)], is_live=_live("a.py")),
+ )
+ (stored,) = (await _payoffs(async_session, repo.id)).values()
+ assert stored.outcome == SUPERSEDED
+
+
+async def test_a_reopened_plan_loses_its_payoff_and_open_plans_show_none(async_session):
+ repo = await insert_repo(async_session)
+ await save_refactoring_suggestions(async_session, repo.id, [_plan()])
+ await _resolve_all(async_session, repo.id, [], live={"a.py"})
+ assert len(await _payoffs(async_session, repo.id)) == 1
+
+ await save_refactoring_suggestions(
+ async_session,
+ repo.id,
+ [_plan()],
+ payoff=PayoffContext(fact_rows=[], is_live=_live("a.py")),
+ )
+ (row,) = (await async_session.execute(select(SuggestionRow))).scalars()
+ assert row.status == "open"
+ assert await _payoffs(async_session, repo.id) == {}
+ assert await plan_payoff(async_session, row) is None
+
+
+async def test_a_plan_a_person_resolved_shows_no_payoff(async_session):
+ repo = await insert_repo(async_session)
+ await save_refactoring_suggestions(async_session, repo.id, [_plan()])
+ await _resolve_all(async_session, repo.id, [], live=set())
+ (row,) = (await async_session.execute(select(SuggestionRow))).scalars()
+ assert (await plan_payoff(async_session, row))["outcome"] == FILE_DELETED
+ await update_refactoring_suggestion_status(async_session, repo.id, row.id, "resolved")
+ assert await plan_payoff(async_session, row) is None
+
+
+async def test_an_older_models_row_resolves_without_a_payoff(async_session):
+ repo = await insert_repo(async_session)
+ await save_refactoring_suggestions(async_session, repo.id, [_plan()])
+ (row,) = (await async_session.execute(select(SuggestionRow))).scalars()
+ row.model_version = REFACTORING_MODEL_VERSION - 1
+ await async_session.flush()
+ await _resolve_all(async_session, repo.id, [], live=set())
+ assert row.status == "resolved"
+ assert await _payoffs(async_session, repo.id) == {}
+
+
+async def test_an_incremental_update_keeps_payoffs_outside_its_scope(async_session):
+ repo = await insert_repo(async_session)
+ await save_refactoring_suggestions(async_session, repo.id, [_plan("a.py"), _plan("b.py")])
+ ctx = PayoffContext(fact_rows=[], is_live=_live("a.py", "b.py"), commit="c1")
+ await upsert_refactoring_suggestions(
+ async_session, repo.id, [_plan("b.py")], file_paths=["a.py"], payoff=ctx
+ )
+ first = await _payoffs(async_session, repo.id)
+ assert len(first) == 1
+
+ ctx = PayoffContext(fact_rows=[], is_live=_live("a.py", "b.py"), commit="c2")
+ await upsert_refactoring_suggestions(async_session, repo.id, [], file_paths=["b.py"], payoff=ctx)
+ second = await _payoffs(async_session, repo.id)
+ assert len(second) == 2
+ a_id = next(iter(first))
+ assert second[a_id].resolved_commit == "c1"
+
+
+async def test_without_a_payoff_context_the_writer_records_nothing(async_session):
+ repo = await insert_repo(async_session)
+ await save_refactoring_suggestions(async_session, repo.id, [_plan()])
+ await finalize_refactoring_suggestions(async_session, repo.id, [])
+ row = await get_refactoring_suggestion(
+ async_session, repo.id, (await async_session.execute(select(SuggestionRow.id))).scalar_one()
+ )
+ assert row.status == "resolved"
+ assert await _payoffs(async_session, repo.id) == {}
+
+
+async def test_the_deleted_file_prune_resolves_its_plans_as_file_deleted(async_session, tmp_path):
+ from repowise.core.pipeline.persist import prune_deleted_file_rows
+
+ repo = await insert_repo(async_session)
+ (tmp_path / "kept.py").write_text("def run():\n pass\n", encoding="utf-8")
+ await save_refactoring_suggestions(
+ async_session, repo.id, [_plan("kept.py"), _plan("gone.py")]
+ )
+ await write_function_facts(async_session, repo.id, [_fact("gone.py::run", 14, 50)])
+
+ await prune_deleted_file_rows(async_session, repo.id, tmp_path)
+
+ rows = {r.file_path: r for r in (await async_session.execute(select(SuggestionRow))).scalars()}
+ assert rows["kept.py"].status == "open"
+ assert (rows["gone.py"].status, rows["gone.py"].status_reason) == (
+ "resolved",
+ "no_longer_detected",
+ )
+ (stored,) = (await _payoffs(async_session, repo.id)).values()
+ assert (stored.suggestion_id, stored.outcome) == (rows["gone.py"].id, FILE_DELETED)
+ assert stored.before_ccn == 14
+
+
+async def test_fact_rows_store_the_size_measures(async_session):
+ repo = await insert_repo(async_session)
+ await write_function_facts(async_session, repo.id, [_fact("a.py::run", 14, 50, None)])
+ (fact,) = (await async_session.execute(select(FunctionFact))).scalars()
+ assert (fact.ccn, fact.nloc, fact.params, fact.max_nesting) == (14, 50, None, None)
+
+
+# --- the migration ------------------------------------------------------------
+
+
+def _columns(db_path: Path, table: str) -> set[str]:
+ return {name for name, _notnull, _pk in _shape(db_path, table)[0]}
+
+
+def _shape(db_path: Path, table: str) -> tuple[set[tuple], set[tuple]]:
+ """``(name, notnull, pk)`` per column and ``(name, columns)`` per index."""
+ conn = sqlite3.connect(db_path)
+ try:
+ columns = {
+ (row[1], row[3], row[5]) for row in conn.execute(f'PRAGMA table_info("{table}")')
+ }
+ indexes = {
+ (name, tuple(r[2] for r in conn.execute(f'PRAGMA index_info("{name}")')))
+ for _seq, name, *_rest in conn.execute(f'PRAGMA index_list("{table}")')
+ if not name.startswith("sqlite_autoindex")
+ }
+ return columns, indexes
+ finally:
+ conn.close()
+
+
+def _alembic_config(db_path: Path):
+ from alembic.config import Config
+
+ root = Path(__file__).resolve().parents[3] / "packages" / "core"
+ config = Config()
+ config.set_main_option("script_location", str(root / "alembic"))
+ config.set_main_option("sqlalchemy.url", f"sqlite+aiosqlite:///{db_path}")
+ return config
+
+
+def test_the_migration_adds_and_drops_the_columns_and_table(tmp_path: Path) -> None:
+ from alembic import command
+
+ db_path = tmp_path / "wiki.db"
+ config = _alembic_config(db_path)
+ command.upgrade(config, "0105")
+ assert {"ccn", "nloc", "params", "max_nesting"} <= _columns(db_path, "function_facts")
+ assert "outcome" in _columns(db_path, "refactoring_payoffs")
+ command.downgrade(config, "0104")
+ assert "ccn" not in _columns(db_path, "function_facts")
+ assert _columns(db_path, "refactoring_payoffs") == set()
+
+
+def test_the_migration_and_the_model_agree(tmp_path: Path) -> None:
+ import asyncio
+
+ from alembic import command
+
+ from repowise.core.persistence.database import create_engine, init_db
+
+ migrated = tmp_path / "migrated.db"
+ command.upgrade(_alembic_config(migrated), "head")
+ declared = tmp_path / "declared.db"
+
+ async def _build() -> None:
+ engine = create_engine(f"sqlite+aiosqlite:///{declared}")
+ await init_db(engine)
+ await engine.dispose()
+
+ asyncio.run(_build())
+ for table in ("function_facts", "refactoring_payoffs"):
+ assert _shape(migrated, table) == _shape(declared, table)
diff --git a/tests/unit/server/test_refactoring.py b/tests/unit/server/test_refactoring.py
index 03204ceb5..abfaec86c 100644
--- a/tests/unit/server/test_refactoring.py
+++ b/tests/unit/server/test_refactoring.py
@@ -307,6 +307,37 @@ async def test_plan_detail_by_id(client: AsyncClient, app) -> None:
assert detail["plan"]["cut_edges"] == [{"from": "pkg/a.py", "to": "pkg/b.py"}]
+async def test_a_resolved_plan_detail_says_what_happened_to_it(client: AsyncClient, app) -> None:
+ from repowise.server.services.refactoring_health import RefactoringHealthService
+
+ repo_id = await _seed(client, app)
+ listed = (await client.get(f"/api/repos/{repo_id}/refactoring/targets")).json()["plans"]
+ open_plan = next(p for p in listed if p["refactoring_type"] == "extract_class")
+ assert "payoff" not in (await client.get(f"/api/repos/{repo_id}/refactoring/{open_plan['id']}")).json()
+
+ async with app.state.session_factory() as session:
+ # pkg/leaf.py is gone from the run that stops detecting its plan.
+ await crud.upsert_refactoring_suggestions(
+ session,
+ repo_id,
+ [],
+ file_paths=["pkg/leaf.py"],
+ payoff=crud.PayoffContext(fact_rows=[], is_live=lambda _path: False, commit="f00d"),
+ )
+ await session.commit()
+
+ detail = (await client.get(f"/api/repos/{repo_id}/refactoring/{open_plan['id']}")).json()
+ assert detail["payoff"]["outcome"] == "file_deleted"
+ assert detail["payoff"]["resolved_commit"] == "f00d"
+
+ async with app.state.session_factory() as session:
+ served = await RefactoringHealthService(session, repo_id, repo_id).plan_detail(
+ open_plan["id"]
+ )
+ assert served["plan"]["status"] == "resolved"
+ assert served["plan"]["payoff"]["outcome"] == "file_deleted"
+
+
async def test_an_unranked_plan_detail_serves_steps_without_verify(
client: AsyncClient, app
) -> None:
diff --git a/tests/unit/server/test_wire_vocabulary_parity.py b/tests/unit/server/test_wire_vocabulary_parity.py
index edbee086b..5c593d4a9 100644
--- a/tests/unit/server/test_wire_vocabulary_parity.py
+++ b/tests/unit/server/test_wire_vocabulary_parity.py
@@ -178,6 +178,12 @@ def test_refactoring_recipe_vocabularies_match_python() -> None:
assert _union_members("RecipePreconditionKind", "refactoring.ts") == set(PRECONDITION_KINDS)
+def test_refactoring_payoff_outcomes_match_python() -> None:
+ from repowise.core.analysis.health.refactoring.payoff import PAYOFF_OUTCOMES
+
+ assert _union_members("RefactoringPayoffOutcome", "refactoring.ts") == set(PAYOFF_OUTCOMES)
+
+
def _interface_body(name: str, module: str) -> str:
"""The text between `export interface <name> {` and its closing brace."""
text = (_TYPES_SRC / module).read_text(encoding="utf-8")