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.

refactor(core): split the helpers this week made too complex (#3545)

Raghav Chamadiya211004996c45
diff --git a/packages/core/src/repowise/core/agent_prompts/refactoring.py b/packages/core/src/repowise/core/agent_prompts/refactoring.py
index f874d7324..1426026c9 100644
--- a/packages/core/src/repowise/core/agent_prompts/refactoring.py
+++ b/packages/core/src/repowise/core/agent_prompts/refactoring.py
@@ -46,16 +46,34 @@ def _loc(file: Any, span: Mapping[str, int] | None) -> str:
def _symbol_lines(step: Mapping[str, Any]) -> list[str]:
"""What an Extract Method step adds: the texts to copy and the slots."""
symbol = step.get("new_symbol") or {}
- call = step.get("call_site") or {}
- span = call.get("replace_span") or step.get("span") or {}
+ out = _helper_text_lines(symbol)
+ replace = _replace_line(step)
+ if replace:
+ out.append(replace)
+ out.extend(_helper_io_lines(symbol))
+ return out
+
+
+def _helper_text_lines(symbol: Mapping[str, Any]) -> list[str]:
out = []
if symbol.get("signature_text"):
out.append(f"New helper: `{symbol['signature_text']}`")
if symbol.get("return_text"):
out.append(f"End the helper with: `{symbol['return_text']}`")
- if call.get("new_text"):
- lines = "the span" if step.get("anchors") else f"lines {span.get('start')}-{span.get('end')}"
- out.append(f"Replace {lines} with: `{call['new_text']}`")
+ return out
+
+
+def _replace_line(step: Mapping[str, Any]) -> str | None:
+ call = step.get("call_site") or {}
+ if not call.get("new_text"):
+ return None
+ span = call.get("replace_span") or step.get("span") or {}
+ lines = "the span" if step.get("anchors") else f"lines {span.get('start')}-{span.get('end')}"
+ return f"Replace {lines} with: `{call['new_text']}`"
+
+
+def _helper_io_lines(symbol: Mapping[str, Any]) -> list[str]:
+ out = []
if symbol:
out.append(f"Parameters (in): {', '.join(symbol.get('params') or []) or '(none)'}")
out.append(f"Returns (out): {', '.join(symbol.get('returns') or []) or '(nothing)'}")
diff --git a/packages/core/src/repowise/core/analysis/execution_roles.py b/packages/core/src/repowise/core/analysis/execution_roles.py
index 4080586cf..8bb77bf21 100644
--- a/packages/core/src/repowise/core/analysis/execution_roles.py
+++ b/packages/core/src/repowise/core/analysis/execution_roles.py
@@ -207,22 +207,26 @@ def _scan(graph: Any) -> _Scan:
path = attrs.get("file_path") or file_of_symbol(node)
scan.symbols.setdefault(path, []).append((node, attrs))
for source, target, data in graph.edges(data=True):
- edge_type = (data or {}).get("edge_type")
- if edge_type == "imports":
- root = _import_root(target)
- if root is not None:
- scan.imports.setdefault(source, set()).add(root)
- elif edge_type == "framework" and source.endswith("urls.py"):
- scan.url_targets.add(target)
- elif edge_type == "framework_binds":
- scan.binds.append((source, target))
- # A registry holding the function says nothing about how it runs.
- elif edge_type == "references" and (data or {}).get("hint_source") != REGISTRATION_HINT:
- scan.references.append((source, target))
- scan.referenced.add(target)
+ _scan_edge(scan, source, target, data or {})
return scan
+def _scan_edge(scan: _Scan, source: str, target: str, data: Mapping[str, Any]) -> None:
+ edge_type = data.get("edge_type")
+ if edge_type == "imports":
+ root = _import_root(target)
+ if root is not None:
+ scan.imports.setdefault(source, set()).add(root)
+ elif edge_type == "framework" and source.endswith("urls.py"):
+ scan.url_targets.add(target)
+ elif edge_type == "framework_binds":
+ scan.binds.append((source, target))
+ # A registry holding the function says nothing about how it runs.
+ elif edge_type == "references" and data.get("hint_source") != REGISTRATION_HINT:
+ scan.references.append((source, target))
+ scan.referenced.add(target)
+
+
def _decorator_role(decorators: Iterable[str], language: str) -> ExecutionRole | None:
for text in decorators:
if language == "python" and (any(flask_routes(text)) or _PY_REQUEST_DECORATOR.match(text)):
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py
index adcf5de80..263913560 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py
@@ -757,6 +757,26 @@ def _drop_hub_only(file_path: str, labels: set[str], keep: set[str]) -> set[str]
}
+def _inferred_target(
+ file_path: str, reached: ReachedBy | None, keep: set[str] | None
+) -> tuple[set[str], ValidationBasis, ValidationVia | None, int, bool]:
+ """Labels, basis, via, total and identity completeness from the inferred map."""
+ if reached is None:
+ return set(), "unknown", None, 0, True
+ labels = set(reached.all_tests or reached.tests)
+ basis: ValidationBasis = "inferred" if reached.total else "unknown"
+ via = reached.via if reached.total else None
+ total = reached.total
+ identities_complete = reached.all_tests is not None or total == len(labels)
+ if keep is not None:
+ labels = _drop_hub_only(file_path, labels, keep)
+ if identities_complete:
+ # The whole list was filtered, so what is left is the answer.
+ basis, via = ("inferred", via) if labels else ("unknown", None)
+ total = len(labels)
+ return labels, basis, via, total, identities_complete
+
+
def _validation_target(
file_path: str,
lines: set[int] | None,
@@ -776,19 +796,9 @@ def _validation_target(
identities_complete = True
else:
reached = inferred.get(file_path)
- labels = set(reached.all_tests or reached.tests) if reached is not None else set()
- basis = "inferred" if reached is not None and reached.total else "unknown"
- via = reached.via if reached is not None and reached.total else None
- total = reached.total if reached is not None else 0
- identities_complete = (
- reached is None or reached.all_tests is not None or total == len(labels)
+ labels, basis, via, total, identities_complete = _inferred_target(
+ file_path, reached, keep
)
- if keep is not None and reached is not None:
- labels = _drop_hub_only(file_path, labels, keep)
- if identities_complete:
- # The whole list was filtered, so what is left is the answer.
- basis, via = ("inferred", via) if labels else ("unknown", None)
- total = len(labels)
ranked = rank(labels, covered, reached)
ordered = sorted(labels, key=lambda label: (ranked[label][0], label))
return (
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 e43a5fbbe..3a7ae180d 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py
@@ -34,6 +34,8 @@ from ...sql import rule_predicate
from .._shared import _BATCH_SIZE, _finding_file_path
if TYPE_CHECKING:
+ from datetime import datetime
+
from .refactoring_payoff import PayoffContext
# The finding-triage vocabulary, shared with health findings so Code Health has
@@ -167,6 +169,88 @@ def _scope_suggestions(
]
+async def _reusable_rows(
+ session: AsyncSession,
+ repository_id: str,
+ stored_rows: list[RefactoringSuggestion],
+ public_ids: list[str],
+ model_version: int,
+) -> dict[str, RefactoringSuggestion]:
+ """Stored current-model rows by public id, the scoped ones and any named elsewhere."""
+ reusable: dict[str, RefactoringSuggestion] = {}
+ for row in stored_rows:
+ if row.public_id and row.model_version == model_version:
+ reusable[row.public_id] = row
+
+ # A clone group and an import cycle are named by their members rather than
+ # by the file the row happens to be anchored at, so a scoped run can hold a
+ # plan whose stored row sits outside the scope. Look those up by id before
+ # deciding anything is new: inserting instead would duplicate the plan, and
+ # the identity is unique per repository and model.
+ outside = sorted({pid for pid in public_ids if pid not in reusable})
+ for index in range(0, len(outside), _BATCH_SIZE):
+ found = await session.execute(
+ select(RefactoringSuggestion).where(
+ RefactoringSuggestion.repository_id == repository_id,
+ RefactoringSuggestion.model_version == model_version,
+ RefactoringSuggestion.public_id.in_(outside[index : index + _BATCH_SIZE]),
+ )
+ )
+ for row in found.scalars().all():
+ reusable.setdefault(row.public_id, row)
+ return reusable
+
+
+def _refresh_detected_row(
+ row: RefactoringSuggestion,
+ suggestion: Any,
+ repository_id: str,
+ public_id: str,
+ now: datetime,
+) -> bool:
+ """Refresh a detected-again row in place. True when it reopened."""
+ values = _refactoring_row_kwargs(suggestion, repository_id, public_id=public_id)
+ for name in _REFRESHED_COLUMNS:
+ if name in values:
+ setattr(row, name, values[name])
+ # Unranked until the finalizer ranks the refreshed content; a finalize
+ # that fails then leaves no stale rank beside fresh fields.
+ row.rank_position = row.blast_size = row.rank_json = None
+ reopened = row.status == "resolved" and row.status_reason == "no_longer_detected"
+ if reopened:
+ row.status = "open"
+ row.status_reason = None
+ row.status_changed_at = now
+ row.updated_at = now
+ return reopened
+
+
+def _resolve_undetected_rows(
+ stored_rows: list[RefactoringSuggestion],
+ seen: set[str],
+ now: datetime,
+ model_version: int,
+) -> list[RefactoringSuggestion]:
+ """Resolve every open stored row this run did not detect.
+
+ Returns the current-model ones, the rows a payoff is settled for.
+ """
+ resolved: list[RefactoringSuggestion] = []
+ for row in stored_rows:
+ if row.public_id in seen and row.model_version == model_version:
+ 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 == model_version:
+ resolved.append(row)
+ row.status = "resolved"
+ row.status_reason = "no_longer_detected"
+ row.status_changed_at = now
+ row.updated_at = now
+ return resolved
+
+
async def finalize_refactoring_suggestions(
session: AsyncSession,
repository_id: str,
@@ -229,33 +313,14 @@ async def finalize_refactoring_suggestions(
.scalars()
.all()
)
- reusable: dict[str, RefactoringSuggestion] = {}
- for row in stored_rows:
- if row.public_id and row.model_version == REFACTORING_MODEL_VERSION:
- reusable[row.public_id] = row
-
- # A clone group and an import cycle are named by their members rather than
- # by the file the row happens to be anchored at, so a scoped run can hold a
- # plan whose stored row sits outside the scope. Look those up by id before
- # deciding anything is new: inserting instead would duplicate the plan, and
- # the identity is unique per repository and model.
- outside = sorted({pid for pid in public_ids if pid not in reusable})
- for index in range(0, len(outside), _BATCH_SIZE):
- found = await session.execute(
- select(RefactoringSuggestion).where(
- RefactoringSuggestion.repository_id == repository_id,
- RefactoringSuggestion.model_version == REFACTORING_MODEL_VERSION,
- RefactoringSuggestion.public_id.in_(outside[index : index + _BATCH_SIZE]),
- )
- )
- for row in found.scalars().all():
- reusable.setdefault(row.public_id, row)
+ reusable = await _reusable_rows(
+ session, repository_id, stored_rows, public_ids, REFACTORING_MODEL_VERSION
+ )
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
@@ -273,32 +338,10 @@ async def finalize_refactoring_suggestions(
continue
if row.status == "false_positive":
continue
- values = _refactoring_row_kwargs(suggestion, repository_id, public_id=public_id)
- for name in _REFRESHED_COLUMNS:
- if name in values:
- setattr(row, name, values[name])
- # Unranked until the finalizer ranks the refreshed content; a finalize
- # that fails then leaves no stale rank beside fresh fields.
- row.rank_position = row.blast_size = row.rank_json = None
- if row.status == "resolved" and row.status_reason == "no_longer_detected":
- row.status = "open"
- row.status_reason = None
- row.status_changed_at = now
+ if _refresh_detected_row(row, suggestion, repository_id, public_id, now):
reopened.append(row.id)
- row.updated_at = now
- for row in stored_rows:
- if row.public_id in seen and row.model_version == REFACTORING_MODEL_VERSION:
- 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
- row.updated_at = now
+ resolved = _resolve_undetected_rows(stored_rows, seen, now, REFACTORING_MODEL_VERSION)
for index in range(0, len(pending), _BATCH_SIZE):
for row in pending[index : index + _BATCH_SIZE]:
diff --git a/packages/core/src/repowise/core/persistence/database.py b/packages/core/src/repowise/core/persistence/database.py
index 4a8e4065d..811cc191c 100644
--- a/packages/core/src/repowise/core/persistence/database.py
+++ b/packages/core/src/repowise/core/persistence/database.py
@@ -17,6 +17,7 @@ import warnings
from collections.abc import AsyncGenerator, Callable
from contextlib import asynccontextmanager
from pathlib import Path
+from typing import Any
import structlog
from sqlalchemy import String, event, inspect, literal
@@ -515,6 +516,43 @@ def _loosen_postgres_columns(table: object, live: dict[str, dict], dialect: obje
return statements
+def _reconcile_columns(
+ connection: object,
+ inspector: Any,
+ table: Any,
+ run: Callable[[str, Callable[[], object]], None],
+ failures: list[tuple[str, Exception]],
+) -> None:
+ """Loosen and add one existing table's columns (see :func:`_reconcile_schema`)."""
+ dialect = connection.dialect # type: ignore[attr-defined]
+ # Render the column DDL fragment exactly as SQLAlchemy would emit
+ # it inside CREATE TABLE — preserves type, server_default, and
+ # nullability. We deliberately do NOT enforce FK constraints on
+ # back-filled columns: SQLite can't add an enforced FK after the
+ # fact, and write-time enforcement is sufficient for our purposes.
+ # The Alembic-only pgvector column triggers an unknown-type warning.
+ with warnings.catch_warnings():
+ if dialect.name == "postgresql": # type: ignore[attr-defined]
+ warnings.filterwarnings("ignore", message="Did not recognize type 'vector'")
+ db_cols = {c["name"]: c for c in inspector.get_columns(table.name)}
+ if dialect.name == "postgresql": # type: ignore[attr-defined]
+ for what, statement in _loosen_postgres_columns(table, db_cols, dialect):
+ run(what, lambda statement=statement: statement)
+ for column in table.columns:
+ if column.name in db_cols:
+ continue
+ what = f"{table.name}.{column.name}"
+ run(
+ what,
+ lambda table=table, column=column: text(
+ f'ALTER TABLE "{table.name}" ADD COLUMN {_add_column_ddl(column, dialect)}'
+ ),
+ )
+ data_step = _DATA_STEPS_ON_ADD.get(what)
+ if data_step is not None and not any(name == what for name, _ in failures):
+ run(f"{what}:data", lambda data_step=data_step: _run_data_step(data_step, connection))
+
+
def _reconcile_schema(connection: object) -> None:
"""Bring an existing database up to ``Base.metadata`` (additive only).
@@ -602,33 +640,7 @@ def _reconcile_schema(connection: object) -> None:
# reconcile a brand-new table column-by-column.
continue
- # --- Columns ---------------------------------------------------
- # Render the column DDL fragment exactly as SQLAlchemy would emit
- # it inside CREATE TABLE — preserves type, server_default, and
- # nullability. We deliberately do NOT enforce FK constraints on
- # back-filled columns: SQLite can't add an enforced FK after the
- # fact, and write-time enforcement is sufficient for our purposes.
- # The Alembic-only pgvector column triggers an unknown-type warning.
- with warnings.catch_warnings():
- if dialect.name == "postgresql": # type: ignore[attr-defined]
- warnings.filterwarnings("ignore", message="Did not recognize type 'vector'")
- db_cols = {c["name"]: c for c in inspector.get_columns(table.name)}
- if dialect.name == "postgresql": # type: ignore[attr-defined]
- for what, statement in _loosen_postgres_columns(table, db_cols, dialect):
- _run(what, lambda statement=statement: statement)
- for column in table.columns:
- if column.name in db_cols:
- continue
- what = f"{table.name}.{column.name}"
- _run(
- what,
- lambda table=table, column=column: text(
- f'ALTER TABLE "{table.name}" ADD COLUMN {_add_column_ddl(column, dialect)}'
- ),
- )
- data_step = _DATA_STEPS_ON_ADD.get(what)
- if data_step is not None and not any(name == what for name, _ in failures):
- _run(f"{what}:data", lambda data_step=data_step: _run_data_step(data_step, connection))
+ _reconcile_columns(connection, inspector, table, _run, failures)
# --- Nullability (SQLite only) -----------------------------------
# After the columns, so the copy carries every one of them, and before