Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(refactoring): give plans a versioned identity and a real lifecycle (#1986)
Raghav Chamadiyaa4285a206a39
diff --git a/packages/core/alembic/versions/0058_refactoring_identity_lifecycle.py b/packages/core/alembic/versions/0058_refactoring_identity_lifecycle.pynew file mode 100644index 000000000..95c158be1--- /dev/null+++ b/packages/core/alembic/versions/0058_refactoring_identity_lifecycle.py@@ -0,0 +1,80 @@+"""Give refactoring plans a versioned identity and a real lifecycle.++Plan rows were replaced wholesale on every analysis, so an id an agent quoted+stopped resolving on the next update and a dismissal had nowhere to live. This+adds the content-derived public id, the model that minted it, the triage reason+and timestamp, and the indexes that let a page be served without loading every+open plan.++Every column is nullable or defaulted and every index is additive, so an+existing store upgrades without a rewrite and repopulates on its next analysis.++Revision ID: 0058+Revises: 0057+Create Date: 2026-08-29+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++revision: str = "0058"+down_revision: str | None = "0057"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++_SUGGESTION_INDEXES = (+ ("ix_refactoring_suggestions_repo_status", ["repository_id", "status"]),+ (+ "ix_refactoring_suggestions_repo_status_type",+ ["repository_id", "status", "refactoring_type"],+ ),+ (+ "ix_refactoring_suggestions_repo_status_path",+ ["repository_id", "status", "file_path"],+ ),+)++_UNIQUE_NAME = "uq_refactoring_suggestions_repo_model_public_id"+++def upgrade() -> None:+ op.add_column("refactoring_suggestions", sa.Column("public_id", sa.String(64), nullable=True))+ op.add_column(+ "refactoring_suggestions",+ sa.Column("model_version", sa.Integer(), nullable=False, server_default="0"),+ )+ op.add_column(+ "refactoring_suggestions", sa.Column("status_reason", sa.String(32), nullable=True)+ )+ op.add_column(+ "refactoring_suggestions",+ sa.Column("status_changed_at", sa.DateTime(timezone=True), nullable=True),+ )+ for name, columns in _SUGGESTION_INDEXES:+ op.create_index(name, "refactoring_suggestions", columns, if_not_exists=True)+ # Uniqueness is (repository, model, public id), never the id alone: two+ # models may legitimately name the same plan differently, and a row from an+ # older model keeps answering until the writer resolves it. A unique index+ # rather than a table constraint, because SQLite cannot add a constraint to+ # an existing table without rebuilding it.+ op.create_index(+ _UNIQUE_NAME,+ "refactoring_suggestions",+ ["repository_id", "model_version", "public_id"],+ unique=True,+ if_not_exists=True,+ )+++def downgrade() -> None:+ op.drop_index(_UNIQUE_NAME, table_name="refactoring_suggestions", if_exists=True)+ for name, _columns in _SUGGESTION_INDEXES:+ op.drop_index(name, table_name="refactoring_suggestions", if_exists=True)+ op.drop_column("refactoring_suggestions", "status_changed_at")+ op.drop_column("refactoring_suggestions", "status_reason")+ op.drop_column("refactoring_suggestions", "model_version")+ op.drop_column("refactoring_suggestions", "public_id")diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py b/packages/core/src/repowise/core/analysis/health/refactoring/__init__.pyindex 884620d32..7d4708b5d 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py@@ -22,6 +22,13 @@ from . import (split_file, # noqa: F401 (import-for-side-effect))from .graph_signals import build_file_scc_index+from .identity import (+ REFACTORING_MODEL_VERSION,+ assign_public_ids,+ model_state,+ refactoring_kernel,+ refactoring_public_id,+)from .models import (CONFIDENCE_LEVELS,RefactoringContext,@@ -39,15 +46,20 @@ from .registry import (__all__ = ["CONFIDENCE_LEVELS",+ "REFACTORING_MODEL_VERSION","PerformancePlanPolicy","RefactoringContext","RefactoringDetector","RefactoringSuggestion",+ "assign_public_ids","build_file_scc_index","detect_refactorings","effort_bucket",+ "model_state","performance_fix_suggestions","rank_suggestions",+ "refactoring_kernel",+ "refactoring_public_id","register","registered_detectors",]diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/identity.py b/packages/core/src/repowise/core/analysis/health/refactoring/identity.pynew file mode 100644index 000000000..6acc61b16--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/refactoring/identity.py@@ -0,0 +1,333 @@+"""Versioned content identity for refactoring plans.++A plan's public id is derived from what the plan *is*, never from where the row+landed in storage. Two consecutive analyses of unchanged source must produce the+same string, so an agent that quoted an id yesterday can still resolve it, and a+dismissal recorded against it still suppresses the same plan.++The kernel is therefore built per refactoring type out of that type's stable+anchors - symbol names, clone content, group membership - and never out of line+numbers, prose, ranking, effort or confidence. Moving a function down a file+must not mint a new plan; changing what the plan asks you to do must.++The kernel's inputs are a contract. Adding a fact must not change them; changing+them means bumping :data:`REFACTORING_MODEL_VERSION`, which makes every stored id+self-describing as stale rather than silently wrong.+"""++from __future__ import annotations++import hashlib+import json+import re+from typing import Any++REFACTORING_MODEL_VERSION = 2+"""Version of the identity semantics. v1 was the fresh-UUID-per-index era.++The version is the id prefix rather than a hash input, so a stale id is+recognisable from the string alone. Moving this constant means bumping+``HEALTH_ANALYZER_VERSION`` with it, which forces the reanalysis that restamps+every stored plan.+"""++RefactoringKernel = tuple[Any, ...]++_ID_PREFIX = "refac"+_ID_PATTERN = re.compile(rf"^{_ID_PREFIX}(\d*)_[0-9a-f]{{20}}$")++_DIGEST_CHARS = 20+++def _plan_of(suggestion: Any) -> dict:+ """The plan payload, whether this is a dataclass, a dict or an ORM row."""+ plan = getattr(suggestion, "plan", None)+ if plan is None and isinstance(suggestion, dict):+ plan = suggestion.get("plan")+ if plan is None:+ raw = getattr(suggestion, "plan_json", None)+ if raw is None and isinstance(suggestion, dict):+ raw = suggestion.get("plan_json")+ try:+ plan = json.loads(raw or "{}")+ except (TypeError, ValueError):+ plan = {}+ return plan if isinstance(plan, dict) else {}+++def _evidence_of(suggestion: Any) -> dict:+ evidence = getattr(suggestion, "evidence", None)+ if evidence is None and isinstance(suggestion, dict):+ evidence = suggestion.get("evidence")+ if evidence is None:+ raw = getattr(suggestion, "evidence_json", None)+ if raw is None and isinstance(suggestion, dict):+ raw = suggestion.get("evidence_json")+ try:+ evidence = json.loads(raw or "{}")+ except (TypeError, ValueError):+ evidence = {}+ return evidence if isinstance(evidence, dict) else {}+++def _field(suggestion: Any, name: str, default: Any = None) -> Any:+ if isinstance(suggestion, dict):+ return suggestion.get(name, default)+ return getattr(suggestion, name, default)+++def _span_length(suggestion: Any) -> int | None:+ """Span size, which survives the whole block moving down the file."""+ start = _field(suggestion, "line_start")+ end = _field(suggestion, "line_end")+ if isinstance(start, int) and isinstance(end, int):+ return end - start+ return None+++def _text_digest(text: str) -> str:+ """Content digest of a source block, insensitive to trailing whitespace."""+ normalized = "\n".join(line.rstrip() for line in text.splitlines())+ return hashlib.sha256(normalized.encode("utf-8")).hexdigest()[:16]+++def _clone_kernel(suggestion: Any) -> RefactoringKernel:+ """A clone group is named by the duplicated block and where it occurs.++ Deliberately excludes ``file_path``: that column names the anchor+ occurrence, and the anchor moves to the smallest surviving site whenever a+ sibling occurrence is filtered out. The occurrence set is the identity.+ """+ plan = _plan_of(suggestion)+ evidence = _evidence_of(suggestion)+ occurrences = plan.get("occurrences") or []+ files = sorted(+ str(item.get("file", "")) for item in occurrences if isinstance(item, dict)+ )+ snippet = plan.get("snippet")+ return (+ "extract_helper",+ _text_digest(snippet) if isinstance(snippet, str) else None,+ tuple(files),+ len(occurrences),+ evidence.get("token_count"),+ plan.get("duplicated_lines"),+ )+++def _cycle_kernel(suggestion: Any) -> RefactoringKernel:+ """A cycle is named by its members and the cut, not by a representative file."""+ plan = _plan_of(suggestion)+ cycle = plan.get("cycle") or []+ cuts = plan.get("cut_edges") or []+ return (+ "break_cycle",+ tuple(sorted(str(member) for member in cycle)),+ tuple(+ sorted(+ (str(edge.get("from", "")), str(edge.get("to", "")))+ for edge in cuts+ if isinstance(edge, dict)+ )+ ),+ )+++def _extract_class_kernel(suggestion: Any, file_path: str) -> RefactoringKernel:+ """A class split is named by the class and by the clusters it proposes.++ The class name alone would hold still while the proposed split changed under+ it, so an id an agent quoted for one extraction would answer with another.+ """+ plan = _plan_of(suggestion)+ groups = plan.get("groups") or []+ membership = sorted(+ (+ tuple(sorted(str(name) for name in (group.get("methods") or []))),+ tuple(sorted(str(name) for name in (group.get("fields") or []))),+ )+ for group in groups+ if isinstance(group, dict)+ )+ return (+ "extract_class",+ file_path,+ _field(suggestion, "target_symbol") or "",+ tuple(membership),+ )+++def _split_kernel(suggestion: Any, file_path: str) -> RefactoringKernel:+ """A split is named by its group membership; suggested filenames are advice."""+ plan = _plan_of(suggestion)+ groups = plan.get("groups") or []+ membership = sorted(+ tuple(sorted(str(symbol) for symbol in (group.get("symbols") or [])))+ for group in groups+ if isinstance(group, dict)+ )+ return ("split_file", file_path, tuple(membership))+++def _extract_method_kernel(suggestion: Any, file_path: str) -> RefactoringKernel:+ """An extraction is named by its host function and the signature it lifts.++ The span itself is line-based, so only its length participates. Two spans in+ one function that agree on signature and length collide; :func:`assign_public_ids`+ breaks that tie deterministically rather than letting the ids merge.+ """+ plan = _plan_of(suggestion)+ return (+ "extract_method",+ file_path,+ _field(suggestion, "target_symbol") or "",+ tuple(str(name) for name in (plan.get("params") or [])),+ tuple(str(name) for name in (plan.get("returns") or [])),+ _span_length(suggestion),+ )+++def _move_method_kernel(suggestion: Any, file_path: str) -> RefactoringKernel:+ plan = _plan_of(suggestion)+ return (+ "move_method",+ file_path,+ str(plan.get("method") or ""),+ str(plan.get("from_class") or ""),+ str(plan.get("to_class") or ""),+ )+++def _generic_kernel(kind: str, suggestion: Any, file_path: str) -> RefactoringKernel:+ """The degrade path for a type with no declared anchor.++ Deterministic and content-derived, but span-length sensitive, so a future+ detector that lands here without its own branch gets a working id rather+ than a wrong one. New types should add a branch.+ """+ return (+ kind,+ file_path,+ _field(suggestion, "target_symbol") or "",+ _span_length(suggestion),+ )+++def refactoring_kernel(suggestion: Any) -> RefactoringKernel:+ """The identity kernel for one plan.++ Accepts a detector dataclass, a plain dict, or a persisted ORM row: the+ three describe the same plan and must reach the same string.+ """+ kind = str(_field(suggestion, "refactoring_type") or "")+ file_path = str(_field(suggestion, "file_path") or "")+ biomarker = str(_field(suggestion, "source_biomarker") or "")++ if kind == "performance_fix":+ # The performance layer already owns a versioned causal id for this+ # plan and persists it in the plan payload; deriving a second one here+ # would let the two disagree about the same row.+ return ("performance_fix", str(_plan_of(suggestion).get("opportunity_id") or ""))+ if kind == "extract_helper":+ return _clone_kernel(suggestion)+ if kind == "break_cycle":+ return _cycle_kernel(suggestion)+ if kind == "split_file":+ return (*_split_kernel(suggestion, file_path), biomarker)+ if kind == "extract_method":+ return (*_extract_method_kernel(suggestion, file_path), biomarker)+ if kind == "move_method":+ return (*_move_method_kernel(suggestion, file_path), biomarker)+ if kind == "extract_class":+ return (*_extract_class_kernel(suggestion, file_path), biomarker)+ return (*_generic_kernel(kind, suggestion, file_path), biomarker)+++def stable_id(kernel: RefactoringKernel, *, ordinal: int = 0) -> str:+ """Hash a kernel into the public id.++ *ordinal* disambiguates plans whose kernels genuinely coincide; it is 0 for+ the overwhelming majority and never appears in the string.+ """+ payload = json.dumps(+ [kernel, ordinal] if ordinal else kernel,+ separators=(",", ":"),+ ensure_ascii=True,+ default=str,+ )+ digest = hashlib.sha256(payload.encode("utf-8")).hexdigest()[:_DIGEST_CHARS]+ return f"{_ID_PREFIX}{REFACTORING_MODEL_VERSION}_{digest}"+++def refactoring_public_id(suggestion: Any) -> str:+ """The public id for one plan, with no collision context available.++ Single-row callers (a plan written on its own, a lookup rebuilding an id to+ compare) use this. Batch writers use :func:`assign_public_ids`, which can+ see collisions and break them.+ """+ return stable_id(refactoring_kernel(suggestion))+++def assign_public_ids(suggestions: list[Any]) -> list[str]:+ """Public ids for a whole batch, positionally aligned with *suggestions*.++ Kernels that coincide are ordered by their coordinates and given ascending+ ordinals, so the assignment is a function of the batch's content rather than+ of iteration order. A uniform line shift preserves that order, so the ids+ hold; adding or removing a colliding sibling renumbers the ones after it,+ which is the honest outcome of the group having changed.+ """+ kernels = [refactoring_kernel(item) for item in suggestions]+ positions: dict[RefactoringKernel, list[int]] = {}+ for index, kernel in enumerate(kernels):+ positions.setdefault(kernel, []).append(index)++ ids: list[str] = [""] * len(suggestions)+ for kernel, members in positions.items():+ if len(members) == 1:+ ids[members[0]] = stable_id(kernel)+ continue+ ordered = sorted(+ members,+ key=lambda index: (+ str(_field(suggestions[index], "file_path") or ""),+ _field(suggestions[index], "line_start") or 0,+ str(_field(suggestions[index], "target_symbol") or ""),+ ),+ )+ for ordinal, index in enumerate(ordered):+ ids[index] = stable_id(kernel, ordinal=ordinal)+ return ids+++def public_id_model_version(public_id: str) -> int | None:+ """Which model minted this id, or nothing if it was not minted here."""+ match = _ID_PATTERN.match(public_id or "")+ if match is None:+ return None+ return int(match.group(1)) if match.group(1) else 1+++def model_state(public_id: str) -> dict[str, Any]:+ """Whether an id can still be resolved, and what to do when it cannot.++ Ids are not translated across models: a kernel change can split or merge+ what an older id named, and an alias would have to invent which one the+ caller meant. Naming the mismatch and the refresh that fixes it is the only+ honest answer.+ """+ version = public_id_model_version(public_id)+ if version == REFACTORING_MODEL_VERSION:+ state = "current"+ elif version is None:+ state = "unrecognized"+ else:+ state = "stale_model"+ return {+ "state": state,+ "public_id": public_id,+ "requested_model_version": version,+ "refactoring_model_version": REFACTORING_MODEL_VERSION,+ "refresh_required": state == "stale_model",+ }diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.pyindex 895bb2746..5a67f9b80 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py@@ -67,9 +67,12 @@ from .performance import (performance_facet_counts,)from .refactoring import (+ count_refactoring_suggestions,+ finalize_refactoring_suggestions,get_refactoring_suggestion,get_refactoring_suggestions,save_refactoring_suggestions,+ update_refactoring_suggestion_status,upsert_refactoring_suggestions,)@@ -79,9 +82,11 @@ __all__ = ["HealthSnapshotHeadline","HealthSnapshotScalars","backfill_module_attribution",+ "count_refactoring_suggestions","covered_source_files","files_covered_by","finalize_performance_opportunities",+ "finalize_refactoring_suggestions","get_average_health","get_coverage_summary","get_dead_code_findings",@@ -122,6 +127,7 @@ __all__ = ["tests_covering_files","update_dead_code_status","update_health_finding_status",+ "update_refactoring_suggestion_status","upsert_health_findings","upsert_health_metrics","upsert_refactoring_suggestions",diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.pyindex 87b6c932b..f57bd8ac2 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py@@ -1,21 +1,63 @@-"""CRUD operations for refactoring suggestions (repowise persistence layer)."""+"""CRUD operations for refactoring suggestions (repowise persistence layer).++One writer owns lifecycle. :func:`finalize_refactoring_suggestions` reconciles a+detector run against what is stored: a plan whose content is unchanged keeps its+row, its id and whatever a person decided about it; a plan nobody detects any+more is resolved rather than deleted, so an id an agent is holding keeps+answering; and a plan someone called a false positive is never re-emitted. The+full and incremental index paths differ only in the scope they hand it, which is+what makes them agree.+"""from __future__ import annotationsimport jsonfrom typing import Any-from sqlalchemy import select+from sqlalchemy import func, selectfrom sqlalchemy.ext.asyncio import AsyncSession-from ...models import RefactoringSuggestion, _new_uuid+from ...models import RefactoringSuggestion, _new_uuid, _now_utcfrom .._shared import _BATCH_SIZE, _finding_file_path+# 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")++# Owned end to end by ``crud/analysis/performance.py``, which rebuilds these+# rows from the merged stored findings once per index on both paths.+_PERFORMANCE_TYPE = "performance_fix"++# Columns the writer refreshes on an unchanged plan. Everything absent here -+# id, public_id, model_version, status, status_reason, created_at - is either+# identity or a decision, and belongs to the row rather than to the run.+_REFRESHED_COLUMNS = (+ "file_path",+ "target_symbol",+ "line_start",+ "line_end",+ "plan_json",+ "evidence_json",+ "impact_delta",+ "effort_bucket",+ "blast_radius_json",+ "confidence",+ "source_biomarker",+ "opportunity_id",+)+-def _refactoring_row_kwargs(suggestion: Any, repository_id: str) -> dict:+def _refactoring_row_kwargs(+ suggestion: Any, repository_id: str, *, public_id: str | None = None+) -> dict:"""Normalize a ``RefactoringSuggestion`` dataclass or a plain dict intokwargs for the ORM row (folding the open ``plan`` / ``evidence`` /``blast_radius`` dicts into their ``*_json`` columns)."""+ from ....analysis.health.refactoring.identity import (+ REFACTORING_MODEL_VERSION,+ refactoring_public_id,+ )+if hasattr(suggestion, "refactoring_type"):data = {"refactoring_type": suggestion.refactoring_type,@@ -48,6 +90,9 @@ def _refactoring_row_kwargs(suggestion: Any, repository_id: str) -> dict:if isinstance(plan, dict) and isinstance(plan.get("opportunity_id"), str):data.setdefault("opportunity_id", plan["opportunity_id"])+ data["public_id"] = public_id or refactoring_public_id(suggestion)+ data["model_version"] = REFACTORING_MODEL_VERSION+return {"id": _new_uuid(),"repository_id": repository_id,@@ -59,31 +104,185 @@ def _refactoring_row_kwargs(suggestion: Any, repository_id: str) -> dict:}-async def save_refactoring_suggestions(+def _scope_predicates(+ repository_id: str,+ *,+ file_paths: list[str] | None,+ refactoring_type: str | None,+) -> list[Any]:+ predicates: list[Any] = [RefactoringSuggestion.repository_id == repository_id]+ if file_paths is not None:+ predicates.append(RefactoringSuggestion.file_path.in_(file_paths))+ if refactoring_type is not None:+ predicates.append(RefactoringSuggestion.refactoring_type == refactoring_type)+ else:+ # Performance plans are the performance finalizer's rows: it rebuilds+ # them from the merged stored findings on both index paths. Reconciling+ # them here would resolve live plans this call was simply never told+ # about, and today only the finalizer running moments later hides it.+ predicates.append(RefactoringSuggestion.refactoring_type != _PERFORMANCE_TYPE)+ return predicates+++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)+ ]+++async def finalize_refactoring_suggestions(session: AsyncSession,repository_id: str,suggestions: list[Any],-) -> None:- """Replace open refactoring suggestions for *repository_id*.+ *,+ file_paths: list[str] | None = None,+ refactoring_type: str | None = None,+) -> int:+ """Reconcile a detector run against the stored plans. Returns rows left open.++ *file_paths* scopes the reconciliation to the files an incremental run+ touched; ``None`` means the whole repository, which is what a full index+ hands it. *refactoring_type* narrows it further for a type-scoped partial+ run. Everything outside the scope is left exactly as it was, and so are+ ``performance_fix`` rows unless they are named explicitly: the performance+ finalizer rebuilds those from the merged stored findings on both paths.- Delete-then-insert, mirroring ``save_health_findings``. Accepts- ``RefactoringSuggestion`` dataclasses or plain dicts.+ Lifecycle:++ - a stored plan whose kernel is detected again keeps its row, its public id,+ its ``created_at`` and its triage state, and has its mutable fields+ refreshed;+ - a plan an earlier run resolved and this one detects again reopens, because+ the detector disagreeing with ``no_longer_detected`` is the whole signal.+ A plan a person resolved stays resolved;+ - a ``false_positive`` kernel is never re-emitted;+ - a stored plan nobody detected becomes ``resolved`` with reason+ ``no_longer_detected`` rather than being deleted, so a held id keeps+ 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."""- existing = await session.execute(- select(RefactoringSuggestion).where(- RefactoringSuggestion.repository_id == repository_id,- RefactoringSuggestion.status == "open",+ from ....analysis.health.refactoring.identity import (+ REFACTORING_MODEL_VERSION,+ assign_public_ids,+ )++ allowed = set(file_paths) if file_paths is not None else None+ scoped = _scope_suggestions(+ suggestions, allowed=allowed, refactoring_type=refactoring_type+ )+ public_ids = assign_public_ids(scoped)++ stored_rows = list(+ (+ await session.execute(+ select(RefactoringSuggestion).where(+ *_scope_predicates(+ repository_id,+ file_paths=file_paths,+ refactoring_type=refactoring_type,+ )+ )+ ))+ .scalars()+ .all())- for row in existing.scalars().all():- await session.delete(row)- await session.flush()+ 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)++ now = _now_utc()+ seen: set[str] = set()+ pending: 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+ # on. assign_public_ids breaks kernel collisions, so reaching here+ # means the detector emitted the same plan twice; keep the first.+ continue+ seen.add(public_id)+ row = reusable.get(public_id)+ if row is None:+ pending.append(+ RefactoringSuggestion(+ **_refactoring_row_kwargs(suggestion, repository_id, public_id=public_id)+ )+ )+ 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])+ if row.status == "resolved" and row.status_reason == "no_longer_detected":+ row.status = "open"+ row.status_reason = None+ row.status_changed_at = now+ row.updated_at = now- for i in range(0, len(suggestions), _BATCH_SIZE):- batch = suggestions[i : i + _BATCH_SIZE]- for s in batch:- session.add(RefactoringSuggestion(**_refactoring_row_kwargs(s, repository_id)))+ 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+ row.status = "resolved"+ row.status_reason = "no_longer_detected"+ row.status_changed_at = now+ row.updated_at = now++ for index in range(0, len(pending), _BATCH_SIZE):+ for row in pending[index : index + _BATCH_SIZE]:+ session.add(row)await session.flush()+ await session.flush()++ return sum(1 for row in stored_rows if row.status == "open") + len(pending)+++async def save_refactoring_suggestions(+ session: AsyncSession,+ repository_id: str,+ suggestions: list[Any],+) -> 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)async def upsert_refactoring_suggestions(@@ -94,43 +293,49 @@ async def upsert_refactoring_suggestions(file_paths: list[str],refactoring_type: str | None = None,) -> None:- """Replace open suggestions **only for the given file paths**.+ """Reconcile suggestions **only for the given file paths**.The incremental ``repowise update`` sibling of``save_refactoring_suggestions``: unchanged files keep their suggestions.Pass the full set of *changed* paths (not just those that produced a- suggestion) so a changed-but-now-clean file is cleared.+ suggestion) so a changed-but-now-clean file is resolved."""if not file_paths:return- allowed = set(file_paths)- predicates = [- RefactoringSuggestion.repository_id == repository_id,- RefactoringSuggestion.status == "open",- RefactoringSuggestion.file_path.in_(file_paths),- ]- if refactoring_type is not None:- predicates.append(RefactoringSuggestion.refactoring_type == refactoring_type)- existing = await session.execute(select(RefactoringSuggestion).where(*predicates))- for row in existing.scalars().all():- await session.delete(row)- await session.flush()+ await finalize_refactoring_suggestions(+ session,+ repository_id,+ suggestions,+ file_paths=list(file_paths),+ refactoring_type=refactoring_type,+ )- scoped = [- s- for s in suggestions- if _finding_file_path(s) in allowed- and (- refactoring_type is None- or (s.refactoring_type if hasattr(s, "refactoring_type") else s.get("refactoring_type"))- == refactoring_type- )- ]- for i in range(0, len(scoped), _BATCH_SIZE):- batch = scoped[i : i + _BATCH_SIZE]- for s in batch:- session.add(RefactoringSuggestion(**_refactoring_row_kwargs(s, repository_id)))- await session.flush()++async def update_refactoring_suggestion_status(+ session: AsyncSession,+ repository_id: str,+ suggestion_id: str,+ status: str,+ *,+ reason: str = "user",+) -> RefactoringSuggestion | None:+ """Transition one plan's lifecycle state. The single owner of that write.++ *suggestion_id* is the storage id or the content-derived public id, because+ the two surfaces that address a plan quote different strings. Returns+ ``None`` when the id is unknown or belongs to another repository, and raises+ ``ValueError`` for a status outside the triage vocabulary.+ """+ if status not in ALLOWED_STATUSES:+ raise ValueError(f"unknown refactoring status: {status}")+ row = await get_refactoring_suggestion(session, repository_id, suggestion_id)+ if row is None:+ return None+ row.status = status+ row.status_reason = reason+ row.status_changed_at = _now_utc()+ await session.flush()+ return rowasync def get_refactoring_suggestion(@@ -140,8 +345,9 @@ async def get_refactoring_suggestion() -> RefactoringSuggestion | None:"""Return one refactoring suggestion by id, scoped to *repository_id*.- Powers the web tab's plan-detail drill-down (and any deep link to a single- plan). Returns ``None`` when the id is unknown or belongs to another repo.+ Resolves the storage id first, then the content-derived public id, so a deep+ link minted by either surface lands on the row. Both are indexed point+ lookups. Returns ``None`` when the id is unknown or belongs to another repo."""result = await session.execute(select(RefactoringSuggestion).where(@@ -149,9 +355,45 @@ async def get_refactoring_suggestion(RefactoringSuggestion.id == suggestion_id,))+ row = result.scalar_one_or_none()+ if row is not None:+ return row+ result = await session.execute(+ select(RefactoringSuggestion)+ .where(+ RefactoringSuggestion.repository_id == repository_id,+ RefactoringSuggestion.public_id == suggestion_id,+ )+ .order_by(RefactoringSuggestion.model_version.desc())+ .limit(1)+ )return result.scalar_one_or_none()+def _suggestion_filters(+ repository_id: str,+ *,+ refactoring_type: str | None,+ file_paths: list[str] | None,+ min_confidence: str | None,+ status: str,+) -> list[Any]:+ predicates: list[Any] = [+ RefactoringSuggestion.repository_id == repository_id,+ RefactoringSuggestion.status == status,+ ]+ if refactoring_type is not None:+ predicates.append(RefactoringSuggestion.refactoring_type == refactoring_type)+ if file_paths is not None:+ predicates.append(RefactoringSuggestion.file_path.in_(file_paths))+ if min_confidence is not None:+ order = {"low": 0, "medium": 1, "high": 2}+ threshold = order.get(min_confidence, 0)+ allowed = [k for k, v in order.items() if v >= threshold]+ predicates.append(RefactoringSuggestion.confidence.in_(allowed))+ return predicates++async def get_refactoring_suggestions(session: AsyncSession,repository_id: str,@@ -160,21 +402,24 @@ async def get_refactoring_suggestions(file_paths: list[str] | None = None,min_confidence: str | None = None,status: str = "open",+ limit: int | None = None,+ offset: int | None = None,) -> list[RefactoringSuggestion]:- """Return refactoring suggestions, highest recovered impact first."""+ """Return refactoring suggestions, highest recovered impact first.++ *limit* / *offset* page in SQL. Both default to ``None``, which returns the+ whole filtered set exactly as before, because the callers that still rank+ and page in memory have not been rewired yet (R4).+ """q = select(RefactoringSuggestion).where(- RefactoringSuggestion.repository_id == repository_id,- RefactoringSuggestion.status == status,+ *_suggestion_filters(+ repository_id,+ refactoring_type=refactoring_type,+ file_paths=file_paths,+ min_confidence=min_confidence,+ status=status,+ ))- if refactoring_type is not None:- q = q.where(RefactoringSuggestion.refactoring_type == refactoring_type)- if file_paths is not None:- q = q.where(RefactoringSuggestion.file_path.in_(file_paths))- if min_confidence is not None:- order = {"low": 0, "medium": 1, "high": 2}- threshold = order.get(min_confidence, 0)- allowed = [k for k, v in order.items() if v >= threshold]- q = q.where(RefactoringSuggestion.confidence.in_(allowed))# Secondary keys (file_path, target_symbol) make the read order stable for# ties — notably the common 0.0 no-finding case — so it matches the# detector's own deterministic ordering rather than DB row order.@@ -183,5 +428,35 @@ async def get_refactoring_suggestions(RefactoringSuggestion.file_path.asc(),RefactoringSuggestion.target_symbol.asc(),)+ if offset is not None:+ q = q.offset(offset)+ if limit is not None:+ q = q.limit(limit)result = await session.execute(q)return list(result.scalars().all())+++async def count_refactoring_suggestions(+ session: AsyncSession,+ repository_id: str,+ *,+ refactoring_type: str | None = None,+ file_paths: list[str] | None = None,+ min_confidence: str | None = None,+ status: str = "open",+) -> int:+ """The total behind a page, counted in SQL rather than by materializing it."""+ q = (+ select(func.count())+ .select_from(RefactoringSuggestion)+ .where(+ *_suggestion_filters(+ repository_id,+ refactoring_type=refactoring_type,+ file_paths=file_paths,+ min_confidence=min_confidence,+ status=status,+ )+ )+ )+ return int((await session.execute(q)).scalar_one())diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex c1039d582..5b778c89f 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -1272,7 +1272,22 @@ class RefactoringSuggestion(Base):# opportunities to their plans is one indexed batch rather than a scan of# every plan's JSON.opportunity_id: Mapped[str | None] = mapped_column(String(64), nullable=True)+ # Content-derived public identity (``refac<version>_<digest>``) and the model+ # that minted it. Nullable because a store written before the columns existed+ # carries rows nothing has restamped yet; the writer resolves those rather+ # than reusing them.+ public_id: Mapped[str | None] = mapped_column(String(64), nullable=True)+ model_version: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ # "open" | "acknowledged" | "resolved" | "false_positive" - the finding+ # triage vocabulary, one system across Code Health.status: Mapped[str] = mapped_column(String(32), nullable=False, default="open")+ # Why the row reached its current status: "no_longer_detected" when the+ # writer resolved it, "user" when a person did. Distinguishing them is what+ # lets a re-detected plan reopen without overriding a human decision.+ status_reason: Mapped[str | None] = mapped_column(String(32), nullable=True)+ status_changed_at: Mapped[datetime | None] = mapped_column(+ DateTime(timezone=True), nullable=True+ )created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now_utc)@@ -1287,6 +1302,29 @@ class RefactoringSuggestion(Base):"refactoring_type","opportunity_id",),+ Index("ix_refactoring_suggestions_repo_status", "repository_id", "status"),+ Index(+ "ix_refactoring_suggestions_repo_status_type",+ "repository_id",+ "status",+ "refactoring_type",+ ),+ Index(+ "ix_refactoring_suggestions_repo_status_path",+ "repository_id",+ "status",+ "file_path",+ ),+ # A unique index rather than a UniqueConstraint: the SQLite reconciler+ # that upgrades an existing local store replays declared indexes and+ # cannot add a table constraint without rebuilding the table.+ Index(+ "uq_refactoring_suggestions_repo_model_public_id",+ "repository_id",+ "model_version",+ "public_id",+ unique=True,+ ),)diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex 9f7a89051..59695b87d 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -978,8 +978,9 @@ async def persist_partial_health(session: Any, repo_id: str, report: Any) -> Nondimension="performance",)# Refactoring suggestions for the changed files only (unchanged files- # keep theirs). Scoped delete-then-insert across the full changed-file- # set, so a file that became clean has its stale suggestions removed.+ # keep theirs). Scoped reconciliation across the full changed-file set,+ # so a file that became clean has its plans resolved rather than left+ # standing, and a plan that survived the edit keeps its id.if changed_paths:await upsert_refactoring_suggestions(session,diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex 47f11235a..60c2eaf68 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -1543,10 +1543,11 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:if hr.findings:await save_health_findings(session, repo_id, hr.findings)# Structured refactoring suggestions (Extract Class, ...). Repo-wide- # delete-then-insert like findings; empty list clears prior rows.- # Performance plans are excluded: the finalizer below owns them, so- # they are generated once, from the merged stored findings, by the- # same writer on the full and the incremental path.+ # reconciliation: an unchanged plan keeps its id and its triage+ # state, and one nobody detects any more resolves rather than+ # disappearing. Performance plans are excluded: the finalizer below+ # owns them, so they are generated once, from the merged stored+ # findings, by the same writer on the full and the incremental path.await save_refactoring_suggestions(session,repo_id,diff --git a/packages/server/src/repowise/server/mcp_server/_references.py b/packages/server/src/repowise/server/mcp_server/_references.pyindex a6bff398a..87886469e 100644--- a/packages/server/src/repowise/server/mcp_server/_references.py+++ b/packages/server/src/repowise/server/mcp_server/_references.py@@ -128,30 +128,20 @@ def stable_entity_id(prefix: str, repository: str, coordinates: Mapping[str, objdef refactoring_plan_id(suggestion: Any, repository: str) -> str:"""Return the public ID for one refactoring plan, ORM row or dataclass.- Lives here rather than beside one caller because two surfaces address the- same plan and must arrive at the same string.+ Delegates to the refactoring layer's identity kernel, which is the one owner+ of what makes two plans the same plan and is the id the row is stored under.+ Deriving a second one here let the emitted id churn whenever an incidental+ plan detail moved, so an agent that quoted it yesterday could not resolve it.++ *repository* is accepted for call-site compatibility and does not+ participate: storage scopes uniqueness by repository already, and hashing a+ local path or alias into the string would make the same plan carry different+ ids locally and hosted."""- raw_plan = getattr(suggestion, "plan", None)- if raw_plan is None:- raw_plan = getattr(suggestion, "plan_json", None) or "{}"- try:- raw_plan = json.loads(raw_plan)- except (TypeError, json.JSONDecodeError):- raw_plan = str(raw_plan)- return stable_entity_id(- "plan",- repository,- {- "path": path_identity(suggestion.file_path),- "kind": suggestion.refactoring_type,- "symbol": suggestion.target_symbol or "",- "line_start": suggestion.line_start,- "line_end": suggestion.line_end,- "source_biomarker": suggestion.source_biomarker or "",- "plan": raw_plan,- },- )+ from repowise.core.analysis.health.refactoring.identity import refactoring_public_id++ return refactoring_public_id(suggestion)# Compatibility aliases for the get_why-specific module that originallydiff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.pyindex ebb4e5ce6..295105e2f 100644--- a/packages/server/src/repowise/server/routers/refactoring.py+++ b/packages/server/src/repowise/server/routers/refactoring.py@@ -25,6 +25,7 @@ from repowise.core.analysis.health.refactoring.recommendations import (hydrate_recommendations,)from repowise.core.persistence import crud+from repowise.core.persistence.crud.analysis.refactoring import ALLOWED_STATUSESfrom repowise.server.deps import get_db_session, verify_api_keyrouter = APIRouter(@@ -438,6 +439,41 @@ async def get_refactoring_plan(return _to_response(recommendation.as_dict())+class RefactoringStatusUpdate(BaseModel):+ """Same shape and vocabulary as health finding triage — one triage system."""++ status: str = Field(..., description="open | acknowledged | resolved | false_positive")++[email protected]("/{repo_id}/refactoring/{suggestion_id}/status")+async def update_refactoring_plan_status(+ repo_id: str,+ suggestion_id: str,+ payload: RefactoringStatusUpdate,+ session: AsyncSession = Depends(get_db_session),+) -> dict:+ """Record a decision about one plan.++ ``false_positive`` also suppresses the plan on every later analysis, which+ is how a wrong suggestion stops coming back instead of being re-emitted.+ """+ if payload.status not in ALLOWED_STATUSES:+ raise HTTPException(status_code=400, detail=f"invalid status: {payload.status}")+ row = await crud.update_refactoring_suggestion_status(+ session, repo_id, suggestion_id, payload.status+ )+ if row is None:+ raise HTTPException(status_code=404, detail=f"refactoring plan not found: {suggestion_id}")+ await session.commit()+ return {+ "id": row.id,+ "public_id": row.public_id,+ "status": row.status,+ "status_reason": row.status_reason,+ "status_changed_at": row.status_changed_at.isoformat() if row.status_changed_at else None,+ }++# ---------------------------------------------------------------------------# Opt-in LLM enrichment — plan -> generated code + diff# ---------------------------------------------------------------------------diff --git a/tests/unit/health/test_refactoring_identity_contract.py b/tests/unit/health/test_refactoring_identity_contract.pynew file mode 100644index 000000000..7c14fb13c--- /dev/null+++ b/tests/unit/health/test_refactoring_identity_contract.py@@ -0,0 +1,318 @@+"""The refactoring identity kernel is a contract, pinned by hash.++Readers join plans on exact string equality and dismissals are recorded against+the id, so what enters the kernel cannot drift silently. These tests pin two+real ids and then prove, field by field, which inputs move an id and which+cannot. A failure here is either a bug or a deliberate+``REFACTORING_MODEL_VERSION`` bump — never something to regenerate.+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from repowise.core.analysis.health.refactoring.identity import (+ REFACTORING_MODEL_VERSION,+ assign_public_ids,+ model_state,+ public_id_model_version,+ refactoring_public_id,+)++EXTRACT_METHOD_ID = "refac2_f98f466eecc2dd332485"+CLONE_ID = "refac2_e0d9feee45201e014bc3"+++def _extract_method(**overrides):+ base = dict(+ refactoring_type="extract_method",+ file_path="packages/core/src/repowise/core/pipeline/persist.py",+ target_symbol="persist_analysis",+ line_start=100,+ line_end=118,+ plan={+ "span": {"start": 100, "end": 118},+ "params": ["session", "report"],+ "returns": ["written"],+ "suggested_name": "compute_written",+ },+ evidence={"slice_nloc": 18, "ccn_removed": 4},+ impact_delta=1.5,+ effort_bucket="S",+ blast_radius={"scope": "local"},+ confidence="high",+ source_biomarker="complex_method",+ )+ base.update(overrides)+ return SimpleNamespace(**base)+++def _clone(**overrides):+ base = dict(+ refactoring_type="extract_helper",+ file_path="packages/core/src/repowise/core/a.py",+ target_symbol="a.py:10-24",+ line_start=10,+ line_end=24,+ plan={+ "occurrences": [+ {"file": "packages/core/src/repowise/core/a.py", "line_start": 10, "line_end": 24},+ {"file": "packages/core/src/repowise/core/b.py", "line_start": 55, "line_end": 69},+ ],+ "suggested_site": {"directory": "packages/core/src/repowise/core"},+ "duplicated_lines": 15,+ "snippet": "value = compute()\nreturn value\n",+ "snippet_start_line": 10,+ "snippet_truncated": False,+ "suggested_name": None,+ },+ evidence={+ "occurrence_count": 2,+ "duplicated_lines": 15,+ "token_count": 320,+ "co_change_count": 3,+ "is_intra_file": False,+ },+ impact_delta=0.0,+ effort_bucket="S",+ blast_radius={"files": ["b.py"], "file_count": 1, "co_change_count": 3},+ confidence="medium",+ source_biomarker="dry_violation",+ )+ base.update(overrides)+ return SimpleNamespace(**base)+++def test_the_model_version_is_pinned_and_is_carried_by_the_id_prefix() -> None:+ assert REFACTORING_MODEL_VERSION == 2+ assert refactoring_public_id(_extract_method()) == EXTRACT_METHOD_ID+ assert refactoring_public_id(_clone()) == CLONE_ID+ assert EXTRACT_METHOD_ID.startswith(f"refac{REFACTORING_MODEL_VERSION}_")+ assert public_id_model_version(EXTRACT_METHOD_ID) == REFACTORING_MODEL_VERSION+++ ("public_id", "expected"),+ [+ (EXTRACT_METHOD_ID, "current"),+ ("refac_" + "0" * 20, "stale_model"),+ ("refac1_" + "0" * 20, "stale_model"),+ ("plan_" + "0" * 20, "unrecognized"),+ ("", "unrecognized"),+ ],+)+def test_model_state_classifies_an_id_from_the_string_alone(public_id, expected) -> None:+ state = model_state(public_id)+ assert state["state"] == expected+ assert state["refresh_required"] is (expected == "stale_model")+++ "overrides",+ [+ pytest.param({"impact_delta": 9.9}, id="recovered-health-is-rescored-every-run"),+ pytest.param({"effort_bucket": "XL"}, id="effort-follows-the-file-size"),+ pytest.param({"confidence": "medium"}, id="confidence-is-re-bucketed"),+ pytest.param({"blast_radius": {}}, id="blast-radius-is-a-measurement"),+ pytest.param({"evidence": {"slice_nloc": 2, "ccn_removed": 1}}, id="evidence-is-display"),+ pytest.param({"line_start": 400, "line_end": 418}, id="the-whole-span-moved-down"),+ ],+)+def test_display_and_derived_fields_cannot_move_an_extract_method_id(overrides) -> None:+ assert refactoring_public_id(_extract_method(**overrides)) == EXTRACT_METHOD_ID+++def test_a_renamed_helper_suggestion_does_not_move_the_extract_method_id() -> None:+ plan = dict(_extract_method().plan, suggested_name="compute_something_else")+ assert refactoring_public_id(_extract_method(plan=plan)) == EXTRACT_METHOD_ID+++ ("overrides", "reason"),+ [+ ({"file_path": "packages/core/src/repowise/core/pipeline/other.py"}, "another file"),+ ({"target_symbol": "persist_metrics"}, "another host function"),+ ({"source_biomarker": "large_method"}, "another diagnosis"),+ ({"line_end": 130}, "a longer span is a different extraction"),+ ],+)+def test_each_extract_method_kernel_input_moves_the_id(overrides, reason) -> None:+ assert refactoring_public_id(_extract_method(**overrides)) != EXTRACT_METHOD_ID, reason+++ ("key", "value", "reason"),+ [+ ("params", ["session"], "a different signature is a different extraction"),+ ("returns", [], "returning nothing is a different extraction"),+ ],+)+def test_the_lifted_signature_is_part_of_the_extract_method_kernel(key, value, reason) -> None:+ plan = dict(_extract_method().plan, **{key: value})+ assert refactoring_public_id(_extract_method(plan=plan)) != EXTRACT_METHOD_ID, reason+++ "overrides",+ [+ pytest.param({"file_path": "packages/core/src/repowise/core/b.py"}, id="anchor-moved"),+ pytest.param({"target_symbol": "b.py:55-69"}, id="anchor-label-moved"),+ pytest.param({"line_start": 900, "line_end": 914}, id="anchor-lines-moved"),+ pytest.param({"confidence": "high"}, id="confidence"),+ ],+)+def test_the_clone_id_survives_its_anchor_moving(overrides) -> None:+ """The anchor hops to the smallest surviving site; the group is the identity."""+ assert refactoring_public_id(_clone(**overrides)) == CLONE_ID+++def test_the_clone_id_ignores_trailing_whitespace_in_the_duplicated_block() -> None:+ plan = dict(_clone().plan, snippet="value = compute() \nreturn value\n")+ assert refactoring_public_id(_clone(plan=plan)) == CLONE_ID+++ ("key", "value", "reason"),+ [+ ("snippet", "value = compute_other()\nreturn value\n", "a different block"),+ ("duplicated_lines", 40, "a different amount of duplication"),+ (+ "occurrences",+ [+ {"file": "packages/core/src/repowise/core/a.py", "line_start": 10, "line_end": 24},+ {"file": "packages/core/src/repowise/core/c.py", "line_start": 55, "line_end": 69},+ ],+ "a different set of sites",+ ),+ ],+)+def test_each_clone_kernel_input_moves_the_id(key, value, reason) -> None:+ plan = dict(_clone().plan, **{key: value})+ assert refactoring_public_id(_clone(plan=plan)) != CLONE_ID, reason+++def test_a_third_occurrence_makes_it_a_different_clone_group() -> None:+ plan = dict(_clone().plan)+ plan["occurrences"] = [+ *plan["occurrences"],+ {"file": "packages/core/src/repowise/core/c.py", "line_start": 5, "line_end": 19},+ ]+ assert refactoring_public_id(_clone(plan=plan)) != CLONE_ID+++def test_a_performance_plan_takes_its_identity_from_the_causal_id() -> None:+ """Deriving a second id here would let the two disagree about one row."""+ plan = {"opportunity_id": "perf2_abc", "strategy": "batch", "safety": "review"}+ first = SimpleNamespace(+ refactoring_type="performance_fix",+ file_path="a.py",+ target_symbol="a.py::f",+ line_start=1,+ line_end=2,+ plan=plan,+ evidence={},+ impact_delta=0.0,+ effort_bucket="S",+ blast_radius={},+ confidence="high",+ source_biomarker="io_in_loop",+ )+ moved = SimpleNamespace(**{**vars(first), "file_path": "b.py", "line_start": 90, "line_end": 95})+ assert refactoring_public_id(first) == refactoring_public_id(moved)+ other = SimpleNamespace(**{**vars(first), "plan": {**plan, "opportunity_id": "perf2_def"}})+ assert refactoring_public_id(other) != refactoring_public_id(first)+++def test_a_persisted_row_and_the_dataclass_reach_the_same_id() -> None:+ """The three shapes that describe one plan must not disagree about its name."""+ import json++ suggestion = _extract_method()+ row = SimpleNamespace(+ refactoring_type=suggestion.refactoring_type,+ file_path=suggestion.file_path,+ target_symbol=suggestion.target_symbol,+ line_start=suggestion.line_start,+ line_end=suggestion.line_end,+ plan_json=json.dumps(suggestion.plan),+ evidence_json=json.dumps(suggestion.evidence),+ source_biomarker=suggestion.source_biomarker,+ )+ as_dict = {+ "refactoring_type": suggestion.refactoring_type,+ "file_path": suggestion.file_path,+ "target_symbol": suggestion.target_symbol,+ "line_start": suggestion.line_start,+ "line_end": suggestion.line_end,+ "plan": suggestion.plan,+ "evidence": suggestion.evidence,+ "source_biomarker": suggestion.source_biomarker,+ }+ assert refactoring_public_id(row) == EXTRACT_METHOD_ID+ assert refactoring_public_id(as_dict) == EXTRACT_METHOD_ID+++def test_colliding_kernels_get_distinct_ids_ordered_by_coordinates() -> None:+ """Two extractions can agree on host, signature and length; ids may not."""+ first = _extract_method(line_start=100, line_end=118)+ second = _extract_method(line_start=300, line_end=318)+ ids = assign_public_ids([second, first])+ assert len(set(ids)) == 2+ # Assignment follows the plans' coordinates, not the list order they arrived in.+ assert assign_public_ids([first, second]) == [ids[1], ids[0]]+ # The lower span keeps the collision-free id, so a batch that later stops+ # colliding does not rename the survivor.+ assert ids[1] == EXTRACT_METHOD_ID+++def test_a_uniform_line_shift_renames_nothing_in_a_batch() -> None:+ batch = [_extract_method(), _clone()]+ shifted = [+ _extract_method(line_start=140, line_end=158),+ _clone(line_start=50, line_end=64),+ ]+ assert assign_public_ids(batch) == assign_public_ids(shifted)+++def _extract_class(**overrides):+ base = dict(+ refactoring_type="extract_class",+ file_path="packages/core/src/repowise/core/report.py",+ target_symbol="GenerationReport",+ line_start=20,+ line_end=180,+ plan={+ "groups": [+ {"name": None, "methods": ["render", "to_dict"], "fields": ["rows"]},+ {"name": None, "methods": ["validate"], "fields": ["errors"]},+ ]+ },+ evidence={"lcom4": 7, "method_count": 10, "field_count": 7, "wmc": 22},+ impact_delta=2.4,+ effort_bucket="L",+ blast_radius={"dependents_count": 3},+ confidence="high",+ source_biomarker="low_cohesion",+ )+ base.update(overrides)+ return SimpleNamespace(**base)+++def test_a_class_split_is_named_by_the_clusters_it_proposes() -> None:+ """The class name alone would hold still while the proposed split moved."""+ baseline = refactoring_public_id(_extract_class())+ reordered = dict(_extract_class().plan)+ reordered["groups"] = list(reversed(reordered["groups"]))+ assert refactoring_public_id(_extract_class(plan=reordered)) == baseline++ moved = _extract_class(line_start=500, line_end=660, impact_delta=0.1, effort_bucket="S")+ assert refactoring_public_id(moved) == baseline++ regrouped = dict(_extract_class().plan)+ regrouped["groups"] = [+ {"name": None, "methods": ["render"], "fields": ["rows"]},+ {"name": None, "methods": ["to_dict", "validate"], "fields": ["errors"]},+ ]+ assert refactoring_public_id(_extract_class(plan=regrouped)) != baselinediff --git a/tests/unit/persistence/test_refactoring_lifecycle.py b/tests/unit/persistence/test_refactoring_lifecycle.pynew file mode 100644index 000000000..871ad01a5--- /dev/null+++ b/tests/unit/persistence/test_refactoring_lifecycle.py@@ -0,0 +1,410 @@+"""Refactoring plans keep their identity and their triage across analyses.++The writer is the only place lifecycle is decided, and both index paths call it,+which is what makes a full and an incremental run agree. These tests pin the+four things that decision has to get right: an unchanged plan is the same row, a+plan nobody detects any more resolves rather than vanishing, a decision a person+recorded survives the next analysis, and a false positive never comes back.+"""++from __future__ import annotations++import sqlite3+from pathlib import Path++import pytest+from sqlalchemy import select++from repowise.core.analysis.health.refactoring import RefactoringSuggestion+from repowise.core.persistence.crud.analysis import (+ finalize_refactoring_suggestions,+ get_refactoring_suggestion,+ get_refactoring_suggestions,+ save_refactoring_suggestions,+ update_refactoring_suggestion_status,+ upsert_refactoring_suggestions,+)+from repowise.core.persistence.models import RefactoringSuggestion as SuggestionRow+from tests.unit.persistence.helpers import insert_repo+++def _suggestion(path: str, target: str, **overrides) -> RefactoringSuggestion:+ base = dict(+ refactoring_type="extract_class",+ file_path=path,+ target_symbol=target,+ line_start=1,+ line_end=80,+ plan={"groups": [{"name": None, "methods": ["m1", "m2"], "fields": ["a"]}]},+ evidence={"lcom4": 2, "method_count": 6, "field_count": 2, "wmc": 9},+ impact_delta=2.4,+ effort_bucket="M",+ blast_radius={"dependents_count": 3},+ confidence="high",+ source_biomarker="low_cohesion",+ )+ base.update(overrides)+ return RefactoringSuggestion(**base)+++async def _all_rows(session, repo_id: str) -> list[SuggestionRow]:+ result = await session.execute(+ select(SuggestionRow).where(SuggestionRow.repository_id == repo_id)+ )+ return list(result.scalars().all())+++async def test_an_unchanged_plan_keeps_its_row_and_its_public_id(async_session):+ repo = await insert_repo(async_session)+ plans = [_suggestion("a.py", "Foo"), _suggestion("b.py", "Bar")]++ await save_refactoring_suggestions(async_session, repo.id, plans)+ await async_session.commit()+ before = {row.public_id: (row.id, row.created_at) for row in await _all_rows(async_session, repo.id)}++ await save_refactoring_suggestions(async_session, repo.id, plans)+ await async_session.commit()+ after = {row.public_id: (row.id, row.created_at) for row in await _all_rows(async_session, repo.id)}++ assert len(before) == 2+ assert after == before, "a second analysis of unchanged source must not mint new rows"+ assert all(key.startswith("refac2_") for key in after)+++async def test_moving_a_class_down_the_file_does_not_mint_a_new_plan(async_session):+ repo = await insert_repo(async_session)+ await save_refactoring_suggestions(async_session, repo.id, [_suggestion("a.py", "Foo")])+ await async_session.commit()+ [before] = await _all_rows(async_session, repo.id)++ await save_refactoring_suggestions(+ async_session, repo.id, [_suggestion("a.py", "Foo", line_start=400, line_end=479)]+ )+ await async_session.commit()+ rows = await _all_rows(async_session, repo.id)++ assert len(rows) == 1+ assert rows[0].id == before.id+ assert rows[0].line_start == 400, "the row still tracks where the class is now"+++async def test_a_plan_nobody_detects_resolves_rather_than_disappearing(async_session):+ repo = await insert_repo(async_session)+ await save_refactoring_suggestions(+ async_session, repo.id, [_suggestion("a.py", "Foo"), _suggestion("b.py", "Bar")]+ )+ await async_session.commit()++ await save_refactoring_suggestions(async_session, repo.id, [_suggestion("a.py", "Foo")])+ await async_session.commit()++ rows = {row.file_path: row for row in await _all_rows(async_session, repo.id)}+ assert rows["b.py"].status == "resolved"+ assert rows["b.py"].status_reason == "no_longer_detected"+ assert rows["b.py"].status_changed_at is not None+ # A held id keeps answering, and stops reading as current.+ assert await get_refactoring_suggestion(async_session, repo.id, rows["b.py"].public_id)+ assert [row.file_path for row in await get_refactoring_suggestions(async_session, repo.id)] == [+ "a.py"+ ]+++async def test_a_plan_that_comes_back_reopens_but_a_human_decision_does_not(async_session):+ repo = await insert_repo(async_session)+ await save_refactoring_suggestions(async_session, repo.id, [_suggestion("a.py", "Foo")])+ await async_session.commit()+ [row] = await _all_rows(async_session, repo.id)++ await save_refactoring_suggestions(async_session, repo.id, [])+ await async_session.commit()+ await async_session.refresh(row)+ assert row.status == "resolved"++ await save_refactoring_suggestions(async_session, repo.id, [_suggestion("a.py", "Foo")])+ await async_session.commit()+ await async_session.refresh(row)+ assert row.status == "open", "the detector disagreeing with no_longer_detected is the signal"+ assert row.status_reason is None++ await update_refactoring_suggestion_status(async_session, repo.id, row.id, "resolved")+ await async_session.commit()+ await save_refactoring_suggestions(async_session, repo.id, [_suggestion("a.py", "Foo")])+ await async_session.commit()+ await async_session.refresh(row)+ assert row.status == "resolved", "a person's decision outranks re-detection"+ assert row.status_reason == "user"+++async def test_a_false_positive_is_never_re_emitted(async_session):+ repo = await insert_repo(async_session)+ await save_refactoring_suggestions(async_session, repo.id, [_suggestion("a.py", "Foo")])+ await async_session.commit()+ [row] = await _all_rows(async_session, repo.id)++ await update_refactoring_suggestion_status(+ async_session, repo.id, row.public_id, "false_positive"+ )+ await async_session.commit()++ for _ in range(2):+ await save_refactoring_suggestions(async_session, repo.id, [_suggestion("a.py", "Foo")])+ await async_session.commit()++ rows = await _all_rows(async_session, repo.id)+ assert len(rows) == 1, "the suppressed kernel must not reappear as a second row"+ assert rows[0].status == "false_positive"+ assert await get_refactoring_suggestions(async_session, repo.id) == []+++async def test_acknowledged_survives_the_next_analysis(async_session):+ repo = await insert_repo(async_session)+ await save_refactoring_suggestions(async_session, repo.id, [_suggestion("a.py", "Foo")])+ await async_session.commit()+ [row] = await _all_rows(async_session, repo.id)+ await update_refactoring_suggestion_status(async_session, repo.id, row.id, "acknowledged")+ await async_session.commit()++ await save_refactoring_suggestions(async_session, repo.id, [_suggestion("a.py", "Foo")])+ await async_session.commit()+ await async_session.refresh(row)+ assert row.status == "acknowledged"+++async def test_a_partial_run_and_a_full_run_reach_the_same_plans(async_session):+ """The two paths differ only in scope, so their output must not differ."""+ repo_full = await insert_repo(async_session, name="full", local_path="/tmp/full")+ repo_partial = await insert_repo(async_session, name="partial", local_path="/tmp/partial")+ first = [_suggestion("a.py", "Foo"), _suggestion("b.py", "Bar")]+ second = [_suggestion("a.py", "Foo"), _suggestion("b.py", "Baz")]++ for repo_id in (repo_full.id, repo_partial.id):+ await save_refactoring_suggestions(async_session, repo_id, first)+ await async_session.commit()++ await save_refactoring_suggestions(async_session, repo_full.id, second)+ await upsert_refactoring_suggestions(+ async_session, repo_partial.id, second, file_paths=["b.py"]+ )+ await async_session.commit()++ def _signature(rows):+ return sorted((r.public_id, r.file_path, r.target_symbol, r.status) for r in rows)++ assert _signature(await _all_rows(async_session, repo_full.id)) == _signature(+ await _all_rows(async_session, repo_partial.id)+ )+++async def test_an_incremental_run_leaves_untouched_files_completely_alone(async_session):+ repo = await insert_repo(async_session)+ await save_refactoring_suggestions(+ async_session, repo.id, [_suggestion("a.py", "Foo"), _suggestion("b.py", "Bar")]+ )+ await async_session.commit()+ before = {row.file_path: (row.id, row.status) for row in await _all_rows(async_session, repo.id)}++ await upsert_refactoring_suggestions(async_session, repo.id, [], file_paths=["b.py"])+ await async_session.commit()+ rows = {row.file_path: row for row in await _all_rows(async_session, repo.id)}++ assert (rows["a.py"].id, rows["a.py"].status) == before["a.py"]+ assert rows["b.py"].status == "resolved"+++async def test_a_row_from_an_older_model_is_resolved_rather_than_reused(async_session):+ repo = await insert_repo(async_session)+ await save_refactoring_suggestions(async_session, repo.id, [_suggestion("a.py", "Foo")])+ await async_session.commit()+ [row] = await _all_rows(async_session, repo.id)+ row.model_version = 1+ await async_session.commit()++ await save_refactoring_suggestions(async_session, repo.id, [_suggestion("a.py", "Foo")])+ await async_session.commit()++ rows = sorted(await _all_rows(async_session, repo.id), key=lambda r: r.model_version)+ assert [r.status for r in rows] == ["resolved", "open"]+ assert rows[0].status_reason == "no_longer_detected"+++async def test_a_store_written_before_the_columns_existed_is_restamped(async_session):+ repo = await insert_repo(async_session)+ await save_refactoring_suggestions(async_session, repo.id, [_suggestion("a.py", "Foo")])+ await async_session.commit()+ [row] = await _all_rows(async_session, repo.id)+ row.public_id = None+ row.model_version = 0+ await async_session.commit()++ await save_refactoring_suggestions(async_session, repo.id, [_suggestion("a.py", "Foo")])+ await async_session.commit()++ rows = await _all_rows(async_session, repo.id)+ assert len(rows) == 2+ stamped = [r for r in rows if r.public_id]+ assert len(stamped) == 1 and stamped[0].status == "open"+++async def test_a_page_is_fetched_in_sql_not_sliced_in_memory(async_session):+ repo = await insert_repo(async_session)+ plans = [+ _suggestion(f"f{index:03d}.py", f"C{index}", impact_delta=float(index))+ for index in range(50)+ ]+ await save_refactoring_suggestions(async_session, repo.id, plans)+ await async_session.commit()++ page = await get_refactoring_suggestions(async_session, repo.id, limit=10, offset=10)+ everything = await get_refactoring_suggestions(async_session, repo.id)+ assert len(page) == 10+ assert [row.id for row in page] == [row.id for row in everything[10:20]]+++async def test_an_unknown_status_is_refused(async_session):+ repo = await insert_repo(async_session)+ await save_refactoring_suggestions(async_session, repo.id, [_suggestion("a.py", "Foo")])+ await async_session.commit()+ [row] = await _all_rows(async_session, repo.id)+ with pytest.raises(ValueError):+ await update_refactoring_suggestion_status(async_session, repo.id, row.id, "wontfix")+ assert await update_refactoring_suggestion_status(+ async_session, repo.id, "no-such-id", "resolved"+ ) is None+++async def test_the_finalizer_reports_how_many_plans_are_open(async_session):+ repo = await insert_repo(async_session)+ plans = [_suggestion("a.py", "Foo"), _suggestion("b.py", "Bar")]+ assert await finalize_refactoring_suggestions(async_session, repo.id, plans) == 2+ await async_session.commit()+ assert await finalize_refactoring_suggestions(async_session, repo.id, plans[:1]) == 1+++def _columns(db_path: Path, table: str) -> set[str]:+ with sqlite3.connect(db_path) as connection:+ return {row[1] for row in connection.execute(f'PRAGMA table_info("{table}")')}+++def _indexes(db_path: Path, table: str) -> set[str]:+ with sqlite3.connect(db_path) as connection:+ return {row[1] for row in connection.execute(f'PRAGMA index_list("{table}")')}+++def test_the_migration_upgrades_and_rolls_back(tmp_path: Path) -> None:+ """Explicit migration for managed stores, both directions.++ Local stores are created by ``init_db`` and never see Alembic, which is why+ the model declaration and this migration have to describe the same shape.+ """+ from alembic import command+ from alembic.config import Config++ root = Path(__file__).resolve().parents[3] / "packages" / "core"+ db_path = tmp_path / "wiki.db"+ # Built without the ini file on purpose. Passing it makes ``env.py`` call+ # ``fileConfig``, which reconfigures logging for the rest of the session.+ config = Config()+ config.set_main_option("script_location", str(root / "alembic"))+ config.set_main_option("sqlalchemy.url", f"sqlite+aiosqlite:///{db_path}")++ new_columns = {"public_id", "model_version", "status_reason", "status_changed_at"}+ new_indexes = {+ "ix_refactoring_suggestions_repo_status",+ "ix_refactoring_suggestions_repo_status_type",+ "ix_refactoring_suggestions_repo_status_path",+ "uq_refactoring_suggestions_repo_model_public_id",+ }++ command.upgrade(config, "0058")+ assert new_columns <= _columns(db_path, "refactoring_suggestions")+ assert new_indexes <= _indexes(db_path, "refactoring_suggestions")++ command.downgrade(config, "0057")+ assert not new_columns & _columns(db_path, "refactoring_suggestions")+ assert not new_indexes & _indexes(db_path, "refactoring_suggestions")+++def _clone(anchor: str, partner: str) -> RefactoringSuggestion:+ """A clone group's identity is its members, not the file it is anchored at."""+ return RefactoringSuggestion(+ refactoring_type="extract_helper",+ file_path=anchor,+ target_symbol=f"{anchor}:10-24",+ line_start=10,+ line_end=24,+ plan={+ "occurrences": [+ {"file": anchor, "line_start": 10, "line_end": 24},+ {"file": partner, "line_start": 55, "line_end": 69},+ ],+ "suggested_site": {"directory": None},+ "duplicated_lines": 15,+ "snippet": "value = compute()\nreturn value\n",+ "snippet_start_line": 10,+ "snippet_truncated": False,+ "suggested_name": None,+ },+ evidence={"occurrence_count": 2, "duplicated_lines": 15, "token_count": 320},+ impact_delta=0.0,+ effort_bucket="S",+ blast_radius={"files": [partner], "file_count": 1},+ confidence="medium",+ source_biomarker="dry_violation",+ )+++async def test_a_scoped_run_reuses_a_clone_row_anchored_outside_its_scope(async_session):+ """The stored row sits at a.py; the run only sees b.py. One plan, one row."""+ repo = await insert_repo(async_session)+ await save_refactoring_suggestions(async_session, repo.id, [_clone("a.py", "b.py")])+ await async_session.commit()+ [before] = await _all_rows(async_session, repo.id)++ await upsert_refactoring_suggestions(+ async_session, repo.id, [_clone("b.py", "a.py")], file_paths=["b.py"]+ )+ await async_session.commit()++ rows = await _all_rows(async_session, repo.id)+ assert len(rows) == 1, "the same clone group must not become a second row"+ assert rows[0].id == before.id+ assert rows[0].file_path == "b.py", "the row follows the anchor the run reported"+ assert rows[0].status == "open"+++async def test_the_structural_writer_leaves_performance_plans_to_their_owner(async_session):+ """Their finalizer rebuilds them from the merged findings; this must not race it."""+ repo = await insert_repo(async_session)+ plan = _suggestion(+ "a.py",+ "a.py::handler",+ refactoring_type="performance_fix",+ plan={"opportunity_id": "perf2_abc", "strategy": "batch"},+ source_biomarker="io_in_loop",+ )+ await save_refactoring_suggestions(async_session, repo.id, [plan])+ await async_session.commit()++ # A later structural run knows nothing about performance plans.+ await save_refactoring_suggestions(async_session, repo.id, [_suggestion("b.py", "Bar")])+ await async_session.commit()++ rows = {row.refactoring_type: row for row in await _all_rows(async_session, repo.id)}+ assert rows["performance_fix"].status == "open"+ assert rows["performance_fix"].status_reason is None+ assert rows["performance_fix"].opportunity_id == "perf2_abc"diff --git a/tests/unit/server/mcp/test_cross_tool_reference_contracts.py b/tests/unit/server/mcp/test_cross_tool_reference_contracts.pyindex 7b0a3de2c..35b009080 100644--- a/tests/unit/server/mcp/test_cross_tool_reference_contracts.py+++ b/tests/unit/server/mcp/test_cross_tool_reference_contracts.py@@ -292,7 +292,7 @@ def _extract_contract_references(entity_family="dead_code" if emitter == "get_dead_code" else "health",))- elif identifier.startswith("plan_"):+ elif identifier.startswith(("plan_", "refac")):refs.append(Ref(emitter,diff --git a/tests/unit/server/mcp/test_performance_levels.py b/tests/unit/server/mcp/test_performance_levels.pyindex 26a0ca51f..5b0cb2b67 100644--- a/tests/unit/server/mcp/test_performance_levels.py+++ b/tests/unit/server/mcp/test_performance_levels.py@@ -232,7 +232,8 @@ async def test_one_id_returns_the_cause_its_plan_and_its_rank_rationale(assert result["opportunity_id"] == leadassert result["intervention_symbol"] == "src/shared.py::load"assert result["plan_status"] == "available"- assert result["plan_reference"].startswith("plan_")+ # The plan address space is the refactoring layer's content identity.+ assert result["plan_reference"].startswith("refac2_")assert result["confidence"] == "high"assert result["fix"]["safety"] == "proven"assert result["facets"]["leverage"] == "shared"@@ -364,7 +365,7 @@ async def test_the_lede_links_the_exact_plan_for_the_exact_lead(setup_mcp, mater)lede = result["recommendation_lede"]assert lede["performance_plan_id"] is not None- assert lede["performance_plan_id"].startswith("plan_")+ assert lede["performance_plan_id"].startswith("refac2_")plan = await get_health(plan_id=lede["performance_plan_id"])assert plan["resolved"] is Truediff --git a/tests/unit/server/mcp/test_refactoring.py b/tests/unit/server/mcp/test_refactoring.pyindex ce88a29f3..b73b7420e 100644--- a/tests/unit/server/mcp/test_refactoring.py+++ b/tests/unit/server/mcp/test_refactoring.py@@ -106,7 +106,8 @@ async def test_generate_code_disabled(factory, _mcp_globals) -> None:result = await generate_refactoring_code(sid)assert result["resolved"] is True- assert result["suggestion_id"].startswith("plan_")+ # The content-derived plan identity, versioned by its prefix.+ assert result["suggestion_id"].startswith("refac2_")assert result["generation"]["available"] is Falseassert result["generation"]["reason"] == "disabled"diff --git a/tests/unit/server/test_refactoring.py b/tests/unit/server/test_refactoring.pyindex 5c4ba3300..3633ec703 100644--- a/tests/unit/server/test_refactoring.py+++ b/tests/unit/server/test_refactoring.py@@ -677,3 +677,45 @@ async def test_settings_put_blank_provider_clears_key(client: AsyncClient, app)async def test_settings_unknown_repo_404(client: AsyncClient, app) -> None:resp = await client.get("/api/repos/does-not-exist/refactoring/settings")assert resp.status_code == 404+++async def test_plan_status_round_trips_and_hides_the_row(client: AsyncClient, app) -> None:+ """The triage vocabulary is the findings one, and the write is visible."""+ repo_id = await _seed(client, app)+ listed = (await client.get(f"/api/repos/{repo_id}/refactoring/targets")).json()["plans"]+ target = next(p for p in listed if p["refactoring_type"] == "break_cycle")++ resp = await client.patch(+ f"/api/repos/{repo_id}/refactoring/{target['id']}/status",+ json={"status": "acknowledged"},+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["status"] == "acknowledged"+ assert body["status_reason"] == "user"+ assert body["status_changed_at"] is not None+ assert body["public_id"].startswith("refac2_")++ resp = await client.patch(+ f"/api/repos/{repo_id}/refactoring/{target['id']}/status",+ json={"status": "false_positive"},+ )+ assert resp.status_code == 200+ remaining = (await client.get(f"/api/repos/{repo_id}/refactoring/targets")).json()["plans"]+ assert target["id"] not in {plan["id"] for plan in remaining}+++async def test_plan_status_refuses_an_unknown_state_and_an_unknown_plan(+ client: AsyncClient, app+) -> None:+ repo_id = await _seed(client, app)+ listed = (await client.get(f"/api/repos/{repo_id}/refactoring/targets")).json()["plans"]+ resp = await client.patch(+ f"/api/repos/{repo_id}/refactoring/{listed[0]['id']}/status",+ json={"status": "wontfix"},+ )+ assert resp.status_code == 400+ resp = await client.patch(+ f"/api/repos/{repo_id}/refactoring/deadbeef/status", json={"status": "resolved"}+ )+ assert resp.status_code == 404