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(gates): serve every language, with a preview label where precision is below the bar (#3867)

Raghav Chamadiyab30ccaed3794
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.md
index b032f3e89..da0e2ff22 100644
--- a/docs/layers/REFACTORING.md
+++ b/docs/layers/REFACTORING.md
@@ -137,10 +137,11 @@ the extracted span appeared beside it (computed for Extract Method only). 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`.
-Plans and opportunities on Java, C#, C and C++ files are composed and stored as
-usual but held back pending verification: the plan lists, the queue, its facets
-and the rollup's lead leave them out unless the caller passes
-`include_unverified`, and responses count them in `gated`.
+Plans and opportunities on Java, C#, C and C++ files are served as a preview:
+they are listed and counted like any other, and each one carries the
+measurement behind it, as `preview` on a REST row, in `_meta.preview` on
+`get_health`, and as a dim line under the CLI list. A language gated instead is
+left out unless the caller passes `include_unverified`, and counted in `gated`.
Plans and opportunities on test files are held back the same way on every plan
surface, `scope=all` included, as Fix first already leaves them out. They are
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 17299d856..ec004e8bd 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -1118,6 +1118,8 @@ Report per-file code-health scores from 51 deterministic detectors (McCabe compl
By default it reads the analysis the last `repowise init` or `repowise update` stored, the same rows MCP and the web UI serve, and writes nothing. `--recompute` analyzes the working tree in-process instead.
+When a listed finding or plan sits on a language its layer serves as a preview, the report prints one dim line per layer and language with the measurement behind it, for example `Refactoring on Java: preview, measured 22% precision on 55 judged plans from 2 Java repos, 2026-10-15`. `repowise dead-code` does the same. Today that is health on C++, and refactoring, performance and dead code on Java, C#, C and C++ (dead code on Kotlin and Swift too); no language is held back.
+
**Options:**
| Flag | Description |
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index d9169b466..626b91bb5 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -383,11 +383,11 @@ Items are ordered by value first, then tier. History markers (churn, ownership,
Provisional finding types appear only with `include=["unverified"]`, each marked `verification: "unverified"`. A withheld type never lists but still lowers the score it was counted in, so a file row reports it as `withheld_deduction` and `_meta.withheld` names the type, its count and why it is held back. Targeted mode is never split into production and test.
-Health findings, refactoring plans and opportunities, and performance opportunities on Java, C#, C and C++ files are held back pending verification for those languages. They are still stored and a lookup by id still answers; `_meta.gated` counts them per layer and language, and `include=["unverified"]` shows them.
+A layer on a language is gated, preview or ungated (no row), one row each in `finding_registry.py`. Gated rows are held back pending verification: still stored and addressable by id, counted in `_meta.gated` per layer and language, and listed with `include=["unverified"]`. Preview rows are served and counted like any other, and `_meta.preview` gives `{layer: {language: note}}` once for the cells a response lists, where the note is the measurement (for example `preview, measured 22% precision on 55 judged plans from 2 Java repos, 2026-10-15`). Nothing is gated today: health is ungated on Java, C# and C and preview on C++, and refactoring, performance and dead code are preview on Java, C#, C and C++ (dead code on Kotlin and Swift too).
Health findings on files the index stores as vendored or generated are held back the same way, in every language: that code is changed upstream or by its generator. `_meta.gated.health` counts them under `vendored` and `generated` as plain numbers, and `_meta.gated.reasons` gives each reason once when the call lists no finding. Scores, KPIs and the worst-file order still count them.
-On test files, history markers (ownership, churn, change entropy, co-change and the other git-derived kinds) are held back too, counted under `test_history`: they describe how a test changes, not a defect in it. Code-shape findings on tests are still listed.
+On test files, history markers (ownership, churn, change entropy, co-change and the other git-derived kinds) are held back too, counted under `test_history`: they describe how a test changes, not a defect in it. Code-shape findings on tests are still listed. On every other file they are held back from finding lists and counts under `history`: they order hotspots and Fix first, and `get_risk` still lists them.
### Opt-in blocks
@@ -435,7 +435,7 @@ The `performance_opportunities` list holds causes whose cost is measured (`cost_
| `tiers` | Findings by tier: `high` (0.7 and up), `medium` (0.4 to 0.7), `low`. Each has path, kind, confidence, line count, cleanup impact and a stable `id` |
| `summary` | Totals over every open finding; `filtered_findings` counts what the filters kept; `filters` echoes non-default filters; `scope` says which is which |
| `summary.withheld_types` | Provisional finding types held back; ask with `kind=` to see them, marked unverified |
-| `summary.gated` | Findings held back pending verification on Java, C#, C, C++, Kotlin and Swift files, counted per language; `include_unverified=true` shows them |
+| `summary.gated` | Findings held back on a gated language, counted per language; `include_unverified=true` shows them. No language is gated today; dead code on Java, C#, C, C++, Kotlin and Swift is preview, labelled in `_meta.preview` |
| `summary.call_resolution_basis` | Per language, how many call edges the index resolved and the share that are guesses: the graph the findings rest on |
| `by_directory`, `by_owner` | Rollups with `group_by` |
| `limit_note` | A `limit` over 25 was clamped |
diff --git a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
index cfa80e568..4392acda2 100644
--- a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
@@ -23,6 +23,7 @@ from repowise.cli.output import notice_console
from repowise.core.analysis.dead_code.models import DeadCodeFindingData, DeadCodeReport
from repowise.core.analysis.dead_code.risk_factors import RISK_CAP_CONFIDENCE
from repowise.core.analysis.dead_code.serving import safe_only_note
+from repowise.core.analysis.finding_registry import preview_lines
#: The floor ``init`` and ``update`` store findings at: they run the analyzer
#: with its default config, which keeps nothing below this and runs all four
@@ -359,6 +360,13 @@ def dead_code_command(
)
console.print(table)
+ for line in preview_lines(
+ "dead_code",
+ findings,
+ kind="kind",
+ get=lambda f, k: f.kind.value if k == "kind" else getattr(f, k),
+ ):
+ console.print(f"[dim]{line}[/dim]")
# confidence_summary is a {"high": N, ...} dict; interpolating it printed a
# raw Python repr, braces and quotes included, at the end of an otherwise
# formatted report.
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/command.py b/packages/cli/src/repowise/cli/commands/health_cmd/command.py
index c10b69908..8a483191a 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py
@@ -25,6 +25,7 @@ from repowise.cli.helpers import (
run_async,
silence_logs_for_machine_output_until_close,
)
+from repowise.core.analysis.finding_registry import preview_lines
from repowise.core.analysis.health.counts import (
COUNTS,
DEFAULT_COUNTS,
@@ -499,6 +500,8 @@ def health_command(
f"-{f.health_impact:.2f}",
)
console.print(f_table)
+ for line in preview_lines("health", findings[:30], kind="biomarker_type"):
+ console.print(f"[dim]{line}[/dim]")
def _recompute_report(repo_path: Path, *, persist: bool) -> tuple[Any, set[str], dict[str, str]]:
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py
index af49b9867..3dd90826c 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py
@@ -149,7 +149,11 @@ def _render_stored_refactoring_targets(
findings = [
f
for f in await crud.get_health_findings(
- session, repo_id, exclude_dimensions=tuple(sorted(ZERO_IMPACT_DIMENSIONS))
+ session,
+ repo_id,
+ exclude_dimensions=tuple(sorted(ZERO_IMPACT_DIMENSIONS)),
+ # The targets table weighs history itself, as the web queue does.
+ hold_history=False,
)
if keep(f.file_path)
]
@@ -344,6 +348,22 @@ def _emit(
console.print(table)
_render_opportunities_console(opportunities, plan_by_id)
_render_unattached_console(unattached)
+ _render_preview_lines(opportunities, unattached)
+
+
+def _render_preview_lines(opportunities: list[dict], plans: list[dict]) -> None:
+ """The measurement behind refactoring rows listed on a preview language."""
+ from repowise.core.analysis.finding_registry import preview_lines
+
+ def get(row: dict, key: str) -> Any:
+ return row.get(key)
+
+ lines = [
+ *preview_lines("refactoring", opportunities, kind="lead_refactoring_type", get=get),
+ *preview_lines("refactoring", plans, kind="refactoring_type", get=get),
+ ]
+ for line in dict.fromkeys(lines):
+ console.print(f"[dim]{line}[/dim]")
def _compose(findings: list, suggestions: list) -> tuple[list, dict]:
diff --git a/packages/core/src/repowise/core/analysis/finding_registry.py b/packages/core/src/repowise/core/analysis/finding_registry.py
index 85df74321..79047dd7b 100644
--- a/packages/core/src/repowise/core/analysis/finding_registry.py
+++ b/packages/core/src/repowise/core/analysis/finding_registry.py
@@ -22,7 +22,10 @@ layer an audit measured below the bar on a language is kept off every default
surface for files of that language, while other languages keep it. The opt-in
is the same as for provisional types (:data:`UNVERIFIED_LABEL`). A gated row is
still computed, stored and addressable by id, so the cell stays measurable and
-ungating it is deleting its row here after a re-audit clears it.
+ungating it is deleting its row here after a re-audit clears it. A row in the
+``preview`` state is served by default and counted as served, labelled with its
+measurement (:func:`preview_note`) instead of held back. A language with no row
+is served unlabelled.
"""
from __future__ import annotations
@@ -96,85 +99,104 @@ REGISTRY: dict[str, FindingTypeStatus] = {
#: opportunities; ``dead_code`` is every dead-code finding, safe-to-delete or not.
GateLayer = Literal["health", "refactoring", "performance", "dead_code"]
+#: ``gated`` holds the layer back on the language (opt-in to see it);
+#: ``preview`` serves it by default, labelled with its measurement.
+GateState = Literal["gated", "preview"]
+
@dataclass(frozen=True)
class LanguageGate:
layer: GateLayer
#: An ``EXTENSION_TO_LANGUAGE`` tag; a file's extension decides its language.
language: str
- #: Measured precision on the sample that failed the bar, ``None`` when the
- #: evidence was a share of wrong rows rather than a judged sample. Kept for
- #: the record: served text never quotes it.
+ #: The share the judged sample scored on ``measure``, ``None`` when nothing
+ #: was served to judge or the evidence was not a judged sample. A gated
+ #: row's served text never quotes it; a preview row's note does.
precision: float | None
#: What the measurement ran on, in words (no repository names).
corpus: str
#: ISO date of the measurement.
measured_on: str
- #: Why the layer failed there, for maintainers; served text says only
- #: that the layer is held back pending verification.
+ #: Why the layer falls short there, for maintainers; served text never
+ #: quotes it (a gated row says only that it is held back pending
+ #: verification).
cause: str
#: The kinds gated, or ``None`` for every kind of the layer.
kinds: frozenset[str] | None = None
+ state: GateState = "gated"
+ #: What ``precision`` measured (``precision`` or ``not wrong``), as the preview note words it.
+ measure: str = "precision"
_AUDIT_DATE = "2026-10-02"
-_JAVA = "hand-judged sample of a 34k-file Java search engine"
-_DOTNET = "hand-judged samples of a 59k-file C#/C/C++ runtime and an 8k-file C#/C++ suite"
+_REAUDIT_DATE = "2026-10-15"
+_PREVIEW = "preview"
_NO_PLAN = "No judged plan was acceptable as written."
_NOT_A_COST = "Most judged opportunities were not real costs."
-
-# Every layer measured below 90% on every audited language, so whole layers
-# are gated (``kinds=None``). Precision is the lowest share of true positives
-# in a judged sample (debatable counted as a miss). Columns: layer, language,
-# precision, corpus, cause.
-_GATE_ROWS: tuple[tuple[GateLayer, str, float, str, str], ...] = (
- ("health", "java", 0.09, _JAVA, "Field reads without `this.` and Java idioms read as defects."),
- ("health", "csharp", 0.06, _DOTNET, "Implicit member access and stubs read as defects."),
- ("health", "c", 0.09, _DOTNET, "Vendored and generated C read as defects."),
- ("health", "cpp", 0.09, _DOTNET, "Implicit member access and vendored code read as defects."),
- ("refactoring", "java", 0.0, _JAVA, _NO_PLAN),
- ("refactoring", "csharp", 0.09, _DOTNET, _NO_PLAN),
- ("refactoring", "c", 0.0, _DOTNET, _NO_PLAN),
- ("refactoring", "cpp", 0.09, _DOTNET, _NO_PLAN),
- ("performance", "java", 0.32, _JAVA, "In-memory lookups are read as database calls."),
- ("performance", "csharp", 0.06, _DOTNET, _NOT_A_COST),
- ("performance", "c", 0.06, _DOTNET, _NOT_A_COST),
- ("performance", "cpp", 0.0, _DOTNET, _NOT_A_COST),
- ("dead_code", "java", 0.20, _JAVA, "Reflection and plugin entry points are unseen."),
- ("dead_code", "csharp", 0.07, _DOTNET, "A `using` reaches one file of its namespace."),
- ("dead_code", "c", 0.04, _DOTNET, "P/Invoke, call-table and typedef uses are unseen."),
- ("dead_code", "cpp", 0.04, _DOTNET, "Uses through DLL tables, COM and callbacks are unseen."),
+_FEW_PLANS = "Most judged plans were not acceptable as written."
+_NONE_SERVED = "No opportunity was served to judge."
+_IN_MEMORY = "In-memory lookups are read as database calls."
+_ONE_PLAN = "One judged plan was not acceptable as written."
+_NOT_WRONG = "not wrong"
+_VENDORED_HEADER = "A vendored single-header library is not classed vendored."
+
+# Each row covers a whole layer on one language (``kinds=None``). Precision is
+# the share of true positives in a judged sample (debatable counted as a miss)
+# unless the row names another measure. Columns: layer, language, precision,
+# corpus, cause, then optionally the state, its measurement date (default
+# gated, ``_AUDIT_DATE``) and the measure. ``_PREVIEW`` serves a row labelled
+# with its measurement, ``"gated"`` in its place holds the layer back again,
+# and deleting the row ungates it.
+_GateRow = (
+ tuple[GateLayer, str, float | None, str, str]
+ | tuple[GateLayer, str, float | None, str, str, GateState, str]
+ | tuple[GateLayer, str, float | None, str, str, GateState, str, str]
)
-
-LANGUAGE_GATES: tuple[LanguageGate, ...] = (
- *(
- LanguageGate(layer, language, precision, corpus, _AUDIT_DATE, cause)
- for layer, language, precision, corpus, cause in _GATE_ROWS
- ),
- # Dead code only: health on these languages is not gated.
- LanguageGate(
- "dead_code",
- "kotlin",
- 2 / 47,
- "hand-judged findings on a Kotlin/Android sample app",
- "2026-10-13",
- "45 of 47 judged findings were wrong.",
- ),
- LanguageGate(
- "dead_code",
- "swift",
- None,
- "unreachable-file findings on a SwiftUI app",
- "2026-10-13",
- "132 of 431 files reported unreachable at confidence 1.0 were reachable.",
- ),
+_GATE_ROWS: tuple[_GateRow, ...] = (
+ # Health ships on a not-wrong bar (debatable counts as not wrong): Java,
+ # C# and C cleared 0.90 on every corpus on 2026-10-15 and are ungated.
+ ("health", "cpp", 0.825, "the lower of 2 C++ repos, 40 judged each", _VENDORED_HEADER, _PREVIEW, _REAUDIT_DATE, _NOT_WRONG),
+ ("refactoring", "java", 0.22, "55 judged plans from 2 Java repos", _FEW_PLANS, _PREVIEW, _REAUDIT_DATE),
+ ("refactoring", "csharp", 0.83, "6 judged plans from 1 C# repo", _ONE_PLAN, _PREVIEW, _REAUDIT_DATE),
+ ("refactoring", "c", 0.0, "1 judged plan from 1 C repo", _NO_PLAN, _PREVIEW, _REAUDIT_DATE),
+ ("refactoring", "cpp", 0.33, "3 judged plans from 1 C++ repo", _FEW_PLANS, _PREVIEW, _REAUDIT_DATE),
+ ("performance", "java", 0.0, "1 judged opportunity from 4 Java repos", _IN_MEMORY, _PREVIEW, _REAUDIT_DATE),
+ ("performance", "csharp", 0.0, "1 judged opportunity from 2 C# repos", _NOT_A_COST, _PREVIEW, _REAUDIT_DATE),
+ ("performance", "c", None, "no served opportunities on 2 C repos", _NONE_SERVED, _PREVIEW, _REAUDIT_DATE),
+ ("performance", "cpp", None, "no served opportunities on 2 C++ repos", _NONE_SERVED, _PREVIEW, _REAUDIT_DATE),
+ # Dead code: pooled precision, with the lowest corpus in the corpus words.
+ ("dead_code", "java", 0.37, "30 judged findings from 3 Java repos (lowest 0%)", "Android manifest and layout uses are unseen.", _PREVIEW, _REAUDIT_DATE),
+ ("dead_code", "csharp", 0.26, "80 judged findings from 2 C# repos (lowest 5%)", "Custom MEF export attributes and C# 14 extension blocks are unseen.", _PREVIEW, _REAUDIT_DATE),
+ ("dead_code", "c", 0.66, "35 judged findings from 2 C repos (lowest 0%)", "P/Invoke exports are unseen.", _PREVIEW, _REAUDIT_DATE),
+ ("dead_code", "cpp", 0.68, "25 judged findings from 1 C++ repo", "Build-listed translation units and macro uses are unseen.", _PREVIEW, _REAUDIT_DATE),
+ ("dead_code", "kotlin", 0.18, "34 judged findings from 2 Kotlin repos (lowest 0%)", "DI-bound classes are not roots.", _PREVIEW, _REAUDIT_DATE),
+ ("dead_code", "swift", 0.44, "71 judged findings from 2 Swift repos (lowest 10%)", "Cross-module function and extension-member uses are unseen.", _PREVIEW, _REAUDIT_DATE),
)
+def _row_gate(
+ layer: GateLayer,
+ language: str,
+ precision: float | None,
+ corpus: str,
+ cause: str,
+ state: GateState = "gated",
+ measured_on: str = _AUDIT_DATE,
+ measure: str = "precision",
+) -> LanguageGate:
+ return LanguageGate(
+ layer, language, precision, corpus, measured_on, cause, state=state, measure=measure
+ )
+
+
+LANGUAGE_GATES: tuple[LanguageGate, ...] = tuple(_row_gate(*row) for row in _GATE_ROWS)
+
+
#: Why a health finding is held back by the file it sits on rather than by its
#: language: vendored and generated code is not the reader's to change, and a
#: history marker on a test file describes how the test changes, not a defect
-#: in it. A refactoring plan or opportunity on a test file is held back too:
+#: in it. On any other file a history marker is context (it orders hotspots and
+#: Fix first) rather than a finding to list. A refactoring plan or opportunity on a test file is held back too:
#: Fix first never offers one, and no other plan surface does either. Read from
#: the file's stored ``code_origin`` and ``is_test``, so it holds on every
#: language, with the same opt-in as a language gate.
@@ -182,6 +204,7 @@ FILE_HOLDS: dict[str, str] = {
"vendored": "Held back on vendored files: the code is maintained upstream.",
"generated": "Held back on generated files: change what generates them instead.",
"test_history": "History markers held back on test files: they describe change, not a defect.",
+ "history": "History markers are context: they order hotspots and Fix first, not the defect list.",
"test": "Plans held back on test files: tests change with the code they cover.",
}
@@ -190,30 +213,41 @@ HELD_ORIGINS: tuple[str, ...] = ("vendored", "generated")
def history_kinds() -> frozenset[str]:
- """The health markers read from git history alone (the ``test_history`` hold)."""
+ """The health markers read from git history alone (the history holds)."""
# Deferred: the health package imports this module.
from repowise.core.analysis.health.scoring import history_biomarkers
return history_biomarkers()
-def file_hold(layer: GateLayer, kind: Any, code_origin: Any, is_test: Any) -> str | None:
+def file_hold(
+ layer: GateLayer, kind: Any, code_origin: Any, is_test: Any, *, hold_history: bool = True
+) -> str | None:
"""The :data:`FILE_HOLDS` key holding back a *layer* row of *kind* on a file
- with that stored origin and test flag, or ``None``."""
+ with that stored origin and test flag, or ``None``. ``hold_history=False``
+ keeps history markers on production files (shown.py's flag of that name)."""
if layer == "refactoring":
return "test" if is_test is True else None
if layer != "health":
return None
if code_origin in HELD_ORIGINS:
return str(code_origin)
- if is_test is True and kind in history_kinds():
- return "test_history"
+ if kind in history_kinds():
+ if is_test is True:
+ return "test_history"
+ return "history" if hold_history else None
return None
def gates_on(layer: GateLayer) -> tuple[LanguageGate, ...]:
- """The gates on *layer*, read from :data:`LANGUAGE_GATES` at call time."""
- return tuple(gate for gate in LANGUAGE_GATES if gate.layer == layer)
+ """The gates holding *layer* back, read from :data:`LANGUAGE_GATES` at call
+ time. Preview rows are served, so they are not among them."""
+ return tuple(g for g in LANGUAGE_GATES if g.layer == layer and g.state == "gated")
+
+
+def previews_on(layer: GateLayer) -> tuple[LanguageGate, ...]:
+ """The preview rows on *layer*: served by default, labelled."""
+ return tuple(g for g in LANGUAGE_GATES if g.layer == layer and g.state == "preview")
def language_of(path: str) -> str | None:
@@ -221,17 +255,71 @@ def language_of(path: str) -> str | None:
return EXTENSION_TO_LANGUAGE.get(PurePosixPath(path or "").suffix.lower())
-def gate_for(layer: GateLayer, path: str, kind: str | None = None) -> LanguageGate | None:
- """The gate keeping a *layer* row on *path* (of *kind*) off default surfaces."""
+def _match(
+ gates: Iterable[LanguageGate], path: str, kind: str | None
+) -> LanguageGate | None:
language = language_of(path)
if language is None:
return None
- for gate in gates_on(layer):
+ for gate in gates:
if gate.language == language and (gate.kinds is None or kind in gate.kinds):
return gate
return None
+def gate_for(layer: GateLayer, path: str, kind: str | None = None) -> LanguageGate | None:
+ """The gate keeping a *layer* row on *path* (of *kind*) off default surfaces."""
+ return _match(gates_on(layer), path, kind)
+
+
+def preview_for(layer: GateLayer, path: str, kind: str | None = None) -> LanguageGate | None:
+ """The preview row a served *layer* row on *path* (of *kind*) is labelled by."""
+ return _match(previews_on(layer), path, kind)
+
+
+def preview_note(gate: LanguageGate) -> str:
+ """The one-line label a preview row's findings carry."""
+ if gate.precision is None:
+ return f"preview, not measured: {gate.corpus}, {gate.measured_on}"
+ return (
+ f"preview, measured {round(gate.precision * 100)}% {gate.measure} "
+ f"on {gate.corpus}, {gate.measured_on}"
+ )
+
+
+def preview_label(layer: GateLayer, path: str, kind: str | None = None) -> str | None:
+ """:func:`preview_note` for a served *layer* row on *path*, else ``None``."""
+ gate = preview_for(layer, path, kind)
+ return preview_note(gate) if gate is not None else None
+
+
+def label_previews(layer: GateLayer, rows: Iterable[dict], *, kind: str) -> list[dict]:
+ """*rows* (dicts with ``file_path``), each on a preview language copied
+ with ``preview`` set to its note; the others unchanged."""
+ out: list[dict] = []
+ for row in rows:
+ note = preview_label(layer, row.get("file_path") or "", row.get(kind))
+ out.append({**row, "preview": note} if note else row)
+ return out
+
+
+def served_previews(
+ layer: GateLayer,
+ rows: Iterable[Any],
+ *,
+ kind: str,
+ get: Callable[[Any, str], Any] = getattr,
+) -> dict[str, str]:
+ """``{language: preview_note}`` for each preview language among served
+ *rows*, so a response labels only the cells it actually lists."""
+ out: dict[str, str] = {}
+ for row in rows:
+ gate = preview_for(layer, get(row, "file_path") or "", get(row, kind))
+ if gate is not None:
+ out.setdefault(gate.language, preview_note(gate))
+ return out
+
+
def is_served(
layer: GateLayer, finding_type: Any, path: str, excluded: frozenset[str]
) -> bool:
@@ -241,6 +329,29 @@ def is_served(
return finding_type not in excluded and gate_for(layer, path, finding_type) is None
+_LAYER_LABEL: dict[str, str] = {
+ "health": "Health",
+ "refactoring": "Refactoring",
+ "performance": "Performance",
+ "dead_code": "Dead code",
+}
+
+
+def preview_lines(
+ layer: GateLayer,
+ rows: Iterable[Any],
+ *,
+ kind: str,
+ get: Callable[[Any, str], Any] = getattr,
+) -> list[str]:
+ """One ``"<Layer> on <Language>: <note>"`` line per preview language among
+ the listed *rows*, for a terminal report to print under its list."""
+ return [
+ f"{_LAYER_LABEL[layer]} on {language_label(language)}: {note}"
+ for language, note in served_previews(layer, rows, kind=kind, get=get).items()
+ ]
+
+
def gated_extensions(language: str) -> tuple[str, ...]:
"""Every extension mapped to *language*, lower-case with the dot."""
return tuple(sorted(ext for ext, tag in EXTENSION_TO_LANGUAGE.items() if tag == language))
@@ -284,6 +395,7 @@ def row_hold(
*,
kind: str,
get: Callable[[Any, str], Any] = getattr,
+ hold_history: bool = True,
) -> str | None:
"""The :data:`FILE_HOLDS` key on *row*, read off its file's metric row in
*files* (``code_origin``, ``is_test``); a path missing from it is not held."""
@@ -291,7 +403,11 @@ def row_hold(
if metric is None:
return None
return file_hold(
- layer, get(row, kind), getattr(metric, "code_origin", None), getattr(metric, "is_test", None)
+ layer,
+ get(row, kind),
+ getattr(metric, "code_origin", None),
+ getattr(metric, "is_test", None),
+ hold_history=hold_history,
)
@@ -324,20 +440,22 @@ def split_gated(
get: Callable[[Any, str], Any] = getattr,
include_unverified: bool = False,
files: Mapping[str, Any] | None = None,
+ hold_history: bool = True,
) -> tuple[list[Any], dict[str, dict]]:
"""``(rows no gate holds back, gated_summary)`` for rows already in memory.
*kind* names the row field holding the finding type; *get* reads a field.
*files* maps a path to its health metric row so the :data:`FILE_HOLDS`
apply too (:func:`row_hold`). ``include_unverified`` keeps every row and
- reports nothing held back.
+ reports nothing held back; ``hold_history=False`` keeps history markers on
+ production files.
"""
if include_unverified:
return list(rows), {}
shown: list[Any] = []
counts: dict[str, int] = {}
for row in rows:
- held = row_hold(layer, row, files, kind=kind, get=get)
+ held = row_hold(layer, row, files, kind=kind, get=get, hold_history=hold_history)
gate = None if held else gate_for(layer, get(row, "file_path") or "", get(row, kind))
key = held or (gate.language if gate is not None else None)
if key is None:
@@ -399,6 +517,7 @@ __all__ = [
"FindingStatus",
"FindingTypeStatus",
"GateLayer",
+ "GateState",
"LanguageGate",
"excluded_types",
"file_hold",
@@ -409,8 +528,15 @@ __all__ = [
"history_kinds",
"is_served",
"is_shown",
+ "label_previews",
"language_of",
+ "preview_for",
+ "preview_label",
+ "preview_lines",
+ "preview_note",
+ "previews_on",
"row_hold",
+ "served_previews",
"split_gated",
"split_held",
"status_of",
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.py b/packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.py
index 0bd8bc1d6..70d7c86c5 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.py
@@ -20,6 +20,8 @@ Two narrowings keep the finding to signatures someone can actually fix:
objects this smell asks for. Untyped parameters are left out of that
majority, and a wholly untyped signature (unannotated Python or JavaScript)
is judged on the count alone, as before.
+- A parameter a framework binds by annotation (``@PathVariable``) is the
+ route's or the data format's, so only the remaining ones are counted.
A wide signature only counts as obsession in a file with enough substance to
*have* a design (`_MIN_FILE_NLOC`). In a tiny module a long parameter list is
@@ -62,7 +64,7 @@ class PrimitiveObsessionDetector:
out.append(
BiomarkerResult(
biomarker_type=self.name,
- severity=_severity(fn.param_count, threshold),
+ severity=_severity(fn.param_count - fn.bound_param_count, threshold),
function_name=fn.name,
line_start=fn.start_line,
line_end=fn.end_line,
@@ -70,9 +72,11 @@ class PrimitiveObsessionDetector:
"param_count": fn.param_count,
"typed_param_count": typed,
"primitive_param_count": primitive,
+ "bound_param_count": fn.bound_param_count,
},
reason=(
f"long parameter list: {fn.name} takes {fn.param_count} parameters"
+ + (f", {fn.bound_param_count} bound by the framework" if fn.bound_param_count else "")
+ (f", {primitive} of {typed} typed ones scalars or strings" if typed else "")
),
)
@@ -87,7 +91,7 @@ def _threshold(fn: FunctionComplexity) -> int | None:
if fn.is_test_case or fn.signature_fixed:
return None
threshold = _PARAM_THRESHOLD + (_CTOR_GRACE if fn.is_constructor else 0)
- if fn.param_count < threshold:
+ if fn.param_count - fn.bound_param_count < threshold:
return None
typed = fn.typed_param_count
if typed and fn.primitive_param_count * 2 <= typed:
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
index 248202c49..903005897 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -314,6 +314,10 @@ class LanguageNodeMap:
# decorator words saying the parameter list belongs to another
# declaration: an override, a native or generated binding, a
# data-driven test whose arguments the runner supplies.
+ # * ``bound_param_markers`` -- annotation words on one parameter saying
+ # a framework fills it from the request route or the data format
+ # (``@PathVariable``), so the route, not a caller, chose it. Object
+ # binders (``@RequestBody``) stay out: that parameter is the value object.
# * ``explicit_impl_kinds`` / ``trait_impl_kinds`` -- an explicit
# interface implementation on the member, an enclosing trait impl.
# * ``public_api_modifiers`` / ``public_api_type_kinds`` -- a member
@@ -326,6 +330,7 @@ class LanguageNodeMap:
ctor_kinds: frozenset[str] = frozenset()
ctor_names: frozenset[str] = frozenset()
fixed_signature_markers: frozenset[str] = frozenset()
+ bound_param_markers: frozenset[str] = frozenset()
explicit_impl_kinds: frozenset[str] = frozenset()
trait_impl_kinds: frozenset[str] = frozenset()
public_api_modifiers: frozenset[str] = frozenset()
@@ -516,9 +521,19 @@ _GO = LanguageNodeMap(
continue_kinds=frozenset({"continue_statement"}),
)
+# Spring MVC, JAX-RS, MaxMind and Jackson creator parameter bindings.
+_JVM_BOUND_PARAM_MARKERS = frozenset(
+ {
+ "PathVariable", "RequestParam", "RequestHeader", "CookieValue", "MatrixVariable", "RequestPart",
+ "PathParam", "QueryParam", "HeaderParam", "CookieParam", "FormParam", "MatrixParam",
+ "MaxMindDbParameter", "JsonProperty",
+ }
+)
+
_JAVA = LanguageNodeMap(
ctor_kinds=frozenset({"constructor_declaration"}),
fixed_signature_markers=frozenset({"Override"}),
+ bound_param_markers=_JVM_BOUND_PARAM_MARKERS,
scalar_type_names=frozenset({"boolean", "byte", "short", "int", "long", "float", "double", "char", "String", "Boolean", "Byte", "Short", "Integer", "Long", "Float", "Double", "Character"}),
function_kinds=frozenset({"method_declaration", "constructor_declaration"}),
lambda_kinds=frozenset({"lambda_expression"}),
@@ -669,6 +684,7 @@ _RUST = LanguageNodeMap(
_KOTLIN = LanguageNodeMap(
ctor_kinds=frozenset({"secondary_constructor"}),
fixed_signature_markers=frozenset({"override"}),
+ bound_param_markers=_JVM_BOUND_PARAM_MARKERS,
scalar_type_names=frozenset(
{"Int", "Long", "Short", "Byte", "Boolean", "Char", "Float", "Double", "String", "UInt", "ULong"}
),
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 42b4d8717..c6e7ce6e1 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py
@@ -54,6 +54,9 @@ class FunctionComplexity:
# flags below, read only by ``primitive_obsession``. ``complexity/signature.py``.
typed_param_count: int = 0
primitive_param_count: int = 0
+ # Of ``param_count``, the ones a framework binds by annotation
+ # (``@PathVariable``); they are in neither count above.
+ bound_param_count: int = 0
# A constructor, by node kind, conventional name, or its type's name.
is_constructor: bool = False
# The parameter list is set by another declaration (an override, an
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/signature.py b/packages/core/src/repowise/core/analysis/health/complexity/signature.py
index e896dd55e..672e71cd2 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/signature.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/signature.py
@@ -16,6 +16,9 @@ reads the tree with it.
- **typed / scalar parameters**: how many parameters declare a type, and how
many of those are a scalar or a string. An untyped parameter is in neither
count.
+- **bound parameters**: parameters whose own annotation says a framework fills
+ them (``@PathVariable``), read the same way as a declaration's markers. They
+ stay in the declared count and leave the typed and scalar ones.
"""
from __future__ import annotations
@@ -74,6 +77,10 @@ def _marker_words(node: Node) -> set[str]:
declarator = node.child_by_field_name("declarator")
if declarator is not None:
stack += [c for c in declarator.children if c.type in _MARKER_CONTAINERS]
+ return _leaf_words(stack)
+
+
+def _leaf_words(stack: list[Node]) -> set[str]:
words: set[str] = set()
while stack:
cur = stack.pop()
@@ -195,8 +202,30 @@ def typed_param_counts(params: Node | None, lmap: LanguageNodeMap) -> tuple[int,
for param in params.named_children:
if param.type in _NON_PARAMS or (type_node := _param_type(param)) is None:
continue
+ if _is_bound(param, lmap):
+ continue
arity = _arity(param)
typed += arity
if _is_scalar(type_node, lmap.scalar_type_names):
scalar += arity
return typed, scalar
+
+
+def _is_bound(param: Node, lmap: LanguageNodeMap) -> bool:
+ if not lmap.bound_param_markers:
+ return False
+ words = _marker_words(param)
+ # Kotlin keeps a parameter's annotations on the sibling before it.
+ prev = param.prev_named_sibling
+ if prev is not None and prev.type == "parameter_modifiers":
+ words |= _leaf_words([prev])
+ return bool(words & lmap.bound_param_markers)
+
+
+def bound_param_count(params: Node | None, lmap: LanguageNodeMap) -> int:
+ """Parameters of *params* a framework binds by annotation."""
+ if not lmap.bound_param_markers or params is None:
+ return 0
+ return sum(
+ _arity(p) for p in params.named_children if p.type not in _NON_PARAMS and _is_bound(p, lmap)
+ )
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
index f29c8ad3f..85f339d26 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
@@ -82,7 +82,7 @@ from .models import (
# which imports it directly from this module.
from .nloc import _count_file_nloc
from .perf_walk import _collect_perf_hits, perf_pass_runs
-from .signature import is_constructor, is_signature_fixed, typed_param_counts
+from .signature import bound_param_count, is_constructor, is_signature_fixed, typed_param_counts
from .test_case import is_test_case
if TYPE_CHECKING:
@@ -203,7 +203,8 @@ def walk_file(
terminal,
) = _collect_assertion_facts(body, lmap, asserts)
name = _find_function_entry_name(fn_node, lmap)
- typed, scalar = typed_param_counts(_parameter_list(fn_node), lmap)
+ params = _parameter_list(fn_node)
+ typed, scalar = typed_param_counts(params, lmap)
dispatch = dispatch_points(body, lmap)
fc = FunctionComplexity(
name=name,
@@ -217,6 +218,7 @@ def walk_file(
param_count=_count_parameters(fn_node),
typed_param_count=typed,
primitive_param_count=scalar,
+ bound_param_count=bound_param_count(params, lmap),
is_constructor=is_constructor(fn_node, name, lmap),
signature_fixed=is_signature_fixed(fn_node, lmap),
complex_conditions=conditions,
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health.py b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
index 8328c9d44..67b4f37cc 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
@@ -498,6 +498,7 @@ async def get_health_findings(
include_withheld: bool = False,
include_unverified: bool = False,
file_holds: bool = True,
+ hold_history: bool = True,
limit: int | None = None,
) -> list[HealthFinding]:
"""Findings for one repository: production ahead of test files, worth doing
@@ -512,7 +513,8 @@ async def get_health_findings(
provisional type). ``include_withheld`` is for analysis that must see every
row. ``file_holds=False`` keeps the findings held back by their file
(vendored, generated, history on a test) for a reader that sums scores or
- KPIs, which count them.
+ KPIs, which count them. ``hold_history=False`` keeps history markers on
+ production files for a view that treats history itself.
``exclude_dimensions`` is how a general queue keeps a dimension out of a
ranking it does not share units with. It is ignored when ``dimension``
@@ -555,6 +557,7 @@ async def get_health_findings(
requested=types,
include_unverified=include_unverified,
file_holds=file_holds,
+ hold_history=hold_history,
)
)
if file_path is not None:
@@ -610,6 +613,7 @@ async def gated_health_counts(
*,
file_path: str | None = None,
include_unverified: bool = False,
+ hold_history: bool = True,
) -> dict[str, dict]:
"""``{language or file hold: {count, reason}}`` over the open findings
:func:`get_health_findings` leaves out by default, so a list says why it
@@ -628,6 +632,7 @@ async def gated_health_counts(
*where,
kind_col=HealthFinding.biomarker_type,
include_unverified=include_unverified,
+ hold_history=hold_history,
)
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/shown.py b/packages/core/src/repowise/core/persistence/crud/analysis/shown.py
index 39b246135..583c6435f 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/shown.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/shown.py
@@ -40,10 +40,13 @@ _HELD_MODELS: dict[str, tuple[Any, ...]] = {
}
-def _file_holds(layer: GateLayer, path_col: Any, kind_col: Any) -> list[tuple[str, Any]]:
+def _file_holds(
+ layer: GateLayer, path_col: Any, kind_col: Any, *, hold_history: bool = True
+) -> list[tuple[str, Any]]:
"""``(FILE_HOLDS key, row matches it)`` for health findings and plans, read
from the file's stored metric row; ahead of the language cells, as
- ``file_hold`` is."""
+ ``file_hold`` is. ``hold_history=False`` keeps history markers on
+ production files, for a view that is about history."""
model = getattr(path_col, "class_", None)
if model not in _HELD_MODELS.get(layer, ()):
return []
@@ -63,23 +66,27 @@ def _file_holds(layer: GateLayer, path_col: Any, kind_col: Any) -> list[tuple[st
return [("test", on_file(HealthFileMetric.is_test.is_(True)))]
cells = [(origin, on_file(HealthFileMetric.code_origin == origin)) for origin in HELD_ORIGINS]
if kind_col is not None:
- cells.append(
- (
- "test_history",
- and_(
- kind_col.in_(sorted(history_kinds())),
- on_file(HealthFileMetric.is_test.is_(True)),
- ),
- )
- )
+ history = kind_col.in_(sorted(history_kinds()))
+ cells.append(("test_history", and_(history, on_file(HealthFileMetric.is_test.is_(True)))))
+ if hold_history:
+ # ``file_hold``'s ``is_test is not True``: an unknown flag is not a test.
+ not_test = HealthFileMetric.is_test.is_not(True)
+ cells.append(("history", and_(history, on_file(not_test))))
return cells
def _cells(
- layer: GateLayer, path_col: Any, kind_col: Any, *, file_holds: bool = True
+ layer: GateLayer,
+ path_col: Any,
+ kind_col: Any,
+ *,
+ file_holds: bool = True,
+ hold_history: bool = True,
) -> list[tuple[str, Any]]:
"""``(key, row matches it)`` for each file hold, then each gate on *layer*."""
- cells = _file_holds(layer, path_col, kind_col) if file_holds else []
+ cells = (
+ _file_holds(layer, path_col, kind_col, hold_history=hold_history) if file_holds else []
+ )
for gate in gates_on(layer):
match = or_(*(path_col.ilike(f"%{ext}") for ext in gated_extensions(gate.language)))
if gate.kinds is not None:
@@ -95,11 +102,17 @@ def ungated(
*,
include_unverified: bool = False,
file_holds: bool = True,
+ hold_history: bool = True,
) -> Any:
"""Rows of *layer* no language gate or file hold keeps back (everything when
- opted in). ``file_holds=False`` applies the language gates alone."""
+ opted in). ``file_holds=False`` applies the language gates alone;
+ ``hold_history=False`` keeps history markers on production files."""
cells = (
- [] if include_unverified else _cells(layer, path_col, kind_col, file_holds=file_holds)
+ []
+ if include_unverified
+ else _cells(
+ layer, path_col, kind_col, file_holds=file_holds, hold_history=hold_history
+ )
)
return not_(or_(*(match for _, match in cells))) if cells else true()
@@ -112,6 +125,7 @@ def shown(
requested: Iterable[str] = (),
include_unverified: bool = False,
file_holds: bool = True,
+ hold_history: bool = True,
) -> Any:
"""Rows whose type the registry shows and whose language no gate holds back.
@@ -129,6 +143,7 @@ def shown(
kind_col,
include_unverified=include_unverified,
file_holds=file_holds,
+ hold_history=hold_history,
),
)
@@ -140,6 +155,7 @@ async def gated_counts(
*where: Any,
kind_col: Any = None,
include_unverified: bool = False,
+ hold_history: bool = True,
) -> dict[str, dict]:
"""What the gates on *layer* hold back among *model* rows matching *where*.
@@ -147,7 +163,11 @@ async def gated_counts(
surface can say how many rows it left out and why instead of reading empty.
Empty when ``include_unverified``: nothing was held back.
"""
- cells = [] if include_unverified else _cells(layer, model.file_path, kind_col)
+ cells = (
+ []
+ if include_unverified
+ else _cells(layer, model.file_path, kind_col, hold_history=hold_history)
+ )
if not cells:
return {}
language = case(*((match, lang) for lang, match in cells))
diff --git a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
index f2aff0224..23a44d823 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
@@ -27,7 +27,7 @@ from repowise.core.analysis.dead_code.serving import (
serialize_finding,
summary_counts,
)
-from repowise.core.analysis.finding_registry import excluded_types
+from repowise.core.analysis.finding_registry import excluded_types, served_previews
from repowise.core.persistence.crud import get_dead_code_findings
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import GitMetadata
@@ -111,6 +111,7 @@ async def _get_dead_code_all_repos(
}
apply_limit_note(result_ws)
result_ws["_meta"] = _build_meta()
+ _attach_preview(result_ws)
fed.annotate(result_ws, merged_findings)
return result_ws
@@ -355,6 +356,22 @@ async def get_dead_code(
)
result["_meta"] = _build_meta(repository=repository)
+ _attach_preview(result)
attach_ignored_arguments(result, ignored)
collector.attach(result)
return result
+
+
+def _attach_preview(result: dict[str, Any]) -> None:
+ """``_meta.preview = {"dead_code": {language: note}}`` for the preview
+ languages the tiers list a finding on; absent when none."""
+ rows = (
+ f
+ for t in result.get("tiers", {}).values()
+ if isinstance(t, dict)
+ for f in t.get("findings", [])
+ if isinstance(f, dict)
+ )
+ served = served_previews("dead_code", rows, kind="kind", get=lambda r, k: r.get(k))
+ if served:
+ result["_meta"]["preview"] = {"dead_code": served}
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/details.py b/packages/server/src/repowise/server/mcp_server/tool_health/details.py
index b701dfc65..8be64568e 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/details.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/details.py
@@ -87,8 +87,10 @@ async def _detail_response(
async def _lower_priority(session: Any, repository_id: str, finding: Any) -> str | None:
"""The finding's tier reason, measured over its file's open findings as
- the list measured it."""
- peers = await get_health_findings(session, repository_id, file_path=finding.file_path)
+ the list measured it: file-held rows included, as the list reads them."""
+ peers = await get_health_findings(
+ session, repository_id, file_path=finding.file_path, file_holds=False
+ )
reasons = dict(zip((f.id for f in peers), finding_priorities(peers), strict=True))
return LOW_PRIORITY_LABEL.get(reasons.get(finding.id) or "")
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/tool.py b/packages/server/src/repowise/server/mcp_server/tool_health/tool.py
index a2ddbcaa1..8b90a6490 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/tool.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/tool.py
@@ -13,7 +13,12 @@ from collections import Counter
from time import perf_counter
from typing import Any
-from repowise.core.analysis.finding_registry import FILE_HOLDS, withheld_summary
+from repowise.core.analysis.finding_registry import (
+ FILE_HOLDS,
+ GateLayer,
+ served_previews,
+ withheld_summary,
+)
from repowise.core.analysis.health.counts import DEFAULT_COUNTS
from repowise.core.analysis.health.refactoring.serving import (
DEFAULT_VIEW as _REFACTORING_VIEW_DEFAULT,
@@ -268,6 +273,7 @@ async def get_health(
else:
_attach_health_analysis_meta(result["_meta"], data.pop.all_metrics)
_attach_gated(result["_meta"], data)
+ _attach_preview(result)
_attach_withheld(result, data)
pager.report_omissions(result, omission_collector)
omission_collector.attach(result)
@@ -299,6 +305,67 @@ def _attach_gated(meta: dict[str, Any], data: HealthData) -> None:
meta["gated"] = {**gated, "opt_in": {"include": ["unverified"]}}
+#: The lists that carry rows of a gated layer: ``(layer, the row's kind field)``.
+#: A file row (its score and lead) is health's.
+_LAYER_LISTS: dict[str, tuple[GateLayer, str]] = {
+ "findings": ("health", "biomarker_type"),
+ "top_findings": ("health", "biomarker_type"),
+ "test_findings": ("health", "biomarker_type"),
+ "metrics": ("health", "primary_biomarker"),
+ "worst_files": ("health", "primary_biomarker"),
+ "test_worst_files": ("health", "primary_biomarker"),
+ "high_leverage_files": ("health", "primary_biomarker"),
+ "refactoring_plans": ("refactoring", "refactoring_type"),
+ "refactoring_opportunities": ("refactoring", "lead_refactoring_type"),
+ "performance_opportunities": ("performance", "biomarker_type"),
+}
+
+#: A Fix-first item's kind, as the layer it was built from.
+_FIX_KIND_LAYER: dict[str, GateLayer] = {
+ "finding": "health",
+ "refactor": "refactoring",
+ "perf_fix": "performance",
+}
+
+
+def _fix_first_rows(result: dict[str, Any]) -> dict[GateLayer, list[dict[str, Any]]]:
+ """The listed Fix-first items (lead included) as ``file_path`` rows by layer."""
+ block = result.get("fix_first")
+ if not isinstance(block, dict):
+ return {}
+ items = [*(block.get("items") or []), block.get("lead")]
+ out: dict[GateLayer, list[dict[str, Any]]] = {}
+ for item in items:
+ if isinstance(item, dict) and (layer := _FIX_KIND_LAYER.get(item.get("kind") or "")):
+ path = (item.get("target") or {}).get("file_path")
+ out.setdefault(layer, []).append({"file_path": path})
+ return out
+
+
+def _attach_preview(result: dict[str, Any]) -> None:
+ """``_meta.preview``: ``{layer: {language: note}}`` for the preview cells
+ this response lists rows from, read after projection so only what was
+ sent is labelled. Absent when none, so a default response does not grow."""
+ sources: list[tuple[GateLayer, str, list[Any]]] = [
+ (layer, kind, rows)
+ for key, (layer, kind) in _LAYER_LISTS.items()
+ if isinstance(rows := result.get(key), list)
+ ]
+ sources += [(layer, "kind", rows) for layer, rows in _fix_first_rows(result).items()]
+ preview: dict[str, dict[str, str]] = {}
+ for layer, kind, rows in sources:
+ served = served_previews(
+ layer,
+ (r for r in rows if isinstance(r, dict)),
+ kind=kind,
+ get=lambda r, k: r.get(k),
+ )
+ if served:
+ preview.setdefault(layer, {}).update(served)
+ if preview:
+ result["_meta"]["preview"] = preview
+
+
def _attach_withheld(result: dict[str, Any], data: HealthData) -> None:
"""The withheld types behind the ``withheld_deduction`` of each emitted
file row, so none is unexplained. Absent when no emitted row carries one."""
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py
index dfeba6857..abc9dd059 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py
@@ -358,7 +358,13 @@ async def _enrich_health(results: list[dict], ctx: Any, repo_id: str) -> None:
HealthFinding.file_path.in_(target_paths),
HealthFinding.status == "open",
HealthFinding.biomarker_type.not_in(excluded_types()),
- ungated("health", HealthFinding.file_path, HealthFinding.biomarker_type),
+ # get_risk is about history: its history markers stay.
+ ungated(
+ "health",
+ HealthFinding.file_path,
+ HealthFinding.biomarker_type,
+ hold_history=False,
+ ),
)
.order_by(HealthFinding.health_impact.desc())
)
diff --git a/packages/server/src/repowise/server/routers/actions.py b/packages/server/src/repowise/server/routers/actions.py
index 1081dda23..3f0bc613b 100644
--- a/packages/server/src/repowise/server/routers/actions.py
+++ b/packages/server/src/repowise/server/routers/actions.py
@@ -46,6 +46,8 @@ async def _require_repo(session: AsyncSession, repo_id: str) -> Repository:
@router.get(
"/api/repos/{repo_id}/actions/{action_id}/prompt",
response_model=AgentPromptResponse,
+ # ``preview`` is sent only when the item sits on a preview cell.
+ response_model_exclude_none=True,
)
async def get_action_prompt(
repo_id: str,
diff --git a/packages/server/src/repowise/server/routers/code_health/files_routes.py b/packages/server/src/repowise/server/routers/code_health/files_routes.py
index 150620ccc..2b4a5078a 100644
--- a/packages/server/src/repowise/server/routers/code_health/files_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/files_routes.py
@@ -111,7 +111,9 @@ async def list_health_files(
if summary:
findings = await crud.get_health_findings(session, repo_id, dimension="performance")
else:
- findings = await crud.get_health_findings(session, repo_id)
+ # History markers kept: a file's lead names what its score counted, so a
+ # history-only file scoring below 10 still has one.
+ findings = await crud.get_health_findings(session, repo_id, hold_history=False)
# Leads only for the page's files — enough to carry the top-reason chip
# and the magnitude tiebreak without loading every finding for every row.
page_paths = {m.file_path for m in page}
@@ -171,26 +173,37 @@ async def file_score_breakdown(
findings = await crud.get_health_findings(
session, repo_id, file_path=file_path, include_unverified=True
)
+ files = {m.file_path: m for m in metrics}
# The score counts every finding; a gated one is held back from the list
- # and the breakdown, and ``gated`` says how many.
+ # and the breakdown, and ``gated`` says how many. History markers are held
+ # from the list only: the breakdown and the lead still sum what the score
+ # counted.
+ scored, _ = split_gated(
+ "health",
+ findings,
+ kind="biomarker_type",
+ include_unverified=include_unverified,
+ files=files,
+ hold_history=False,
+ )
findings, gated = split_gated(
"health",
findings,
kind="biomarker_type",
include_unverified=include_unverified,
- files={m.file_path: m for m in metrics},
+ files=files,
)
# This drawer opens from a row the reader just saw a score on. Reading it
# under the other counts would answer a click on 8.5 with a 2.0 and list
# the findings the page had just said were excluded.
- metrics, findings, _unscored = project(counts, metrics, findings)
+ metrics, scored, findings, _unscored = project(counts, metrics, scored, findings)
metric = metrics[0] if metrics else None
# No breakdown of a score the file does not have (no health dialect for
# its language): one rebuilt from its findings would read 10.0.
breakdown = (
None
if metric is not None and metric.score is None
- else _score_breakdown_from_findings(findings)
+ else _score_breakdown_from_findings(scored)
)
finding_dicts = await _attach_symbol_ids(
session, repo_id, [_finding_to_dict(f) for f in findings]
@@ -200,7 +213,7 @@ async def file_score_breakdown(
)
return {
"file_path": file_path,
- "metric": _metric_to_dict(metric, _primary_and_magnitude(findings)) if metric else None,
+ "metric": _metric_to_dict(metric, _primary_and_magnitude(scored)) if metric else None,
"breakdown": breakdown,
"findings": finding_dicts,
"gated": gated,
diff --git a/packages/server/src/repowise/server/routers/code_health/findings_routes.py b/packages/server/src/repowise/server/routers/code_health/findings_routes.py
index 7be2e8b7a..147d4ec4f 100644
--- a/packages/server/src/repowise/server/routers/code_health/findings_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/findings_routes.py
@@ -89,6 +89,10 @@ async def list_health_findings(
# The exclusion holds for the list that ranks the whole repository against
# itself. See the docstring for the three ways out.
ranks_everything = biomarker_type is None and not include_zero_impact
+ # A file's list is the set the work queue counted its row from, and that
+ # queue reads history markers (it counts history-only files itself), so
+ # one file's findings keep them; the repo-wide list holds them back.
+ hold_history = file_path is None
findings = await crud.get_health_findings(
session,
repo_id,
@@ -102,6 +106,7 @@ async def list_health_findings(
tuple(sorted(ZERO_IMPACT_DIMENSIONS)) if ranks_everything else None
),
include_unverified=include_unverified,
+ hold_history=hold_history,
)
# A finding carries a path, not ``is_test``, so narrowing it needs the
# metric rows that do. Read them only when the answer depends on them:
@@ -117,7 +122,11 @@ async def list_health_findings(
# The body is a list, so what a language gate or file hold left out rides
# in a header: ``{key: {count, reason}}``, absent when nothing was held.
gated = await crud.gated_health_counts(
- session, repo_id, file_path=file_path, include_unverified=include_unverified
+ session,
+ repo_id,
+ file_path=file_path,
+ include_unverified=include_unverified,
+ hold_history=hold_history,
)
if gated:
response.headers[GATED_HEADER] = json.dumps(gated, separators=(",", ":"))
diff --git a/packages/server/src/repowise/server/routers/code_health/fix_first_routes.py b/packages/server/src/repowise/server/routers/code_health/fix_first_routes.py
index ec10ec8e1..9bbcd933b 100644
--- a/packages/server/src/repowise/server/routers/code_health/fix_first_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/fix_first_routes.py
@@ -13,6 +13,7 @@ from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.agent_prompts import Flavor, render_fix_item
+from repowise.core.analysis.finding_registry import GateLayer, preview_label
from repowise.core.analysis.health.fix_first import FIX_SCOPES, FixItem
from repowise.core.analysis.health.fix_first.model import FixTotals
from repowise.core.analysis.health.queue.counts import QueueCounts
@@ -85,6 +86,8 @@ async def get_fix_first_item(
@router.get(
"/api/repos/{repo_id}/health/fix-first/{fix_id}/prompt",
response_model=AgentPromptResponse,
+ # ``preview`` is sent only when the item sits on a preview cell.
+ response_model_exclude_none=True,
)
async def get_fix_first_item_prompt(
repo_id: str,
@@ -95,7 +98,18 @@ async def get_fix_first_item_prompt(
) -> AgentPromptResponse:
"""One item as the prompt an agent starts from, worded for its harness."""
repo, item = await _item(session, repo_id, fix_id, scope)
- return AgentPromptResponse(flavor=flavor, text=render_fix_item(item.as_dict(), flavor, repo.name))
+ text = render_fix_item(item.as_dict(), flavor, repo.name)
+ layer = _FIX_KIND_LAYER.get(item.kind)
+ note = preview_label(layer, item.target.file_path) if layer else None
+ return AgentPromptResponse.labelled(flavor, text, note)
+
+
+#: A Fix-first item's kind, as the layer it was built from.
+_FIX_KIND_LAYER: dict[str, GateLayer] = {
+ "finding": "health",
+ "refactor": "refactoring",
+ "perf_fix": "performance",
+}
__all__ = ["get_fix_first", "get_fix_first_item", "get_fix_first_item_prompt"]
diff --git a/packages/server/src/repowise/server/routers/code_health/performance_routes.py b/packages/server/src/repowise/server/routers/code_health/performance_routes.py
index 2e38ffc6d..59761a7df 100644
--- a/packages/server/src/repowise/server/routers/code_health/performance_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/performance_routes.py
@@ -13,6 +13,7 @@ from typing import Any
from fastapi import Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.finding_registry import label_previews
from repowise.core.analysis.health.perf.serving import parse_query
from repowise.server.deps import get_db_session
from repowise.server.services.performance_health import PerformanceHealthService
@@ -120,7 +121,9 @@ async def list_performance_opportunities(
query, evidence_per_item=_EVIDENCE_PER_ITEM, with_facets=True, with_summary=True
)
return {
- "items": [_item(item) for item in page.items],
+ "items": label_previews(
+ "performance", [_item(item) for item in page.items], kind="biomarker_type"
+ ),
"total": page.total,
"has_more": page.next_offset is not None,
"next_offset": page.next_offset,
@@ -148,7 +151,7 @@ async def get_performance_opportunity_detail(
detail = await _service(session, repo_id).detail(
opportunity_id, evidence_limit=evidence_limit, evidence_offset=evidence_offset
)
- return _item(detail)
+ return label_previews("performance", [_item(detail)], kind="biomarker_type")[0]
@router.get("/api/repos/{repo_id}/health/performance-opportunities/{opportunity_id}/findings")
@@ -165,7 +168,7 @@ async def list_performance_opportunity_findings(
)
emitted = offset + len(items)
return {
- "items": items,
+ "items": label_previews("performance", items, kind="biomarker_type"),
"total": total,
"has_more": emitted < total,
"next_offset": emitted if emitted < total else None,
diff --git a/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py b/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py
index f01fa60c9..e4028cc3d 100644
--- a/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py
@@ -12,6 +12,7 @@ from typing import Any
from fastapi import Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.finding_registry import label_previews
from repowise.core.analysis.health.impact_effort import (
WORK_QUEUE_SORTS,
build_impact_effort,
@@ -105,6 +106,9 @@ async def _load_queue_rows(
exclude_dimensions=(
tuple(sorted(ZERO_IMPACT_DIMENSIONS)) if q.biomarker is None else None
),
+ # The queue counts history-only files itself (``history_only_excluded``)
+ # and ``history=include`` lists them, so it reads history markers.
+ hold_history=False,
)
metrics, findings = narrow(q.scope, metrics, findings)
metrics, findings, _unscored = project(q.counts, metrics, findings)
@@ -180,7 +184,9 @@ async def health_work_queue(
# Both counts, because the view lists files but triages findings: "50 of
# 812 files" alone leaves the size of the work unsaid.
return {
- "targets": targets[offset : offset + limit],
+ "targets": label_previews(
+ "health", targets[offset : offset + limit], kind="primary_biomarker"
+ ),
"total": len(targets),
"finding_total": sum(t["finding_count"] for t in targets),
"history_only_excluded": history_only,
diff --git a/packages/server/src/repowise/server/routers/code_health/related_work_routes.py b/packages/server/src/repowise/server/routers/code_health/related_work_routes.py
index 91a09e5e1..1af99ef87 100644
--- a/packages/server/src/repowise/server/routers/code_health/related_work_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/related_work_routes.py
@@ -12,6 +12,7 @@ from typing import Any
from fastapi import Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.finding_registry import GateLayer, preview_label
from repowise.core.analysis.related_work import related_work
from repowise.core.persistence import crud
from repowise.core.persistence.crud.analysis.fix_first import load_fix_first
@@ -100,7 +101,7 @@ async def get_related_work(
dead_code = await crud.get_dead_code_findings(
session, repo_id, file_paths=paths, limit=_ROWS_CEILING
)
- return related_work(
+ body = related_work(
paths,
findings=findings,
fix_first=queue.items,
@@ -108,6 +109,22 @@ async def get_related_work(
performance=performance,
dead_code=dead_code,
).as_dict()
+ # One file's rows share its language, so a lens carries one label. Fix
+ # first mixes layers, so it carries none.
+ for entry in body["files"]:
+ for lens, block in entry["lenses"].items():
+ layer = _LENS_LAYER.get(lens)
+ if layer and (note := preview_label(layer, entry["file_path"])):
+ block["preview"] = note
+ return body
+
+
+_LENS_LAYER: dict[str, GateLayer] = {
+ "findings": "health",
+ "refactoring": "refactoring",
+ "performance": "performance",
+ "dead_code": "dead_code",
+}
__all__ = ["get_related_work"]
diff --git a/packages/server/src/repowise/server/routers/code_health/serializers.py b/packages/server/src/repowise/server/routers/code_health/serializers.py
index 37886454e..cb13a0fc4 100644
--- a/packages/server/src/repowise/server/routers/code_health/serializers.py
+++ b/packages/server/src/repowise/server/routers/code_health/serializers.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import json
from typing import Any
-from repowise.core.analysis.finding_registry import verification_label
+from repowise.core.analysis.finding_registry import preview_label, verification_label
from repowise.core.analysis.health.aggregation import (
primary_and_magnitude,
primary_and_magnitude_by_file,
@@ -40,6 +40,8 @@ def _finding_to_dict(f: Any, lower_priority: str | None = None) -> dict:
# "unverified" for a provisional type a caller asked for by name.
"verification": verification_label(f.biomarker_type),
"lower_priority": LOW_PRIORITY_LABEL.get(lower_priority or ""),
+ # The measurement label on a language the layer serves as a preview.
+ "preview": preview_label("health", f.file_path, f.biomarker_type),
}
diff --git a/packages/server/src/repowise/server/routers/files.py b/packages/server/src/repowise/server/routers/files.py
index 4964a02ed..3af7209a2 100644
--- a/packages/server/src/repowise/server/routers/files.py
+++ b/packages/server/src/repowise/server/routers/files.py
@@ -308,21 +308,22 @@ async def file_detail(
)
# The score counts every finding; one a gate or file hold keeps back is left
# out of the list and breakdown, and ``gated`` says how many and why.
- findings, gated = split_gated(
- "health",
- findings,
- kind="biomarker_type",
- files={metric.file_path: metric} if metric is not None else None,
+ # History markers are held from the list only: the breakdown and the lead
+ # sum what the score counted.
+ held_files = {metric.file_path: metric} if metric is not None else None
+ scored, _ = split_gated(
+ "health", findings, kind="biomarker_type", files=held_files, hold_history=False
)
+ findings, gated = split_gated("health", findings, kind="biomarker_type", files=held_files)
snapshots = await crud.list_health_snapshots(
session, repo_id, limit=crud.FILE_TREND_SNAPSHOT_WINDOW
)
health = {
- "metric": _metric_to_dict(metric, _primary_and_magnitude(findings)) if metric else None,
+ "metric": _metric_to_dict(metric, _primary_and_magnitude(scored)) if metric else None,
# None for a file with no score: rebuilt from findings it would read 10.0.
"breakdown": (
- _score_breakdown_from_findings(findings)
- if findings and not (metric is not None and metric.score is None)
+ _score_breakdown_from_findings(scored)
+ if scored and not (metric is not None and metric.score is None)
else None
),
"findings": [_finding_dict(f, slim=slim) for f in findings],
diff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.py
index bc3003ff8..336fb7ac1 100644
--- a/packages/server/src/repowise/server/routers/refactoring.py
+++ b/packages/server/src/repowise/server/routers/refactoring.py
@@ -23,6 +23,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.agent_prompts import Flavor, render_opportunity, render_plan
+from repowise.core.analysis.finding_registry import label_previews, preview_label
from repowise.core.analysis.health.refactoring.recipe import build_recipe
from repowise.core.analysis.health.refactoring.serving import (
CANONICAL_ORDERS,
@@ -105,6 +106,7 @@ async def get_refactoring_targets(
view=view,
)
)
+ body["plans"] = label_previews("refactoring", body["plans"], kind="refactoring_type")
return RefactoringTargetsResponse(
**body,
gated=await gated_plan_counts(session, repo_id, include_unverified=include_unverified),
@@ -194,7 +196,7 @@ async def get_refactoring_opportunities(
with_summary=True,
)
body: dict[str, Any] = {
- "items": page.items,
+ "items": label_previews("refactoring", page.items, kind="lead_refactoring_type"),
"total": page.total,
"offset": page.offset,
"has_more": page.next_offset is not None,
@@ -249,12 +251,14 @@ async def get_refactoring_opportunity_detail(
)
if not detail.get("found"):
raise HTTPException(status_code=404, detail="Unknown opportunity id")
- return detail
+ return label_previews("refactoring", [detail], kind="lead_refactoring_type")[0]
@router.get(
"/{repo_id}/refactoring/opportunities/{opportunity_id}/prompt",
response_model=AgentPromptResponse,
+ # ``preview`` is sent only when the item sits on a preview cell.
+ response_model_exclude_none=True,
)
async def get_refactoring_opportunity_prompt(
repo_id: str,
@@ -270,7 +274,10 @@ async def get_refactoring_opportunity_prompt(
if not detail.get("found"):
raise HTTPException(status_code=404, detail="Unknown opportunity id")
text = render_opportunity(detail, flavor, repo.name)
- return AgentPromptResponse(flavor=flavor, text=text)
+ note = preview_label(
+ "refactoring", detail.get("file_path") or "", detail.get("lead_refactoring_type")
+ )
+ return AgentPromptResponse.labelled(flavor, text, note)
@router.patch(
@@ -365,6 +372,7 @@ async def get_refactoring_plan(
detail, public_id = await _plan_detail(session, repo_id, suggestion_id)
if include == "recipe":
detail["recipe"] = build_recipe({**detail, "id": public_id})
+ (detail,) = label_previews("refactoring", [detail], kind="refactoring_type")
return RefactoringPlanDetailResponse(**detail)
@@ -391,6 +399,8 @@ async def _repository(session: AsyncSession, repo_id: str) -> Any:
@router.get(
"/{repo_id}/refactoring/{suggestion_id}/prompt",
response_model=AgentPromptResponse,
+ # ``preview`` is sent only when the item sits on a preview cell.
+ response_model_exclude_none=True,
)
async def get_refactoring_plan_prompt(
repo_id: str,
@@ -402,7 +412,8 @@ async def get_refactoring_plan_prompt(
repo = await _repository(session, repo_id)
detail, public_id = await _plan_detail(session, repo_id, suggestion_id)
text = render_plan({**detail, "id": public_id}, flavor, repo.name)
- return AgentPromptResponse(flavor=flavor, text=text)
+ note = preview_label("refactoring", detail.get("file_path") or "", detail.get("refactoring_type"))
+ return AgentPromptResponse.labelled(flavor, text, note)
@router.patch(
diff --git a/packages/server/src/repowise/server/schemas/agent_prompts.py b/packages/server/src/repowise/server/schemas/agent_prompts.py
index 9b3ade165..814f7127f 100644
--- a/packages/server/src/repowise/server/schemas/agent_prompts.py
+++ b/packages/server/src/repowise/server/schemas/agent_prompts.py
@@ -10,3 +10,14 @@ from repowise.core.agent_prompts import Flavor
class AgentPromptResponse(BaseModel):
flavor: Flavor
text: str
+ #: The measurement note when the item sits on a preview language cell
+ #: (``finding_registry.preview_note``); the text then ends with it too.
+ preview: str | None = None
+
+ @classmethod
+ def labelled(cls, flavor: Flavor, text: str, preview: str | None) -> AgentPromptResponse:
+ """The prompt, with one closing line naming the preview when set, so
+ the agent reading the text sees the measurement the page shows."""
+ if preview:
+ text = f"{text.rstrip()}\n\nThis language is served as a {preview}.\n"
+ return cls(flavor=flavor, text=text, preview=preview)
diff --git a/packages/server/src/repowise/server/schemas/code_health.py b/packages/server/src/repowise/server/schemas/code_health.py
index ae19ed8e4..6e5db1371 100644
--- a/packages/server/src/repowise/server/schemas/code_health.py
+++ b/packages/server/src/repowise/server/schemas/code_health.py
@@ -34,6 +34,9 @@ class HealthFindingResponse(BaseModel):
verification: str | None = None
#: Why the finding can wait, on a lower-priority finding; else ``None``.
lower_priority: str | None = None
+ #: The measurement note on a language health is served as a preview on
+ #: (``finding_registry.preview_note``); else ``None``.
+ preview: str | None = None
class HealthFindingWithSymbolResponse(HealthFindingResponse):
@@ -201,6 +204,8 @@ class HealthWorkItem(BaseModel):
#: S | M | L | XL
effort_bucket: str
impact_per_effort: float
+ #: The measurement note on a language health is served as a preview on.
+ preview: str | None = None
class HealthWorkQueueResponse(BaseModel):
@@ -279,6 +284,9 @@ class RelatedWorkLens(BaseModel):
items: list[RelatedWorkItem] = []
#: Every row the lens holds for the file; ``items`` stops at the limit.
total: int = 0
+ #: The measurement note when the lens's layer is a preview on the file's
+ #: language; the file's rows share it.
+ preview: str | None = None
class RelatedWorkFile(BaseModel):
diff --git a/packages/server/src/repowise/server/schemas/code_quality.py b/packages/server/src/repowise/server/schemas/code_quality.py
index f246420db..3ee1ba925 100644
--- a/packages/server/src/repowise/server/schemas/code_quality.py
+++ b/packages/server/src/repowise/server/schemas/code_quality.py
@@ -11,7 +11,7 @@ from repowise.core.analysis.dead_code.deletion_gate import effective_safe_to_del
from repowise.core.analysis.dead_code.risk_factors import (
path_risk_factors,
)
-from repowise.core.analysis.finding_registry import verification_label
+from repowise.core.analysis.finding_registry import preview_label, verification_label
class DeadCodeFindingResponse(BaseModel):
@@ -48,6 +48,8 @@ class DeadCodeFindingResponse(BaseModel):
commit_count_90d: int
# ``"unverified"`` for a provisional kind a caller asked for by name.
verification: str | None = None
+ #: The measurement note on a language dead code is served as a preview on.
+ preview: str | None = None
@classmethod
def from_orm(cls, obj: object) -> DeadCodeFindingResponse:
@@ -85,6 +87,7 @@ class DeadCodeFindingResponse(BaseModel):
last_commit_at=obj.last_commit_at, # type: ignore[attr-defined]
commit_count_90d=obj.commit_count_90d, # type: ignore[attr-defined]
verification=verification_label(obj.kind), # type: ignore[attr-defined]
+ preview=preview_label("dead_code", file_path, obj.kind), # type: ignore[attr-defined]
)
diff --git a/packages/server/src/repowise/server/schemas/refactoring.py b/packages/server/src/repowise/server/schemas/refactoring.py
index 3e053ff31..e14eb314d 100644
--- a/packages/server/src/repowise/server/schemas/refactoring.py
+++ b/packages/server/src/repowise/server/schemas/refactoring.py
@@ -102,6 +102,8 @@ class RefactoringOpportunityDetailResponse(BaseModel):
plans: list[dict[str, Any]] | None = None
#: Present when a step names a symbol an earlier step moves.
ordering_note: str | None = None
+ #: The measurement note on a language refactoring is served as a preview on.
+ preview: str | None = None
# Plan-level shapes: the plan lists, one plan, triage bodies and code generation.
@@ -146,6 +148,8 @@ class RefactoringPlanResponse(BaseModel):
file_nloc: int = 0
file_weighted_deficit: int = 0
validation: dict[str, Any] = Field(default_factory=dict)
+ #: The measurement note on a language refactoring is served as a preview on.
+ preview: str | None = None
class PlanRiskResponse(BaseModel):
diff --git a/packages/server/src/repowise/server/services/attention.py b/packages/server/src/repowise/server/services/attention.py
index 037491752..bf1347aca 100644
--- a/packages/server/src/repowise/server/services/attention.py
+++ b/packages/server/src/repowise/server/services/attention.py
@@ -84,7 +84,12 @@ async def _health_items(session: AsyncSession, repo_id: str) -> tuple[list[dict]
HealthFinding.status == "open",
HealthFinding.file_path.not_in(_test_paths(repo_id)),
HealthFinding.biomarker_type.not_in(excluded_types()),
- ungated("health", HealthFinding.file_path, HealthFinding.biomarker_type),
+ # Ranks areas by summed impact, as hotspots do, and names a history
+ # marker only when nothing an edit can fix is there: history is
+ # already context here, so it stays in the sum.
+ ungated(
+ "health", HealthFinding.file_path, HealthFinding.biomarker_type, hold_history=False
+ ),
)
rows = (
await session.execute(
diff --git a/packages/types/src/dead-code.ts b/packages/types/src/dead-code.ts
index dc9f5049d..0035e5f64 100644
--- a/packages/types/src/dead-code.ts
+++ b/packages/types/src/dead-code.ts
@@ -107,6 +107,9 @@ export interface DeadCodeFinding {
/** Raw engine artifact fields — present in some downstream pipelines, optional here. */
evidence?: string[] | null;
age_days?: number | null;
+ /** The measurement note when the row's language cell is served as a preview;
+ * null or absent for a validated cell. */
+ preview?: string | null;
}
export interface DeadCodePatchInput {
diff --git a/packages/types/src/files.ts b/packages/types/src/files.ts
index cd505d224..9432f6412 100644
--- a/packages/types/src/files.ts
+++ b/packages/types/src/files.ts
@@ -39,6 +39,9 @@ export interface FileHealthFinding {
/** `"unverified"` for a provisional finding type; null for a validated one. */
verification?: string | null;
lower_priority?: string | null;
+ /** The measurement note when the row's language cell is served as a preview;
+ * null or absent for a validated cell. */
+ preview?: string | null;
}
export interface FileHealthMetric {
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 80f9f4276..909b10cf1 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -106,6 +106,7 @@ export interface ActiveProviderSelection {
export interface AgentPromptResponse {
flavor: "generic" | "claude-code" | "claude-code-mcp" | "cursor";
text: string;
+ preview?: string | null;
}
/** One month of commits by attribution label. */
@@ -1133,6 +1134,7 @@ export interface DeadCodeFindingResponse {
last_commit_at: string | null;
commit_count_90d: number;
verification?: string | null;
+ preview?: string | null;
}
export interface DeadCodeGraphNodeResponse {
@@ -2184,6 +2186,7 @@ export interface HealthFindingResponse {
dimension?: string;
verification?: string | null;
lower_priority?: string | null;
+ preview?: string | null;
}
/**
@@ -2207,6 +2210,7 @@ export interface HealthFindingWithSymbolResponse {
dimension?: string;
verification?: string | null;
lower_priority?: string | null;
+ preview?: string | null;
symbol_id?: string | null;
}
@@ -2283,6 +2287,7 @@ export interface HealthWorkItem {
biomarkers?: string[];
effort_bucket: string;
impact_per_effort: number;
+ preview?: string | null;
}
export interface HealthWorkQueueResponse {
@@ -3122,6 +3127,7 @@ export interface RefactoringOpportunityDetailResponse {
next_actions?: Record<string, unknown>[];
plans?: Record<string, unknown>[] | null;
ordering_note?: string | null;
+ preview?: string | null;
}
/** What one opportunity-level triage decision wrote. */
@@ -3166,6 +3172,7 @@ export interface RefactoringPlanDetailResponse {
file_nloc?: number;
file_weighted_deficit?: number;
validation?: Record<string, unknown>;
+ preview?: string | null;
governed_by?: string[] | null;
risks?: PlanRiskResponse[] | null;
recipe?: Record<string, unknown> | null;
@@ -3199,6 +3206,7 @@ export interface RefactoringPlanResponse {
file_nloc?: number;
file_weighted_deficit?: number;
validation?: Record<string, unknown>;
+ preview?: string | null;
}
/** What one plan-level triage decision wrote. */
@@ -3286,6 +3294,7 @@ export interface RelatedWorkItem {
export interface RelatedWorkLens {
items?: RelatedWorkItem[];
total?: number;
+ preview?: string | null;
}
/** The files to look up, repo-relative. Validated by the route. */
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index 9f199f7b4..39231acdd 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -351,6 +351,9 @@ export interface HealthFinding {
/** Why the finding can wait ("lower priority: ..."); null when it is worth
* doing first. Lower-priority findings are listed after the rest. */
lower_priority?: string | null;
+ /** The measurement note when the row's language cell is served as a preview;
+ * null or absent for a validated cell. */
+ preview?: string | null;
}
export type PerformanceExecutionContext = "production" | "tooling" | "test" | "unknown";
@@ -524,6 +527,9 @@ export interface PerformanceOpportunity {
/** Why the opportunity can wait ("lower priority: ..."); null when its
* production loop is known to grow with the data. */
lower_priority?: string | null;
+ /** The measurement note when the row's language cell is served as a preview;
+ * null or absent for a validated cell. */
+ preview?: string | null;
/** Exact stored match. Never inferred from file, marker, or rank. */
plan_id: string | null;
plan_status: PerformancePlanStatus;
diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.ts
index f246d3534..b1e90daf3 100644
--- a/packages/types/src/refactoring.ts
+++ b/packages/types/src/refactoring.ts
@@ -141,6 +141,9 @@ export interface RefactoringPlan {
recipe?: RefactoringRecipe;
/** Plan detail only, on a plan the index resolved as no longer detected. */
payoff?: RefactoringPlanPayoff;
+ /** The measurement note when the row's language cell is served as a preview;
+ * null or absent for a validated cell. */
+ preview?: string | null;
}
/** What happened to a resolved plan. Mirrors ``refactoring.payoff.PAYOFF_OUTCOMES``. */
@@ -490,6 +493,9 @@ export interface RefactoringOpportunity {
evidence_truncated?: boolean;
evidence_reduced_reason?: string;
evidence_next_cursor?: number;
+ /** The measurement note when the row's language cell is served as a preview;
+ * null or absent for a validated cell. */
+ preview?: string | null;
}
/**
diff --git a/packages/ui/__tests__/health/performance-view.test.tsx b/packages/ui/__tests__/health/performance-view.test.tsx
index 0776b3c9f..79033f29a 100644
--- a/packages/ui/__tests__/health/performance-view.test.tsx
+++ b/packages/ui/__tests__/health/performance-view.test.tsx
@@ -1061,3 +1061,14 @@ describe("ScopeLine", () => {
expect(screen.getByRole("status").textContent).toContain(expected);
});
});
+
+describe("performance drawer preview", () => {
+ it("marks the cause when the detail response carries a preview note", async () => {
+ const note = "preview, measured 40% precision on 30 judged causes, 2026-10-15";
+ const getDetail = vi.fn(async () => resolvedDetail({ preview: note }));
+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunity: getDetail })} />);
+ await openFirstRow();
+ const panel = await screen.findByRole("dialog");
+ expect(await within(panel).findByRole("button", { name: `Preview: ${note}` })).toBeTruthy();
+ });
+});
diff --git a/packages/ui/__tests__/health/preview-badge.test.tsx b/packages/ui/__tests__/health/preview-badge.test.tsx
new file mode 100644
index 000000000..7bc6ab669
--- /dev/null
+++ b/packages/ui/__tests__/health/preview-badge.test.tsx
@@ -0,0 +1,100 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+
+import { PreviewBadge, PreviewBadgeStringsContext } from "../../src/health/preview-badge";
+import { RefactoringCard } from "../../src/health/refactoring-card";
+import { PerformanceView } from "../../src/health/performance-view";
+import { adapter, opportunity, page } from "./fixtures/performance";
+
+const NOTE = "preview, measured 22% precision on 55 judged plans from 2 Java repos, 2026-10-15";
+
+describe("PreviewBadge", () => {
+ it("names the note in its label and shows it in a tooltip on focus", async () => {
+ render(<PreviewBadge note={NOTE} />);
+ const badge = screen.getByRole("button", { name: `Preview: ${NOTE}` });
+ expect(badge.textContent).toBe("Preview");
+ fireEvent.focus(badge);
+ expect((await screen.findAllByText(NOTE)).length).toBeGreaterThan(0);
+ });
+
+ it("uses the strings a host provides", () => {
+ render(
+ <PreviewBadgeStringsContext.Provider value={{ label: "预览", ariaLabel: (n) => `预览:${n}` }}>
+ <PreviewBadge note={NOTE} />
+ </PreviewBadgeStringsContext.Provider>,
+ );
+ expect(screen.getByRole("button", { name: `预览:${NOTE}` }).textContent).toBe("预览");
+ });
+
+ it("lets an explicit label override the provided one", () => {
+ render(<PreviewBadge note={NOTE} label="Beta" />);
+ expect(screen.getByRole("button", { name: `Beta: ${NOTE}` }).textContent).toBe("Beta");
+ });
+
+ it.each([undefined, null, "", " "])("renders nothing for %p", (note) => {
+ const { container } = render(<PreviewBadge note={note} />);
+ expect(container.firstChild).toBeNull();
+ });
+});
+
+describe("Preview badge on list rows", () => {
+ it("marks the preview finding in a file's findings and leaves the other unmarked", () => {
+ render(
+ <RefactoringCard
+ target={{
+ file_path: "src/main/java/App.java",
+ score: 4,
+ nloc: 300,
+ primary_biomarker: "brain_method",
+ primary_severity: "high",
+ primary_reason: "Oversized function.",
+ primary_function: "run",
+ primary_line_start: 10,
+ primary_line_end: 200,
+ total_impact: 3,
+ finding_count: 2,
+ biomarkers: ["brain_method"],
+ effort_bucket: "L",
+ impact_per_effort: 1,
+ all_findings: [
+ { id: "a", biomarker_type: "brain_method", severity: "high", function_name: "run", health_impact: 2, reason: "Oversized function.", preview: NOTE },
+ { id: "b", biomarker_type: "error_handling", severity: "low", function_name: null, health_impact: 1, reason: "Broad catch.", preview: null },
+ ],
+ }}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: /Show all 2 findings/ }));
+ expect(document.querySelectorAll("[data-preview]")).toHaveLength(1);
+ });
+
+ it("marks a work-queue card whose file is served from a preview cell", () => {
+ render(
+ <RefactoringCard
+ target={{
+ file_path: "src/main/java/App.java",
+ score: 4,
+ nloc: 300,
+ primary_biomarker: "brain_method",
+ primary_severity: "high",
+ primary_reason: "Oversized function.",
+ primary_function: "run",
+ primary_line_start: 10,
+ primary_line_end: 200,
+ total_impact: 3,
+ finding_count: 1,
+ biomarkers: ["brain_method"],
+ effort_bucket: "L",
+ impact_per_effort: 1,
+ preview: NOTE,
+ }}
+ />,
+ );
+ expect(screen.getByRole("button", { name: `Preview: ${NOTE}` })).toBeTruthy();
+ });
+
+ it("marks a preview performance opportunity in the queue", async () => {
+ const item = opportunity({ preview: NOTE });
+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: async () => page({ items: [item] }) })} />);
+ expect(await screen.findByRole("button", { name: `Preview: ${NOTE}` })).toBeTruthy();
+ });
+});
diff --git a/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsx b/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsx
index d20153e0f..cde2a2045 100644
--- a/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsx
+++ b/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsx
@@ -417,3 +417,24 @@ describe("RefactoringDrawer risks", () => {
expect(screen.queryByText("Before you start")).toBeNull();
});
});
+
+describe("OpportunityDrawer preview", () => {
+ const NOTE = "preview, measured 22% precision on 55 judged plans from 2 Java repos, 2026-10-15";
+
+ it("marks a preview opportunity and its preview plan", () => {
+ renderDrawer(
+ detail({
+ preview: NOTE,
+ steps: [STEP],
+ steps_emitted: 1,
+ plans: [{ ...PLAN, preview: NOTE }],
+ }),
+ );
+ expect(screen.getAllByRole("button", { name: `Preview: ${NOTE}` })).toHaveLength(2);
+ });
+
+ it("carries no mark for a validated cell", () => {
+ renderDrawer(detail({ steps: [STEP], steps_emitted: 1, plans: [PLAN] }));
+ expect(document.querySelector("[data-preview]")).toBeNull();
+ });
+});
diff --git a/packages/ui/src/dead-code/finding-cells.tsx b/packages/ui/src/dead-code/finding-cells.tsx
index 33a3a4bcc..c11454d05 100644
--- a/packages/ui/src/dead-code/finding-cells.tsx
+++ b/packages/ui/src/dead-code/finding-cells.tsx
@@ -10,6 +10,7 @@ import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
import { formatConfidence } from "../lib/format";
import { toFriendlyMessage } from "../lib/errors";
import { cn } from "../lib/cn";
+import { PreviewBadge } from "../health/preview-badge";
import {
deadCodeRiskFactorLabel,
type DeadCodeFinding,
@@ -124,6 +125,11 @@ export function FindingIdentity({ finding, href, onNavigate, mark }: FindingIden
{finding.reason}
</span>
)}
+ {finding.preview ? (
+ <span className="mt-0.5 block">
+ <PreviewBadge note={finding.preview} />
+ </span>
+ ) : null}
<FindingSafety finding={finding} mark={mark ?? "review"} />
</div>
);
diff --git a/packages/ui/src/files/file-health-tab.tsx b/packages/ui/src/files/file-health-tab.tsx
index 652d37d07..069e84767 100644
--- a/packages/ui/src/files/file-health-tab.tsx
+++ b/packages/ui/src/files/file-health-tab.tsx
@@ -23,6 +23,7 @@ import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";
import { SeverityMark } from "../health/severity-mark";
import { VerificationTag } from "../health/verification-tag";
import { LowerPriorityTag } from "../health/lower-priority-tag";
+import { PreviewBadge } from "../health/preview-badge";
import { formatNumber } from "../lib/format";
import type { FileDetailHealth, FunctionBlameRow } from "@repowise-dev/types/files";
import type { RefactoringOpportunity } from "@repowise-dev/types/refactoring";
@@ -249,6 +250,7 @@ export function FileHealthTab({
</span>
<VerificationTag verification={f.verification} />
<LowerPriorityTag reason={f.lower_priority} />
+ <PreviewBadge note={f.preview} />
{/* Category and pillar are machine-produced labels, so they
are mono micro-labels rather than two tinted chips —
rule 9, nothing here responds to a click. */}
diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsx
index 7a3563306..776df83c1 100644
--- a/packages/ui/src/health/health-file-drawer.tsx
+++ b/packages/ui/src/health/health-file-drawer.tsx
@@ -52,6 +52,7 @@ import type { RefactoringOpportunity } from "@repowise-dev/types/refactoring";
import { SeverityMark } from "./severity-mark";
import { VerificationTag } from "./verification-tag";
import { LowerPriorityTag } from "./lower-priority-tag";
+import { PreviewBadge } from "./preview-badge";
import { ImpactFigure } from "./impact-figure";
export interface HealthDrawerFinding {
@@ -70,6 +71,9 @@ export interface HealthDrawerFinding {
/** `"unverified"` for a provisional finding type. */
verification?: string | null;
lower_priority?: string | null;
+ /** The measurement note when the row's language cell is served as a preview;
+ * null or absent for a validated cell. */
+ preview?: string | null;
}
export interface HealthDrawerMetric {
@@ -235,6 +239,7 @@ export function HealthFileDrawer({
</span>
<VerificationTag verification={f.verification} />
<LowerPriorityTag reason={f.lower_priority} />
+ <PreviewBadge note={f.preview} />
{(() => {
// A history marker wears a neutral "Watch" chip instead of its
// pillar's: it is scored, but nothing in this file will clear it.
diff --git a/packages/ui/src/health/performance/drawer.tsx b/packages/ui/src/health/performance/drawer.tsx
index 4736c8141..9479ad0a1 100644
--- a/packages/ui/src/health/performance/drawer.tsx
+++ b/packages/ui/src/health/performance/drawer.tsx
@@ -29,6 +29,7 @@ import { EFFORT_LABEL, WORK_UNIT_LABEL } from "../labels";
import { RelatedWork, useRelatedWork } from "../related-work";
import type { PerformanceViewAdapter } from "./adapter";
import { LowerPriorityTag } from "../lower-priority-tag";
+import { PreviewBadge } from "../preview-badge";
import { RawObservations } from "./evidence";
import {
ACTIONABILITY_LABEL,
@@ -337,6 +338,11 @@ function PlanSection({
<LowerPriorityTag reason={opportunity.lower_priority} />
</p>
) : null}
+ {opportunity.preview ? (
+ <p className="mt-1">
+ <PreviewBadge note={opportunity.preview} />
+ </p>
+ ) : null}
<p className="mt-1 text-sm text-[var(--color-text-tertiary)]">{presentation.detail}</p>
{opportunity.fix ? (
<p className="mt-2 text-sm text-[var(--color-text-secondary)]">
diff --git a/packages/ui/src/health/performance/queue.tsx b/packages/ui/src/health/performance/queue.tsx
index 9d2b13b9a..65d25d4bc 100644
--- a/packages/ui/src/health/performance/queue.tsx
+++ b/packages/ui/src/health/performance/queue.tsx
@@ -13,6 +13,7 @@ import { Button } from "../../ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "../../ui/popover";
import { CLICKABLE_ROW_CLS, clickableRowProps } from "../../shared/responsive-table";
import { LowerPriorityTag } from "../lower-priority-tag";
+import { PreviewBadge } from "../preview-badge";
import type { PerformanceViewAdapter } from "./adapter";
import {
ACTIONABILITY_HINT,
@@ -195,6 +196,11 @@ const OpportunityRow = memo(function OpportunityRow({
<LowerPriorityTag reason={opportunity.lower_priority} />
</p>
) : null}
+ {opportunity.preview ? (
+ <p className="mt-1">
+ <PreviewBadge note={opportunity.preview} />
+ </p>
+ ) : null}
{why.length > 0 ? (
<p
className="mt-1 text-xs text-[var(--color-text-tertiary)]"
diff --git a/packages/ui/src/health/preview-badge.tsx b/packages/ui/src/health/preview-badge.tsx
new file mode 100644
index 000000000..a09457847
--- /dev/null
+++ b/packages/ui/src/health/preview-badge.tsx
@@ -0,0 +1,65 @@
+"use client";
+
+import { createContext, useContext } from "react";
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "../ui/tooltip";
+
+export interface PreviewBadgeStrings {
+ /** The badge text. */
+ label: string;
+ /** The accessible name, which carries the note so it is read without the tooltip. */
+ ariaLabel: (note: string) => string;
+}
+
+const ENGLISH: PreviewBadgeStrings = {
+ label: "Preview",
+ ariaLabel: (note) => `Preview: ${note}`,
+};
+
+/**
+ * The badge's copy for a host that translates. Provided once at the app root,
+ * so the many views that render the badge need no strings prop of their own.
+ */
+export const PreviewBadgeStringsContext = createContext<PreviewBadgeStrings>(ENGLISH);
+
+/**
+ * The mark a row carries when its language cell is served as a preview.
+ *
+ * A preview cell's findings are shown by default but have not cleared the
+ * measured bar a validated cell has. The server sends the measurement as one
+ * line ("preview, measured 22% precision on 55 judged plans ..."); the tooltip
+ * shows it so a reader can weigh the row. Renders nothing without a note.
+ */
+export function PreviewBadge({
+ note,
+ label,
+}: {
+ note?: string | null | undefined;
+ /** Overrides the provided label; its accessible name becomes "<label>: <note>". */
+ label?: string;
+}) {
+ const strings = useContext(PreviewBadgeStringsContext);
+ const text = note?.trim();
+ if (!text) return null;
+ return (
+ <TooltipProvider delayDuration={150}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ {/* A button so the note is reachable by keyboard; the click is
+ swallowed so a clickable row underneath does not activate. */}
+ <button
+ type="button"
+ data-preview
+ aria-label={label ? `${label}: ${text}` : strings.ariaLabel(text)}
+ onClick={(e) => e.stopPropagation()}
+ className="rounded border border-[var(--color-border-default)] px-1 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-secondary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {label ?? strings.label}
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="top" className="max-w-[280px] whitespace-normal">
+ {text}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+}
diff --git a/packages/ui/src/health/refactoring-card.tsx b/packages/ui/src/health/refactoring-card.tsx
index a2eb8f42a..4816d0cfd 100644
--- a/packages/ui/src/health/refactoring-card.tsx
+++ b/packages/ui/src/health/refactoring-card.tsx
@@ -19,6 +19,7 @@ import { AskAboutThis } from "../chat/ask-about-this";
import { SeverityMark } from "./severity-mark";
import { VerificationTag } from "./verification-tag";
import { LowerPriorityTag } from "./lower-priority-tag";
+import { PreviewBadge } from "./preview-badge";
export type EffortBucket = "S" | "M" | "L" | "XL";
@@ -36,6 +37,9 @@ export interface HealthWorkItemFinding {
/** `"unverified"` for a provisional finding type. */
verification?: string | null;
lower_priority?: string | null;
+ /** The measurement note when the row's language cell is served as a preview;
+ * null or absent for a validated cell. */
+ preview?: string | null;
}
export interface HealthWorkItem {
@@ -60,6 +64,9 @@ export interface HealthWorkItem {
effort_bucket: EffortBucket;
impact_per_effort: number;
all_findings?: HealthWorkItemFinding[];
+ /** The measurement note when the row's language cell is served as a preview;
+ * null or absent for a validated cell. */
+ preview?: string | null;
}
export type FindingStatus = "open" | "acknowledged" | "resolved" | "false_positive";
@@ -205,6 +212,7 @@ export function HealthWorkItemCard({
test
</span>
) : null}
+ <PreviewBadge note={target.preview} />
<span
className={`inline-block rounded px-1.5 py-0.5 text-[10px] uppercase font-semibold ${EFFORT_TINT[target.effort_bucket]}`}
title={`Effort: ${effortLabel[target.effort_bucket]} (NLOC ${target.nloc})`}
@@ -321,6 +329,7 @@ export function HealthWorkItemCard({
</span>
<VerificationTag verification={f.verification} />
<LowerPriorityTag reason={f.lower_priority} />
+ <PreviewBadge note={f.preview} />
{f.function_name ? (
<span className="text-xs font-mono text-[var(--color-text-tertiary)]">{f.function_name}</span>
) : null}
diff --git a/packages/ui/src/refactoring/opportunity-drawer.tsx b/packages/ui/src/refactoring/opportunity-drawer.tsx
index bdb4da4dc..f09155dc3 100644
--- a/packages/ui/src/refactoring/opportunity-drawer.tsx
+++ b/packages/ui/src/refactoring/opportunity-drawer.tsx
@@ -36,6 +36,7 @@ import { CONFIDENCE_LABEL, EFFORT_LABEL, typeMeta } from "./meta";
import { CodeBlock } from "./plan-detail";
import { SourceExcerpt } from "./source-excerpt";
import { RelatedWork, type RelatedWorkSlotProps } from "../health/related-work";
+import { PreviewBadge } from "../health/preview-badge";
import { GenerateCodePanel } from "./generate-code-panel";
import {
RefactoringModelToggle,
@@ -256,6 +257,11 @@ function DrawerBody({
<div className="text-xs text-[var(--color-text-secondary)]">
{meta.label}
{detail.lead_biomarker ? ` · against ${humanizeBiomarker(detail.lead_biomarker)}` : ""}
+ {detail.preview ? (
+ <span className="ml-2">
+ <PreviewBadge note={detail.preview} />
+ </span>
+ ) : null}
</div>
<SheetTitle className="mt-0.5 break-words font-mono text-sm font-semibold text-[var(--color-text-primary)]">
{name}
@@ -568,6 +574,7 @@ function StepCard({
Moved by an earlier step
</span>
) : null}
+ <PreviewBadge note={plan?.preview} />
</div>
<button
diff --git a/packages/ui/src/refactoring/opportunity-rows.tsx b/packages/ui/src/refactoring/opportunity-rows.tsx
index b72abe17d..2fd16c9ec 100644
--- a/packages/ui/src/refactoring/opportunity-rows.tsx
+++ b/packages/ui/src/refactoring/opportunity-rows.tsx
@@ -26,6 +26,7 @@ import * as React from "react";
import { formatNumber } from "../lib/format";
import { typeMeta } from "./meta";
+import { PreviewBadge } from "../health/preview-badge";
import {
STATUS_LABEL,
TRIAGE_STATUSES,
@@ -188,6 +189,11 @@ function OpportunityRow({
>
<div className="order-2 text-xs text-[var(--color-text-secondary)] lg:order-none lg:pt-px">
{meta.label}
+ {opportunity.preview ? (
+ <span className="ml-2">
+ <PreviewBadge note={opportunity.preview} />
+ </span>
+ ) : null}
</div>
<button
diff --git a/packages/web/messages/en.json b/packages/web/messages/en.json
index 18b7caad2..83c7f768a 100644
--- a/packages/web/messages/en.json
+++ b/packages/web/messages/en.json
@@ -12,7 +12,11 @@
"dismiss": "Dismiss",
"close": "Close",
"back": "Back",
- "retry": "Try again"
+ "retry": "Try again",
+ "preview": {
+ "label": "Preview",
+ "ariaLabel": "Preview: {note}"
+ }
},
"language": {
"label": "Language",
diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.json
index f26814f85..06c497d6e 100644
--- a/packages/web/messages/zh-CN.json
+++ b/packages/web/messages/zh-CN.json
@@ -12,7 +12,11 @@
"dismiss": "忽略",
"close": "关闭",
"back": "返回",
- "retry": "重试"
+ "retry": "重试",
+ "preview": {
+ "label": "预览",
+ "ariaLabel": "预览:{note}"
+ }
},
"language": {
"label": "语言",
diff --git a/packages/web/src/app/layout.tsx b/packages/web/src/app/layout.tsx
index fbae21849..8c9d2cd3a 100644
--- a/packages/web/src/app/layout.tsx
+++ b/packages/web/src/app/layout.tsx
@@ -15,6 +15,7 @@ import { MobileNav } from "@/components/layout/mobile-nav";
import { CommandPalette } from "@/components/search/command-palette";
import { ContextDrawerShell } from "@/components/layout/context-drawer-provider";
import { SWRProvider } from "@/components/layout/swr-provider";
+import { PreviewBadgeStrings } from "@/components/layout/preview-badge-strings";
import { UpgradeBanner } from "@/components/layout/upgrade-banner";
import { listRepos } from "@/lib/api/repos";
import { getWorkspace } from "@/lib/api/workspace";
@@ -94,6 +95,7 @@ export default async function RootLayout({
<NuqsAdapter>
<SWRProvider>
<TooltipProvider delayDuration={300}>
+ <PreviewBadgeStrings>
<Suspense fallback={<AppShellSkeleton />}>
<ContextDrawerShell>
{/* Printed, the shell unclips so a long page (a chat
@@ -130,6 +132,7 @@ export default async function RootLayout({
<CommandPalette repos={repos} workspace={workspace} />
</ContextDrawerShell>
</Suspense>
+ </PreviewBadgeStrings>
</TooltipProvider>
</SWRProvider>
</NuqsAdapter>
diff --git a/packages/web/src/components/layout/preview-badge-strings.test.tsx b/packages/web/src/components/layout/preview-badge-strings.test.tsx
new file mode 100644
index 000000000..d9d98394e
--- /dev/null
+++ b/packages/web/src/components/layout/preview-badge-strings.test.tsx
@@ -0,0 +1,32 @@
+// @vitest-environment jsdom
+
+import { render, screen } from "@testing-library/react";
+import { NextIntlClientProvider } from "next-intl";
+import { describe, expect, it } from "vitest";
+import { PreviewBadge } from "@repowise-dev/ui/health/preview-badge";
+import zhMessages from "../../../messages/zh-CN.json";
+import { PreviewBadgeStrings } from "./preview-badge-strings";
+
+const NOTE = "preview, measured 22% precision on 55 judged plans, 2026-10-15";
+
+describe("PreviewBadgeStrings", () => {
+ it("gives the badge the English catalog copy", () => {
+ render(
+ <PreviewBadgeStrings>
+ <PreviewBadge note={NOTE} />
+ </PreviewBadgeStrings>,
+ );
+ expect(screen.getByRole("button", { name: `Preview: ${NOTE}` }).textContent).toBe("Preview");
+ });
+
+ it("gives the badge the zh-CN catalog copy", () => {
+ render(
+ <NextIntlClientProvider locale="zh-CN" messages={zhMessages}>
+ <PreviewBadgeStrings>
+ <PreviewBadge note={NOTE} />
+ </PreviewBadgeStrings>
+ </NextIntlClientProvider>,
+ );
+ expect(screen.getByRole("button", { name: `预览:${NOTE}` }).textContent).toBe("预览");
+ });
+});
diff --git a/packages/web/src/components/layout/preview-badge-strings.tsx b/packages/web/src/components/layout/preview-badge-strings.tsx
new file mode 100644
index 000000000..ada0fa3a0
--- /dev/null
+++ b/packages/web/src/components/layout/preview-badge-strings.tsx
@@ -0,0 +1,17 @@
+"use client";
+
+import { useMemo } from "react";
+import { useTranslations } from "next-intl";
+import { PreviewBadgeStringsContext } from "@repowise-dev/ui/health/preview-badge";
+
+/** Hands the shared Preview badge its translated copy, once for every view. */
+export function PreviewBadgeStrings({ children }: { children: React.ReactNode }) {
+ const t = useTranslations("common.preview");
+ const strings = useMemo(
+ () => ({ label: t("label"), ariaLabel: (note: string) => t("ariaLabel", { note }) }),
+ [t],
+ );
+ return (
+ <PreviewBadgeStringsContext.Provider value={strings}>{children}</PreviewBadgeStringsContext.Provider>
+ );
+}
diff --git a/tests/unit/core/test_components_resolve.py b/tests/unit/core/test_components_resolve.py
index e3f828cf0..aa59dd534 100644
--- a/tests/unit/core/test_components_resolve.py
+++ b/tests/unit/core/test_components_resolve.py
@@ -310,7 +310,12 @@ def test_dead_code_that_never_ran_is_unavailable_not_zero():
assert (ran["dead_code"]["findings"], ran["dead_code"]["basis"]) == (0, "inferred")
-def test_gated_languages_are_left_out_of_health_and_dead_code():
+def test_gated_languages_are_left_out_of_health_and_dead_code(monkeypatch):
+ # No shipped row is gated: run on the audit's gated table.
+ from repowise.core.analysis import finding_registry
+ from tests.unit.server.mcp.test_language_gates import AUDIT_GATED
+
+ monkeypatch.setattr(finding_registry, "LANGUAGE_GATES", AUDIT_GATED)
health_rows = {
"A.java": {"score": 2.0, "nloc": 100},
"b.py": {"score": 8.0, "nloc": 100},
@@ -327,7 +332,12 @@ def test_gated_languages_are_left_out_of_health_and_dead_code():
assert dead["method"].endswith("; 1 file(s) in gated languages excluded")
-def test_only_gated_files_make_health_and_dead_code_unavailable():
+def test_only_gated_files_make_health_and_dead_code_unavailable(monkeypatch):
+ # No shipped row is gated: run on the audit's gated table.
+ from repowise.core.analysis import finding_registry
+ from tests.unit.server.mcp.test_language_gates import AUDIT_GATED
+
+ monkeypatch.setattr(finding_registry, "LANGUAGE_GATES", AUDIT_GATED)
facts = rollup_component(
["A.java", "B.cs"], test_files=set(), git_rows={},
health_rows={"A.java": {"score": 2.0, "nloc": 10}, "B.cs": {"score": 3.0, "nloc": 10}},
diff --git a/tests/unit/core/test_report.py b/tests/unit/core/test_report.py
index 604336f58..3ccc50f7e 100644
--- a/tests/unit/core/test_report.py
+++ b/tests/unit/core/test_report.py
@@ -155,7 +155,12 @@ def test_check_keeps_scorecard_keys_and_forces_inconclusive_without_evidence():
# ---------------------------------------------------------------------------
-async def test_components_section_scores_health_and_marks_gated_languages(ctx):
+async def test_components_section_scores_health_and_marks_gated_languages(ctx, monkeypatch):
+ # No shipped row is gated: run on the audit's gated table.
+ from repowise.core.analysis import finding_registry
+ from tests.unit.server.mcp.test_language_gates import AUDIT_GATED
+
+ monkeypatch.setattr(finding_registry, "LANGUAGE_GATES", AUDIT_GATED)
items = await _section("components", ctx)
assert items["component-map"]["data"]["derived"] == 2
summary = items["components"]
@@ -224,7 +229,12 @@ async def test_bus_factor_item_for_a_component_the_catalog_marks(ctx):
assert items["bus-factor"]["details"] == ["bus factor 1: web"]
-async def test_dead_code_tiers_and_gated_findings(ctx):
+async def test_dead_code_tiers_and_gated_findings(ctx, monkeypatch):
+ # No shipped row is gated: run on the audit's gated table.
+ from repowise.core.analysis import finding_registry
+ from tests.unit.server.mcp.test_language_gates import AUDIT_GATED
+
+ monkeypatch.setattr(finding_registry, "LANGUAGE_GATES", AUDIT_GATED)
items = await _section("dead-code", ctx)
assert items["dead-code:high"]["data"]["count"] == 1
assert items["dead-code:medium"]["data"]["count"] == 0
diff --git a/tests/unit/health/test_language_gates_core.py b/tests/unit/health/test_language_gates_core.py
index c1b998cbc..29580cb91 100644
--- a/tests/unit/health/test_language_gates_core.py
+++ b/tests/unit/health/test_language_gates_core.py
@@ -1,13 +1,26 @@
-"""Core surfaces built from rows in memory honour the layer x language gates."""
+"""Core surfaces built from rows in memory honour the layer x language gates.
+
+They run on the audit's gated table (no shipped row is gated), so the gated
+state stays covered."""
from __future__ import annotations
from types import SimpleNamespace
+import pytest
+
from repowise.core.analysis.actions.build import build_dead
from repowise.core.analysis.change_health.service import _limits
from repowise.core.analysis.health.models import HealthFindingData, Severity
from repowise.core.generation.page_generator.helpers import build_dead_code_map
+from tests.unit.server.mcp.test_language_gates import AUDIT_GATED
+
+
[email protected](autouse=True)
+def _audit_gated(monkeypatch):
+ from repowise.core.analysis import finding_registry
+
+ monkeypatch.setattr(finding_registry, "LANGUAGE_GATES", AUDIT_GATED)
def _dead(path: str) -> dict:
diff --git a/tests/unit/health/test_perf_repository_loops.py b/tests/unit/health/test_perf_repository_loops.py
index 28410d1d1..1ee05ecd9 100644
--- a/tests/unit/health/test_perf_repository_loops.py
+++ b/tests/unit/health/test_perf_repository_loops.py
@@ -257,11 +257,22 @@ def test_collection_of_mappers_is_not_a_mapper(tmp_path: Path):
assert hits == []
-def test_java_rows_are_held_back_and_counted_not_dropped(tmp_path: Path):
- from repowise.core.analysis.finding_registry import split_gated
+def test_java_rows_are_held_back_and_counted_not_dropped(tmp_path: Path, monkeypatch):
+ from repowise.core.analysis import finding_registry
+ from repowise.core.analysis.finding_registry import LanguageGate, split_gated
from repowise.core.analysis.health.biomarkers.base import FileContext
from repowise.core.analysis.health.biomarkers.io_in_loop import BIOMARKER
+ # A gated Java cell on both layers, whatever state today's table holds.
+ monkeypatch.setattr(
+ finding_registry,
+ "LANGUAGE_GATES",
+ tuple(
+ LanguageGate(layer, "java", 0.1, "test", "2026-10-15", "test")
+ for layer in ("health", "performance")
+ ),
+ )
+
hits = _hits(tmp_path, _mybatis(_LOOP_SERVICE), _SERVICE)
ctx = FileContext(file_path=_SERVICE, language="java", nloc=8, has_test_file=False,
module=None, perf_hits=hits)
diff --git a/tests/unit/health/test_signature_facts.py b/tests/unit/health/test_signature_facts.py
index 3cdcecfc5..3529d1191 100644
--- a/tests/unit/health/test_signature_facts.py
+++ b/tests/unit/health/test_signature_facts.py
@@ -108,6 +108,39 @@ def test_typescript_override_modifier_and_name():
assert not fns["override"].signature_fixed
+def test_java_framework_bound_parameters():
+ fns = _fns(
+ "C.java",
+ "java",
+ """class C {
+ void route(@PathVariable String a, @PathVariable String b, @PathVariable("c") String c,
+ @org.springframework.web.bind.annotation.PathVariable String d, String e) {}
+ void query(@RequestParam(value = "x", required = false) String x, @RequestBody Form f) {}
+ C(@MaxMindDbParameter(name = "ip") String ip, @JsonProperty("asn") long asn) {}
+ }""",
+ )
+ route = fns["route"]
+ assert (route.param_count, route.bound_param_count) == (5, 4)
+ # Bound parameters leave the typed and scalar counts.
+ assert (route.typed_param_count, route.primitive_param_count) == (1, 1)
+ # An argument does not hide the binder; an object binder is not one.
+ assert fns["query"].bound_param_count == 1
+ assert fns["query"].typed_param_count == 1
+ assert fns["C"].bound_param_count == 2
+
+
+def test_kotlin_bound_parameter_annotations_sit_beside_the_parameter():
+ from tree_sitter_language_pack import get_parser
+
+ from repowise.core.analysis.health.complexity.languages import get_language_map
+ from repowise.core.analysis.health.complexity.signature import bound_param_count
+
+ src = b'fun f(@PathVariable a: String, @RequestParam("x") b: String, c: String) {}'
+ root = get_parser("kotlin").parse(src).root_node
+ params = next(c for c in root.children[0].children if c.type == "function_value_parameters")
+ assert bound_param_count(params, get_language_map("kotlin")) == 2
+
+
def test_kotlin_override_modifier():
source = "class A : B() {\n override fun run(a: Int) {}\n fun own(a: Int) {}\n}\n"
fns = _fns("A.kt", "kotlin", source)
diff --git a/tests/unit/health/test_structural_biomarkers.py b/tests/unit/health/test_structural_biomarkers.py
index 67c805b71..a05908a12 100644
--- a/tests/unit/health/test_structural_biomarkers.py
+++ b/tests/unit/health/test_structural_biomarkers.py
@@ -8,7 +8,7 @@ from repowise.core.analysis.health.biomarkers.large_method import LargeMethodDet
from repowise.core.analysis.health.biomarkers.primitive_obsession import (
PrimitiveObsessionDetector,
)
-from repowise.core.analysis.health.complexity import FunctionComplexity
+from repowise.core.analysis.health.complexity import FunctionComplexity, walk_file
def _ctx(fns: list[FunctionComplexity]) -> FileContext:
@@ -123,6 +123,41 @@ def test_primitive_obsession_skips_fixed_signatures():
assert PrimitiveObsessionDetector().detect(_ctx([fn, _FILLER])) == []
+_ROLE_CONTROLLER = """@RestController
+class RoleController {
+ @DeleteMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/ns_roles/{roleType}")
+ public ResponseEntity<Void> removeClusterRoleFromUser(@PathVariable String appId,
+ @PathVariable String env, @PathVariable String clusterName, @PathVariable String roleType,
+ @RequestParam String user) {
+ roleService.remove(appId, env, clusterName, roleType, user);
+ return ResponseEntity.ok().build();
+ }
+
+ void removeInternal(String appId, String env, String clusterName, String roleType, String user) {
+ roleService.remove(appId, env, clusterName, roleType, user);
+ }
+
+ @GetMapping("/wide")
+ public void wide(@PathVariable String a, @PathVariable String b, @PathVariable String c,
+ @PathVariable String d, @PathVariable String e, @PathVariable String f,
+ String g, String h, String i, String j, String k, String l) {}
+}
+"""
+
+
+def test_primitive_obsession_counts_only_parameters_the_caller_chooses():
+ fns = walk_file("RoleController.java", "java", _ROLE_CONTROLLER.encode()).functions
+ out = {r.function_name: r for r in PrimitiveObsessionDetector().detect(_ctx([*fns, _FILLER]))}
+ # Four route segments and a query parameter: nothing left to group.
+ assert "removeClusterRoleFromUser" not in out
+ # The same five strings chosen by a caller still fire.
+ assert "removeInternal" in out
+ # Six bound and six free scalars: the free six still fire, and say so.
+ wide = out["wide"]
+ assert wide.details["bound_param_count"] == 6
+ assert "takes 12 parameters, 6 bound by the framework, 6 of 6 typed" in wide.reason
+
+
def test_primitive_obsession_needs_mostly_primitive_params_when_typed():
def fn(typed: int, primitive: int) -> FunctionComplexity:
return FunctionComplexity(
diff --git a/tests/unit/persistence/test_actions_build.py b/tests/unit/persistence/test_actions_build.py
index 01006f783..3204cd0d6 100644
--- a/tests/unit/persistence/test_actions_build.py
+++ b/tests/unit/persistence/test_actions_build.py
@@ -216,7 +216,12 @@ def test_a_store_that_fails_to_build_costs_only_itself() -> None:
assert facts.secrets
-def test_only_a_recent_authored_code_shape_regression_is_a_candidate() -> None:
+def test_only_a_recent_authored_code_shape_regression_is_a_candidate(monkeypatch) -> None:
+ # No shipped row is gated: run on the audit's gated table.
+ from repowise.core.analysis import finding_registry
+ from tests.unit.server.mcp.test_language_gates import AUDIT_GATED
+
+ monkeypatch.setattr(finding_registry, "LANGUAGE_GATES", AUDIT_GATED)
"""Each condition alone keeps a commit-health row out of the recent findings."""
from types import SimpleNamespace
diff --git a/tests/unit/server/mcp/test_file_holds.py b/tests/unit/server/mcp/test_file_holds.py
index 41dcda7c2..c95ef6b56 100644
--- a/tests/unit/server/mcp/test_file_holds.py
+++ b/tests/unit/server/mcp/test_file_holds.py
@@ -28,10 +28,11 @@ def test_file_hold_reads_origin_and_test_flag():
assert file_hold("health", "change_entropy", "test", True) == "test_history"
# A code-shape finding on a test file is still served.
assert file_hold("health", "complex_method", "test", True) is None
- # A history marker on production code is still served.
- assert file_hold("health", "ownership_risk", "production", False) is None
- # Unknown flag (row written before the column) is not held.
- assert file_hold("health", "ownership_risk", None, None) is None
+ # A history marker on production code is context, held under its own key.
+ assert file_hold("health", "ownership_risk", "production", False) == "history"
+ # Unknown flag (row written before the column) is not a test file.
+ assert file_hold("health", "ownership_risk", None, None) == "history"
+ assert file_hold("health", "complex_method", "production", False) is None
# Other layers are untouched.
assert file_hold("dead_code", "unreachable_file", "vendored", False) is None
@@ -53,11 +54,11 @@ def test_split_gated_applies_file_holds_with_their_reason():
)
assert [(r["file_path"], r["biomarker_type"]) for r in shown] == [
(_TEST, "complex_method"),
- ("src/app.py", "ownership_risk"),
]
assert gated == {
"vendored": {"count": 1, "reason": FILE_HOLDS["vendored"]},
"test_history": {"count": 1, "reason": FILE_HOLDS["test_history"]},
+ "history": {"count": 1, "reason": FILE_HOLDS["history"]},
}
# Without the metric rows nothing is held by file (unknown is not a hold).
assert len(split_gated("health", rows, kind="biomarker_type", get=lambda r, k: r[k])[0]) == 4
diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.py
index 4e389e08d..b9e9d31f3 100644
--- a/tests/unit/server/mcp/test_health.py
+++ b/tests/unit/server/mcp/test_health.py
@@ -66,7 +66,8 @@ async def test_finding_ids_distinguish_same_coordinate_evidence(
session.add_all(rows)
await session.commit()
- emitted = await get_health(only=["top_findings"], limit=10)
+ # A history marker is held from the default list; the opt-in lists it.
+ emitted = await get_health(only=["top_findings"], include=["unverified"], limit=10)
findings = [
row
for row in emitted["top_findings"]
@@ -1203,7 +1204,8 @@ async def health_data_with_tests(session, health_data: str) -> str:
``is_test=True``; this gives it health rows. Its findings carry the two
highest impacts in the fixture, so an unsplit list leads with the test
suite — which is the shape measured on the real index, where 2 of the top
- 5 open findings repo-wide sat on test files.
+ 5 open findings repo-wide sat on test files. Both are code-shape markers:
+ a history marker is held from finding lists on any file.
Rows are added through the ORM rather than ``save_health_metrics`` /
``save_health_findings``: both are delete-then-insert over the whole repo,
@@ -1229,7 +1231,7 @@ async def health_data_with_tests(session, health_data: str) -> str:
)
)
for biomarker, fn, impact, reason in (
- ("change_entropy", None, 3.02, "tests/test_service.py changes with unrelated files"),
+ ("god_class", None, 3.02, "tests/test_service.py holds one class doing everything"),
("complex_method", "test_everything", 2.5, "test_everything has complexity 12"),
):
session.add(
diff --git a/tests/unit/server/mcp/test_history_hold.py b/tests/unit/server/mcp/test_history_hold.py
new file mode 100644
index 000000000..67f2e8766
--- /dev/null
+++ b/tests/unit/server/mcp/test_history_hold.py
@@ -0,0 +1,194 @@
+"""History markers on production files are context, not defect-list findings.
+
+A git-derived marker (``ownership_risk``, ``change_entropy`` ...) orders
+hotspots and Fix first; finding lists and their counts hold it back under the
+``history`` file hold, with its reason, and ``include=["unverified"]`` still
+lists it. Scores, KPIs and the worst-file order still count it.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+from sqlalchemy import select
+
+from repowise.core.analysis.finding_registry import FILE_HOLDS, split_gated
+
+_APP = "src/app_service.py"
+
+
+async def _seed(session, rid: str) -> None:
+ from repowise.core.persistence.crud import upsert_health_findings, upsert_health_metrics
+
+ await upsert_health_metrics(
+ session,
+ rid,
+ [
+ {
+ "file_path": _APP,
+ "score": 4.0,
+ "max_ccn": 25,
+ "max_nesting": 5,
+ "nloc": 300,
+ "has_test_file": False,
+ "module": "x",
+ "code_origin": "production",
+ "is_test": False,
+ }
+ ],
+ )
+ await upsert_health_findings(
+ session,
+ rid,
+ [
+ {
+ "file_path": _APP,
+ "biomarker_type": kind,
+ "severity": "high",
+ "function_name": "run",
+ "line_start": 1,
+ "line_end": 90,
+ "details": {},
+ "health_impact": impact,
+ "reason": f"{kind} on {_APP}",
+ }
+ for kind, impact in (("ownership_risk", 1.5), ("change_entropy", 1.0),
+ ("complex_method", 2.0))
+ ],
+ file_paths=[_APP],
+ )
+ await session.commit()
+
+
+async def test_sql_and_in_memory_holds_agree(session, health_data):
+ from repowise.core.persistence.crud import (
+ gated_health_counts,
+ get_health_findings,
+ get_health_metrics,
+ )
+
+ await _seed(session, health_data)
+ every = await get_health_findings(session, health_data, include_unverified=True)
+ metrics = {m.file_path: m for m in await get_health_metrics(session, health_data)}
+
+ sql_kept = {f.id for f in await get_health_findings(session, health_data)}
+ sql_held = await gated_health_counts(session, health_data)
+ mem_kept, mem_held = split_gated("health", every, kind="biomarker_type", files=metrics)
+
+ assert {f.id for f in mem_kept} == sql_kept
+ assert sql_held == mem_held
+ assert sql_held["history"] == {"count": 2, "reason": FILE_HOLDS["history"]}
+ kinds = {(f.file_path, f.biomarker_type) for f in every if f.id in sql_kept}
+ assert (_APP, "complex_method") in kinds
+ assert not {(_APP, "ownership_risk"), (_APP, "change_entropy")} & kinds
+ # The opt-in lists them.
+ assert {(_APP, "ownership_risk"), (_APP, "change_entropy")} <= {
+ (f.file_path, f.biomarker_type) for f in every
+ }
+
+
+def test_test_files_keep_their_own_key():
+ rows = [
+ {"file_path": "tests/test_a.py", "biomarker_type": "ownership_risk"},
+ {"file_path": "src/a.py", "biomarker_type": "ownership_risk"},
+ ]
+ files = {
+ "tests/test_a.py": SimpleNamespace(code_origin="test", is_test=True),
+ "src/a.py": SimpleNamespace(code_origin="production", is_test=False),
+ }
+ shown, gated = split_gated(
+ "health", rows, kind="biomarker_type", get=lambda r, k: r[k], files=files
+ )
+ assert shown == []
+ assert {k: v["count"] for k, v in gated.items()} == {"test_history": 1, "history": 1}
+
+
+async def test_a_history_view_keeps_them(session, health_data):
+ from repowise.core.persistence.crud.analysis.shown import ungated
+ from repowise.core.persistence.models import HealthFinding
+
+ await _seed(session, health_data)
+
+ async def kinds(**kw) -> set[str]:
+ rows = await session.execute(
+ select(HealthFinding.biomarker_type).where(
+ HealthFinding.repository_id == health_data,
+ HealthFinding.file_path == _APP,
+ ungated("health", HealthFinding.file_path, HealthFinding.biomarker_type, **kw),
+ )
+ )
+ return set(rows.scalars())
+
+ assert await kinds() == {"complex_method"}
+ assert await kinds(hold_history=False) == {"complex_method", "ownership_risk", "change_entropy"}
+
+
+async def test_get_health_lists_count_and_scores_hold(setup_mcp, session, health_data, monkeypatch):
+ from repowise.core.analysis import finding_registry
+ from repowise.core.persistence.crud.analysis import shown as shown_module
+ from repowise.server.mcp_server import get_health
+
+ await _seed(session, health_data)
+ default = await get_health(only=["top_findings", "kpis", "worst_files"], limit=50)
+ listed = {(f["file_path"], f["biomarker_type"]) for f in default["top_findings"]}
+ assert (_APP, "complex_method") in listed
+ assert not {(_APP, "ownership_risk"), (_APP, "change_entropy")} & listed
+ assert default["_meta"]["gated"]["health"] == {"history": 2}
+
+ opted = await get_health(only=["top_findings"], include=["unverified"], limit=50)
+ assert (_APP, "ownership_risk") in {
+ (f["file_path"], f["biomarker_type"]) for f in opted["top_findings"]
+ }
+
+ # Scores, KPIs and the worst-file order still count the held markers.
+ monkeypatch.setattr(shown_module, "_file_holds", lambda *a, **k: [])
+ monkeypatch.setattr(finding_registry, "row_hold", lambda *a, **k: None)
+ plain = await get_health(only=["top_findings", "kpis", "worst_files"], limit=50)
+ assert default["kpis"] == plain["kpis"]
+ assert default["worst_files"] == plain["worst_files"]
+
+
+async def test_get_health_history_count_costs_one_int(setup_mcp, session, health_data):
+ import json
+
+ from repowise.server.mcp_server import get_health
+
+ await _seed(session, health_data)
+ result = await get_health()
+ gated = result["_meta"]["gated"]
+ # One integer under one key; no reason sentence while findings are listed.
+ assert gated["health"] == {"history": 2}
+ assert "reasons" not in gated
+ assert len(json.dumps(gated["health"])) < 20
+
+ # Nothing listed on the target but history markers: the reason comes once.
+ from repowise.core.persistence.crud import upsert_health_findings
+
+ await upsert_health_findings(
+ session,
+ health_data,
+ [
+ {
+ "file_path": _APP,
+ "biomarker_type": "ownership_risk",
+ "severity": "high",
+ "function_name": "run",
+ "line_start": 1,
+ "line_end": 90,
+ "details": {},
+ "health_impact": 1.5,
+ "reason": "ownership_risk only",
+ }
+ ],
+ file_paths=[_APP],
+ )
+ await session.commit()
+ targeted = await get_health(targets=[_APP])
+ assert not targeted.get("findings")
+ assert targeted["_meta"]["gated"]["health"] == {"history": 1}
+ assert targeted["_meta"]["gated"]["reasons"] == {"history": FILE_HOLDS["history"]}
diff --git a/tests/unit/server/mcp/test_language_gates.py b/tests/unit/server/mcp/test_language_gates.py
index 29b22f031..debc996b2 100644
--- a/tests/unit/server/mcp/test_language_gates.py
+++ b/tests/unit/server/mcp/test_language_gates.py
@@ -4,7 +4,9 @@ opts in, and every surface says how many rows it held back.
The seeded repository is Python; these tests add Java, C#, C++, Kotlin and
Swift rows beside it, so each case checks both halves: the gated rows leave,
-the Python rows stay.
+the Python rows stay. No row is gated in the shipped table, so every test here
+runs on :data:`AUDIT_GATED`, the 2026-10-02 audit's gated cells, to keep the
+gated state working; ``test_preview_gates`` pins the shipped states.
"""
from __future__ import annotations
@@ -24,15 +26,54 @@ from repowise.core.analysis.finding_registry import (
)
from repowise.core.persistence.models import DeadCodeFinding
+_LAYERS = ("health", "refactoring", "performance", "dead_code")
+
+#: Every audited cell gated: each layer on Java, C#, C and C++, and dead code on
+#: Kotlin and Swift.
+AUDIT_GATED: tuple[LanguageGate, ...] = (
+ *(
+ LanguageGate(layer, language, 0.1, "test sample", "2026-10-02", "test")
+ for layer in _LAYERS
+ for language in ("java", "csharp", "c", "cpp")
+ ),
+ *(
+ LanguageGate("dead_code", language, 0.1, "test sample", "2026-10-02", "test")
+ for language in ("kotlin", "swift")
+ ),
+)
+
+
[email protected](autouse=True)
+def _audit_gated(monkeypatch):
+ monkeypatch.setattr(finding_registry, "LANGUAGE_GATES", AUDIT_GATED)
+
+
+def _java_on_every_layer(monkeypatch, state: str = "gated") -> None:
+ monkeypatch.setattr(
+ finding_registry,
+ "LANGUAGE_GATES",
+ tuple(
+ LanguageGate(layer, "java", 0.1, "test", "2026-10-15", "test", state=state)
+ for layer in _LAYERS
+ ),
+ )
+
+
+def test_a_gated_row_holds_its_layer_back_on_every_extension(monkeypatch):
+ _java_on_every_layer(monkeypatch)
+ for layer in _LAYERS:
+ assert gate_for(layer, "src/Foo.java") is not None, layer
+ assert gate_for(layer, "src/foo.py") is None, layer
+
def test_audited_languages_are_gated_on_every_layer():
- for layer in ("health", "refactoring", "performance", "dead_code"):
+ for layer in _LAYERS:
for path in ("src/Foo.java", "src/Foo.cs", "src/foo.c", "src/foo.cpp", "inc/foo.h"):
assert gate_for(layer, path) is not None, (layer, path)
def test_unaudited_languages_are_never_gated():
- for layer in ("health", "refactoring", "performance", "dead_code"):
+ for layer in _LAYERS:
for path in ("a.py", "a.ts", "a.tsx", "a.js", "a.go", "a.rs", "pom.xml", ""):
assert gate_for(layer, path) is None, (layer, path)
diff --git a/tests/unit/server/mcp/test_preview_gates.py b/tests/unit/server/mcp/test_preview_gates.py
new file mode 100644
index 000000000..9ec51bc96
--- /dev/null
+++ b/tests/unit/server/mcp/test_preview_gates.py
@@ -0,0 +1,310 @@
+"""The ``preview`` gate state: a (layer, language) row that is served by
+default, counted as served, and labelled with its measurement.
+
+Tests patch ``LANGUAGE_GATES`` rather than read today's table, so they pin the
+mechanism: one row moves gated -> preview -> ungated by a table edit and every
+surface follows.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from repowise.core.analysis import finding_registry
+from repowise.core.analysis.finding_registry import (
+ LanguageGate,
+ gate_for,
+ gated_summary,
+ label_previews,
+ preview_for,
+ preview_lines,
+ preview_note,
+ served_previews,
+ split_gated,
+)
+from tests.unit.server.mcp.test_language_gates import _seed_gated_dead_code, _seed_java_health
+
+_NOTE = "preview, measured 22% precision on 55 judged plans from 2 Java repos, 2026-10-15"
+
+
+def _row(layer: str, state: str, precision: float | None = 0.22) -> LanguageGate:
+ return LanguageGate(
+ layer, "java", precision, "55 judged plans from 2 Java repos", "2026-10-15", "test",
+ state=state,
+ )
+
+
+def _table(monkeypatch, *rows: LanguageGate) -> None:
+ monkeypatch.setattr(finding_registry, "LANGUAGE_GATES", rows)
+
+
+def _get(row: dict, key: str):
+ return row.get(key)
+
+
+def test_shipped_table_states():
+ # The one live-table pin: what ships today. Everything else patches a table.
+ states = {(g.layer, g.language): g.state for g in finding_registry.LANGUAGE_GATES}
+ audited = ("java", "csharp", "c", "cpp")
+ expected = {
+ ("health", "cpp"): "preview",
+ **{(layer, lang): "preview" for layer in ("refactoring", "performance") for lang in audited},
+ **{("dead_code", lang): "preview" for lang in (*audited, "kotlin", "swift")},
+ }
+ assert states == expected
+ assert all(finding_registry.gates_on(layer) == () for layer in ("health", "refactoring",
+ "performance", "dead_code"))
+ health_cpp = finding_registry.preview_for("health", "src/a.cpp")
+ assert health_cpp is not None and health_cpp.measure == "not wrong"
+ for path in ("src/A.java", "src/A.cs", "src/a.c"):
+ assert finding_registry.preview_for("health", path) is None
+
+
+def test_preview_note_quotes_the_measurement():
+ assert preview_note(_row("refactoring", "preview")) == _NOTE
+ unmeasured = LanguageGate(
+ "performance", "c", None, "no served opportunities on 2 C repos", "2026-10-15", "x",
+ state="preview",
+ )
+ assert preview_note(unmeasured) == (
+ "preview, not measured: no served opportunities on 2 C repos, 2026-10-15"
+ )
+ not_wrong = LanguageGate(
+ "health", "java", 0.95, "40 judged findings from 2 Java repos", "2026-10-20", "x",
+ state="preview", measure="not wrong",
+ )
+ assert preview_note(not_wrong).startswith("preview, measured 95% not wrong on 40 judged")
+ assert "—" not in _NOTE
+
+
+def test_one_row_moves_gated_to_preview_to_ungated(monkeypatch):
+ rows = [{"file_path": "src/A.java", "kind": "x"}, {"file_path": "a.py", "kind": "x"}]
+
+ _table(monkeypatch, _row("refactoring", "gated"))
+ shown, gated = split_gated("refactoring", rows, kind="kind", get=_get)
+ assert [r["file_path"] for r in shown] == ["a.py"]
+ assert gated["java"]["count"] == 1
+ assert preview_for("refactoring", "src/A.java") is None
+
+ _table(monkeypatch, _row("refactoring", "preview"))
+ shown, gated = split_gated("refactoring", rows, kind="kind", get=_get)
+ # Served and not counted as held back: the list and the count agree.
+ assert shown == rows and gated == {}
+ assert gate_for("refactoring", "src/A.java") is None
+ assert gated_summary("refactoring", {"java": 3}) == {}
+ assert served_previews("refactoring", rows, kind="kind", get=_get) == {"java": _NOTE}
+ labelled = label_previews("refactoring", rows, kind="kind")
+ assert labelled[0]["preview"] == _NOTE and "preview" not in labelled[1]
+ assert "preview" not in rows[0]
+
+ _table(monkeypatch)
+ assert split_gated("refactoring", rows, kind="kind", get=_get) == (rows, {})
+ assert served_previews("refactoring", rows, kind="kind", get=_get) == {}
+
+
+def test_a_preview_row_is_scoped_to_its_layer(monkeypatch):
+ _table(monkeypatch, _row("refactoring", "preview"), _row("dead_code", "gated"))
+ assert preview_for("refactoring", "A.java") is not None
+ assert preview_for("dead_code", "A.java") is None
+ assert gate_for("dead_code", "A.java") is not None
+
+
+def test_preview_lines_name_layer_and_language(monkeypatch):
+ _table(monkeypatch, _row("refactoring", "preview"))
+ rows = [{"file_path": "A.java", "refactoring_type": "extract_method"}] * 2
+ assert preview_lines("refactoring", rows, kind="refactoring_type", get=_get) == [
+ f"Refactoring on Java: {_NOTE}"
+ ]
+ assert preview_lines("refactoring", [{"file_path": "a.py"}], kind="k", get=_get) == []
+
+
+def test_cli_prints_one_dim_line_for_listed_preview_rows(monkeypatch):
+ from repowise.cli.commands.health_cmd import refactoring_targets
+ from repowise.cli.helpers import console
+
+ _table(monkeypatch, _row("refactoring", "preview"))
+ opportunities = [{"file_path": "A.java", "lead_refactoring_type": "extract_method"}]
+ plans = [{"file_path": "B.java", "refactoring_type": "extract_method"}]
+ with console.capture() as out:
+ refactoring_targets._render_preview_lines(opportunities, plans)
+ assert out.get().strip() == f"Refactoring on Java: {_NOTE}"
+ with console.capture() as out:
+ refactoring_targets._render_preview_lines([{"file_path": "a.py"}], [])
+ assert out.get() == ""
+
+
+# ---------------------------------------------------------------------------
+# SQL readers: counts and lists agree for a preview row
+# ---------------------------------------------------------------------------
+
+
+async def test_sql_readers_serve_and_count_a_preview_row(monkeypatch, session, health_data):
+ from repowise.core.persistence.crud import (
+ gated_health_counts,
+ get_dead_code_findings,
+ get_dead_code_summary,
+ get_health_findings,
+ )
+
+ await _seed_java_health(session, health_data)
+ await _seed_gated_dead_code(session, health_data, ("src/Billing.java",))
+
+ _table(monkeypatch, _row("health", "gated"), _row("dead_code", "gated"))
+ held = await get_dead_code_summary(session, health_data)
+ assert held["gated"]["java"]["count"] == 1
+
+ _table(monkeypatch, _row("health", "preview"), _row("dead_code", "preview"))
+ paths = {f.file_path for f in await get_health_findings(session, health_data)}
+ assert "src/Billing.java" in paths
+ assert "java" not in await gated_health_counts(session, health_data)
+ dead = {f.file_path for f in await get_dead_code_findings(session, health_data)}
+ assert "src/Billing.java" in dead
+ summary = await get_dead_code_summary(session, health_data)
+ assert summary["gated"] == {}
+ assert summary["total_findings"] == held["total_findings"] + 1
+
+
+# ---------------------------------------------------------------------------
+# MCP: ``_meta.preview`` names only the cells the response lists
+# ---------------------------------------------------------------------------
+
+
+def _size(result: dict) -> int:
+ meta = {k: v for k, v in result["_meta"].items() if k != "timing_ms"}
+ return len(json.dumps({**result, "_meta": meta}, sort_keys=True, default=str))
+
+
+async def test_get_health_labels_served_preview_cells_in_meta(
+ monkeypatch, setup_mcp, session, health_data
+):
+ from repowise.server.mcp_server import get_health
+
+ await _seed_java_health(session, health_data)
+ _table(monkeypatch, _row("health", "preview"), _row("refactoring", "preview"))
+
+ result = await get_health(only=["top_findings"], limit=50)
+ assert "src/Billing.java" in {f["file_path"] for f in result["top_findings"]}
+ # Only the pair the response lists: no refactoring rows were sent.
+ assert result["_meta"]["preview"] == {"health": {"java": preview_note(_row("health", "x"))}}
+ assert "gated" not in result["_meta"]
+ # Nothing per row.
+ assert all("preview" not in f for f in result["top_findings"])
+
+ # A response that lists no row of the cell carries no label.
+ kpis = await get_health(only=["kpis"])
+ assert "preview" not in kpis["_meta"]
+
+
+async def test_default_get_health_without_preview_rows_does_not_grow(
+ monkeypatch, setup_mcp, session, health_data
+):
+ from repowise.server.mcp_server import get_health
+
+ # The seeded repository is Python: the shipped table adds nothing.
+ shipped = await get_health()
+ assert "preview" not in shipped["_meta"]
+ _table(monkeypatch)
+ assert _size(await get_health()) == _size(shipped)
+
+
+async def test_get_dead_code_labels_served_preview_cells_in_meta(
+ monkeypatch, setup_mcp, session, health_data
+):
+ from repowise.server.mcp_server import get_dead_code
+
+ await _seed_gated_dead_code(session, health_data, ("src/Billing.java",))
+ _table(monkeypatch, _row("dead_code", "preview"))
+
+ result = await get_dead_code(min_confidence=0.0)
+ paths = {f["file_path"] for t in result["tiers"].values() for f in t["findings"]}
+ assert "src/Billing.java" in paths
+ assert result["_meta"]["preview"] == {"dead_code": {"java": preview_note(_row("x", "x"))}}
+ assert "gated" not in result["summary"]
+
+ _table(monkeypatch)
+ assert "preview" not in (await get_dead_code(min_confidence=0.0))["_meta"]
+
+
+async def test_get_health_labels_refactoring_preview_cells(
+ monkeypatch, setup_mcp, session, health_data
+):
+ from repowise.core.persistence import crud
+ from repowise.server.mcp_server import get_health
+ from tests.unit.server.test_language_gates_rest import _plan
+
+ await _seed_java_health(session, health_data)
+ await crud.save_refactoring_suggestions(
+ session, health_data, [_plan("src/Billing.java", "charge")]
+ )
+ await crud.finalize_refactoring_opportunities(session, health_data, analyzed_commit="c" * 40)
+ await session.commit()
+ _table(monkeypatch, _row("refactoring", "preview"))
+
+ result = await get_health(
+ include=["refactoring"], only=["refactoring_plans", "refactoring_opportunities"]
+ )
+ listed = {
+ r["file_path"]
+ for key in ("refactoring_plans", "refactoring_opportunities")
+ for r in result.get(key) or []
+ }
+ assert "src/Billing.java" in listed
+ assert result["_meta"]["preview"] == {"refactoring": {"java": _NOTE}}
+
+
+async def test_get_health_labels_file_rows_and_fix_first_in_one_map(
+ monkeypatch, setup_mcp, session, health_data
+):
+ from repowise.server.mcp_server import get_health
+
+ await _seed_java_health(session, health_data)
+ _table(monkeypatch, _row("health", "preview"))
+ note = preview_note(_row("health", "x"))
+
+ # File rows alone label the cell.
+ rows = await get_health(only=["worst_files"], limit=50)
+ assert "src/Billing.java" in {r["file_path"] for r in rows["worst_files"]}
+ assert rows["_meta"]["preview"] == {"health": {"java": note}}
+
+ # Fix first items are labelled by the layer their kind was built from.
+ queue = await get_health(only=["fix_first"])
+ items = [*(queue.get("fix_first") or {}).get("items", [])]
+ on_java = [i for i in items if i["target"]["file_path"] == "src/Billing.java"]
+ if on_java:
+ assert queue["_meta"]["preview"]["health"] == {"java": note}
+
+ # The whole dashboard: one map, nothing per row.
+ dashboard = await get_health()
+ assert dashboard["_meta"]["preview"] == {"health": {"java": note}}
+ assert len(json.dumps(dashboard["_meta"]["preview"])) < 160
+ for value in dashboard.values():
+ if isinstance(value, list):
+ assert all("preview" not in r for r in value if isinstance(r, dict))
+
+
+def test_fix_first_items_label_the_layer_their_kind_came_from(monkeypatch):
+ from repowise.server.mcp_server.tool_health.tool import _attach_preview
+
+ _table(monkeypatch, _row("refactoring", "preview"), _row("health", "preview"))
+ result = {
+ "fix_first": {
+ "lead": {"kind": "refactor", "target": {"file_path": "src/A.java"}},
+ "items": [
+ {"kind": "refactor", "target": {"file_path": "src/A.java"}},
+ {"kind": "perf_fix", "target": {"file_path": "src/B.java"}},
+ {"kind": "finding", "target": {"file_path": "src/c.py"}},
+ ],
+ },
+ "_meta": {},
+ }
+ _attach_preview(result)
+ assert result["_meta"]["preview"] == {"refactoring": {"java": _NOTE}}
+ assert "preview" not in result["fix_first"]["items"][0]
diff --git a/tests/unit/server/test_history_hold_routes.py b/tests/unit/server/test_history_hold_routes.py
new file mode 100644
index 000000000..01474c889
--- /dev/null
+++ b/tests/unit/server/test_history_hold_routes.py
@@ -0,0 +1,110 @@
+"""The history hold on the REST health surfaces: finding lists leave history
+markers on production files out and count them under ``history``, while each
+file's score breakdown, its lead and the work queue's expander still read
+what the score and the queue counted.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core.analysis.finding_registry import FILE_HOLDS
+from repowise.core.persistence import crud
+from repowise.core.persistence.database import get_session
+from tests.unit.server.conftest import create_test_repo
+from tests.unit.server.test_health_file_holds_routes import _finding, _metric, _no_holds
+
+_PROD = "src/app.py"
+_HISTORY_ONLY = "src/legacy.py"
+
+
+async def _seed(app, repo_id: str) -> None:
+ async with get_session(app.state.session_factory) as session:
+ await crud.save_health_metrics(
+ session,
+ repo_id,
+ [
+ _metric(_PROD, 5.5, "production", False),
+ _metric(_HISTORY_ONLY, 8.0, "production", False),
+ ],
+ )
+ await crud.save_health_findings(
+ session,
+ repo_id,
+ [
+ _finding(_PROD, "complex_method", 2.0),
+ _finding(_PROD, "ownership_risk", 1.5),
+ _finding(_PROD, "change_entropy", 1.0),
+ _finding(_HISTORY_ONLY, "ownership_risk", 2.0),
+ ],
+ )
+
+
+async def _get(client: AsyncClient, url: str, **params) -> dict:
+ resp = await client.get(url, params=params)
+ assert resp.status_code == 200, resp.text
+ return resp.json()
+
+
+async def test_repo_list_holds_history_and_says_so(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app, repo["id"])
+ resp = await client.get(f"/api/repos/{repo['id']}/health/findings")
+ assert {(f["file_path"], f["biomarker_type"]) for f in resp.json()} == {
+ (_PROD, "complex_method")
+ }
+ gated = json.loads(resp.headers["X-Repowise-Gated"])
+ assert gated["history"] == {"count": 3, "reason": FILE_HOLDS["history"]}
+
+
+async def test_queue_count_matches_its_expander(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app, repo["id"])
+ base = f"/api/repos/{repo['id']}/health"
+ for history in ("exclude", "include"):
+ queue = await _get(client, f"{base}/refactoring-targets", history=history)
+ assert queue["targets"], history
+ for row in queue["targets"]:
+ resp = await client.get(f"{base}/findings", params={"file_path": row["file_path"]})
+ assert len(resp.json()) == row["finding_count"], (history, row["file_path"])
+ assert "history" not in json.loads(resp.headers.get("X-Repowise-Gated", "{}"))
+ included = await _get(client, f"{base}/refactoring-targets", history="include")
+ assert _HISTORY_ONLY in {r["file_path"] for r in included["targets"]}
+
+
+async def test_breakdown_and_lead_read_what_the_score_counted(
+ client: AsyncClient, app, monkeypatch
+) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app, repo["id"])
+ base = f"/api/repos/{repo['id']}"
+
+ drawer = await _get(client, f"{base}/health/files/breakdown", file_path=_PROD)
+ page = (await _get(client, f"{base}/files/{_PROD}"))["health"]
+ files = {r["file_path"]: r for r in (await _get(client, f"{base}/health/files"))["files"]}
+ # The lists hold the markers and count them.
+ assert [f["biomarker_type"] for f in drawer["findings"]] == ["complex_method"]
+ assert drawer["gated"]["history"]["count"] == 2
+ assert [f["biomarker_type"] for f in page["findings"]] == ["complex_method"]
+ assert page["gated"]["history"]["count"] == 2
+ # A history-only file still has a lead while its score is below 10.
+ assert files[_HISTORY_ONLY]["primary_biomarker"] == "ownership_risk"
+
+ _no_holds(monkeypatch)
+ plain_drawer = await _get(client, f"{base}/health/files/breakdown", file_path=_PROD)
+ plain_page = (await _get(client, f"{base}/files/{_PROD}"))["health"]
+ plain_files = {
+ r["file_path"]: r for r in (await _get(client, f"{base}/health/files"))["files"]
+ }
+ # Breakdown and lead are the same with and without the hold.
+ assert drawer["breakdown"] == plain_drawer["breakdown"]
+ assert drawer["metric"] == plain_drawer["metric"]
+ assert page["breakdown"] == plain_page["breakdown"]
+ assert page["metric"] == plain_page["metric"]
+ assert files == plain_files
diff --git a/tests/unit/server/test_language_gates_rest.py b/tests/unit/server/test_language_gates_rest.py
index 5f2687dac..74395e8cb 100644
--- a/tests/unit/server/test_language_gates_rest.py
+++ b/tests/unit/server/test_language_gates_rest.py
@@ -2,7 +2,9 @@
Each route hides rows on a gated language (Java here) by default, returns
them with ``include_unverified=true``, counts what it held back in ``gated``,
-and leaves the Python rows beside them alone.
+and leaves the Python rows beside them alone. The gate table is patched, so
+these pin the mechanism, not which cells today's table holds back; a preview
+row is served with its ``preview`` note instead.
"""
from __future__ import annotations
@@ -10,8 +12,11 @@ from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
+import pytest
from httpx import AsyncClient
+from repowise.core.analysis import finding_registry
+from repowise.core.analysis.finding_registry import LanguageGate, preview_note
from repowise.core.analysis.health.models import HealthFindingData, Severity
from repowise.core.analysis.health.perf.opportunities import link_performance_findings
from repowise.core.persistence import crud
@@ -20,6 +25,19 @@ from tests.unit.server.conftest import create_test_repo
JAVA = "src/Billing.java"
PY = "src/billing.py"
+_LAYERS = ("health", "refactoring", "performance", "dead_code")
+
+
+def _java_table(state: str) -> tuple[LanguageGate, ...]:
+ return tuple(
+ LanguageGate(layer, "java", 0.2, "test sample", "2026-10-15", "test", state=state)
+ for layer in _LAYERS
+ )
+
+
[email protected](autouse=True)
+def _java_gated(monkeypatch):
+ monkeypatch.setattr(finding_registry, "LANGUAGE_GATES", _java_table("gated"))
def _finding(path: str, function_name: str) -> dict[str, Any]:
@@ -212,3 +230,122 @@ async def test_performance_queue(client: AsyncClient, app) -> None:
assert page["summary"]["total"] == page["total"]
opted = await _get(client, url, **every, include_unverified=True)
assert opted["total"] == page["total"] + 1 and opted["gated"] == {}
+
+
+async def test_preview_rows_are_served_labelled_and_not_counted(
+ client: AsyncClient, app, monkeypatch
+) -> None:
+ repo_id = await _seed(client, app)
+ monkeypatch.setattr(finding_registry, "LANGUAGE_GATES", _java_table("preview"))
+ note = preview_note(_java_table("preview")[0])
+
+ def by_path(rows: list[dict]) -> dict[str, Any]:
+ return {row["file_path"]: row.get("preview") for row in rows}
+
+ findings = await _get(client, f"/api/repos/{repo_id}/health/findings")
+ assert by_path(findings) == {JAVA: note, PY: None}
+
+ queue_rows = await _get(client, f"/api/repos/{repo_id}/health/refactoring-targets")
+ assert by_path(queue_rows["targets"]) == {JAVA: note, PY: None}
+
+ page = await _get(client, f"/api/repos/{repo_id}/files/{JAVA}")
+ assert {f["preview"] for f in page["health"]["findings"]} == {note}
+ assert page["health"]["gated"] == {}
+
+ targets = await _get(client, f"/api/repos/{repo_id}/refactoring/targets")
+ assert by_path(targets["plans"])[JAVA] == note and by_path(targets["plans"])[PY] is None
+ assert targets["gated"] == {}
+
+ queue = await _get(client, f"/api/repos/{repo_id}/refactoring/opportunities", scope="all")
+ assert by_path(queue["items"]) == {JAVA: note, PY: None}
+ assert queue["gated"] == {}
+
+ every = {"context": "all", "proof": "unproven", "role": "all"}
+ perf = await _get(client, f"/api/repos/{repo_id}/health/performance-opportunities", **every)
+ assert by_path(perf["items"]) == {JAVA: note, PY: None} and perf["gated"] == {}
+
+ dead = await _get(client, f"/api/repos/{repo_id}/dead-code")
+ assert by_path(dead) == {JAVA: note, PY: None}
+ summary = await _get(client, f"/api/repos/{repo_id}/dead-code/summary")
+ assert summary["total_findings"] == 2 and summary["gated"] == {}
+
+
+async def test_preview_rows_are_labelled_on_detail_routes(
+ client: AsyncClient, app, monkeypatch
+) -> None:
+ repo_id = await _seed(client, app)
+ monkeypatch.setattr(finding_registry, "LANGUAGE_GATES", _java_table("preview"))
+ note = preview_note(_java_table("preview")[0])
+ base = f"/api/repos/{repo_id}"
+
+ every = {"context": "all", "proof": "unproven", "role": "all"}
+ perf = await _get(client, f"{base}/health/performance-opportunities", **every)
+ for item in perf["items"]:
+ detail = await _get(
+ client, f"{base}/health/performance-opportunities/{item['opportunity_id']}"
+ )
+ assert detail.get("preview") == (note if item["file_path"] == JAVA else None)
+
+ queue = await _get(client, f"{base}/refactoring/opportunities", scope="all")
+ for item in queue["items"]:
+ detail = await _get(client, f"{base}/refactoring/opportunities/{item['opportunity_id']}")
+ assert detail.get("preview") == (note if item["file_path"] == JAVA else None)
+
+ plans = (await _get(client, f"{base}/refactoring/targets"))["plans"]
+ for plan in plans:
+ detail = await _get(client, f"{base}/refactoring/{plan['id']}")
+ assert detail.get("preview") == (note if plan["file_path"] == JAVA else None)
+
+ resp = await client.post(
+ f"{base}/health/related-work", json={"file_paths": [JAVA, PY]}
+ )
+ assert resp.status_code == 200, resp.text
+ lenses = {f["file_path"]: f["lenses"] for f in resp.json()["files"]}
+ assert lenses[JAVA] and all(
+ block.get("preview") == (None if lens == "fix_first" else note)
+ for lens, block in lenses[JAVA].items()
+ )
+ assert all("preview" not in block for block in lenses[PY].values())
+
+
+async def test_preview_rows_are_labelled_on_prompts_and_evidence(
+ client: AsyncClient, app, monkeypatch
+) -> None:
+ repo_id = await _seed(client, app)
+ monkeypatch.setattr(finding_registry, "LANGUAGE_GATES", _java_table("preview"))
+ note = preview_note(_java_table("preview")[0])
+ base = f"/api/repos/{repo_id}"
+ line = f"This language is served as a {note}."
+
+ def check(prompt: dict, on_java: bool) -> None:
+ assert prompt.get("preview") == (note if on_java else None)
+ assert (line in prompt["text"]) is on_java
+
+ queue = await _get(client, f"{base}/refactoring/opportunities", scope="all")
+ for item in queue["items"]:
+ prompt = await _get(
+ client, f"{base}/refactoring/opportunities/{item['opportunity_id']}/prompt"
+ )
+ check(prompt, item["file_path"] == JAVA)
+
+ for plan in (await _get(client, f"{base}/refactoring/targets"))["plans"]:
+ check(await _get(client, f"{base}/refactoring/{plan['id']}/prompt"), plan["file_path"] == JAVA)
+
+ every = {"context": "all", "proof": "unproven", "role": "all"}
+ perf = await _get(client, f"{base}/health/performance-opportunities", **every)
+ seen = set()
+ for item in perf["items"]:
+ evidence = await _get(
+ client, f"{base}/health/performance-opportunities/{item['opportunity_id']}/findings"
+ )
+ for row in evidence["items"]:
+ seen.add(row["file_path"])
+ assert row.get("preview") == (note if row["file_path"] == JAVA else None)
+ assert JAVA in seen
+
+ fix_first = await _get(client, f"{base}/health/fix-first", scope="all", limit=20)
+ for item in fix_first["items"]:
+ prompt = await _get(
+ client, f"{base}/health/fix-first/{item['id']}/prompt", scope="all"
+ )
+ check(prompt, item["target"]["file_path"] == JAVA)