Skip to content

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

feat(health): hold back layers measured below the precision bar per language (#2921)

Raghav Chamadiya89bc2c06a936
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.md
index 0318ff02a..ae267ce64 100644
--- a/docs/layers/REFACTORING.md
+++ b/docs/layers/REFACTORING.md
@@ -135,6 +135,11 @@ the extracted span appeared beside it (Extract Method only, so far). The other
outcomes are `file_deleted`, `superseded` (the same plan found again under a new
id), `target_changed` (renamed or rewritten another way) and `unknown`.
+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`.
+
Break Cycle is advisory. Its plan names edges to cut, not which symbols cross
them or how to move them, so an opportunity carries it as `evidence` rather than
as a numbered step: it never leads, and never reaches Fix first. The plan itself
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index 2ea8c9909..2a48101db 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -354,6 +354,8 @@ Items are ordered by value first, then tier. History markers (churn, ownership,
Provisional finding types appear only with `include=["unverified"]`, each marked `verification: "unverified"`. 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.
+
### Opt-in blocks
| `include` | Adds |
@@ -400,6 +402,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.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/core/src/repowise/core/analysis/actions/build.py b/packages/core/src/repowise/core/analysis/actions/build.py
index 2652373ea..bd1a0e9cf 100644
--- a/packages/core/src/repowise/core/analysis/actions/build.py
+++ b/packages/core/src/repowise/core/analysis/actions/build.py
@@ -64,7 +64,7 @@ from datetime import datetime, timedelta
from typing import Any
from repowise.core.analysis.dead_code.risk_factors import REVIEW_ONLY_KINDS
-from repowise.core.analysis.finding_registry import excluded_types
+from repowise.core.analysis.finding_registry import excluded_types, is_served
from repowise.core.analysis.health.fix_first import build_fix_first
from repowise.core.analysis.health.models import primary_finding, split_by_origin
from repowise.core.analysis.health.rows import field
@@ -206,7 +206,8 @@ def with_leads(files: Mapping[str, FileFacts], findings: Rows) -> dict[str, File
by_path: dict[str, list] = defaultdict(list)
for f in findings:
path = field(f, "file_path")
- if path in wanted and _open(f) and field(f, "biomarker_type") not in hidden:
+ biomarker = field(f, "biomarker_type")
+ if path in wanted and _open(f) and is_served("health", biomarker, path, hidden):
by_path[path].append(f)
out = dict(files)
for path, found in by_path.items():
@@ -286,9 +287,12 @@ def _authored_regression(row: Any) -> bool:
)
-def _shown_code_shape(biomarker: Any, hidden: frozenset[str]) -> bool:
- """A code-shape marker, not a history one, and not one the registry hides."""
- return biomarker_category(biomarker) != HISTORY_CATEGORY and biomarker not in hidden
+def _shown_code_shape(row: Any, hidden: frozenset[str]) -> bool:
+ """A code-shape marker, not a history one, and one the registry serves."""
+ biomarker = field(row, "biomarker_type")
+ return biomarker_category(biomarker) != HISTORY_CATEGORY and is_served(
+ "health", biomarker, field(row, "file_path"), hidden
+ )
def _recent_candidates(
@@ -305,7 +309,7 @@ def _recent_candidates(
continue
if _is_test(field(f, "file_path"), files):
continue
- if _shown_code_shape(field(f, "biomarker_type"), hidden):
+ if _shown_code_shape(f, hidden):
out.append((f, at))
return out
@@ -438,7 +442,7 @@ def build_dead(rows: Rows, files: Mapping[str, FileFacts]) -> dict[str, Any]:
for r in rows
if _open(r)
and field(r, "safe_to_delete")
- and field(r, "kind") not in skipped
+ and is_served("dead_code", field(r, "kind"), field(r, "file_path"), skipped)
and not _is_test(field(r, "file_path"), files)
and not _test_path(field(r, "file_path"))
)
diff --git a/packages/core/src/repowise/core/analysis/change_health/service.py b/packages/core/src/repowise/core/analysis/change_health/service.py
index e215b5a9a..6c711699a 100644
--- a/packages/core/src/repowise/core/analysis/change_health/service.py
+++ b/packages/core/src/repowise/core/analysis/change_health/service.py
@@ -15,7 +15,7 @@ from dataclasses import dataclass
from ...support_paths import is_doc_or_config_path
from ...test_paths import is_test_related_path
-from ..finding_registry import excluded_types
+from ..finding_registry import excluded_types, gate_for, is_served, language_label
from ..health import HEALTH_ANALYZER_VERSION, HealthFindingData
from ..health.perf.causal import PERFORMANCE_MODEL_VERSION
from ..health.scoring import ADVISORY_DIMENSION, is_advisory
@@ -287,23 +287,15 @@ class ChangeHealthDeltaService:
# Advisory markers deduct nothing, so adding one is not a regression
# and removing one is not a fix. Dropped from BOTH sides before
# matching, so every counter derived from the match agrees. Types the
- # finding-type registry withholds go the same way, for the same reason.
+ # finding-type registry withholds go the same way, for the same reason,
+ # as do findings on a language the registry gates for health findings.
withheld = excluded_types()
base_findings = [
f
for f in base_run.findings
- if rename.get(f.file_path, f.file_path) in subject
- and not is_advisory(f.biomarker_type)
- and not _is_test_perf(f)
- and f.biomarker_type not in withheld
- ]
- head_findings = [
- f
- for f in head_run.findings_for(subject)
- if not is_advisory(f.biomarker_type)
- and not _is_test_perf(f)
- and f.biomarker_type not in withheld
+ if rename.get(f.file_path, f.file_path) in subject and _comparable(f, withheld)
]
+ head_findings = [f for f in head_run.findings_for(subject) if _comparable(f, withheld)]
match = matcher.match(base_findings, head_findings)
by_file: dict[str, list[HealthFindingData]] = {}
@@ -339,7 +331,7 @@ class ChangeHealthDeltaService:
resolved_total=len(match.resolved),
unchanged_total=match.unchanged_total,
skipped=skipped,
- limits=_limits(),
+ limits=_limits(head_run.findings_for(subject)),
)
delta.timing_ms = (time.perf_counter() - started) * 1000
return delta
@@ -431,11 +423,34 @@ def _status_for(
return "available", f"Compared {scope.analyzed} changed files on both sides."
-def _limits() -> list[str]:
- return [
+def _limits(head_findings: list[HealthFindingData]) -> list[str]:
+ limits = [
"Both sides are analysed over the changed files only, so cross-file "
"detectors (duplication, cross-function performance) see no wider context."
]
+ gated = sorted(
+ {
+ gate.language
+ for f in head_findings
+ if (gate := gate_for("health", f.file_path, f.biomarker_type)) is not None
+ }
+ )
+ if gated:
+ limits.append(
+ f"Health findings on {', '.join(language_label(g) for g in gated)} files "
+ "are not compared: they are held back pending verification there."
+ )
+ return limits
+
+
+def _comparable(finding: HealthFindingData, withheld: frozenset[str]) -> bool:
+ """A finding both sides of a comparison count: not advisory, not a test's
+ performance finding, and one the registry serves."""
+ return (
+ not is_advisory(finding.biomarker_type)
+ and not _is_test_perf(finding)
+ and is_served("health", finding.biomarker_type, finding.file_path, withheld)
+ )
def _is_test_perf(finding: HealthFindingData) -> bool:
diff --git a/packages/core/src/repowise/core/analysis/dead_code/serving.py b/packages/core/src/repowise/core/analysis/dead_code/serving.py
index d02d660df..4735b448e 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/serving.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/serving.py
@@ -19,7 +19,11 @@ from repowise.core.analysis.dead_code.risk_factors import (
SAFE_CONFIDENCE_THRESHOLD,
path_risk_factors,
)
-from repowise.core.analysis.finding_registry import verification_label, withheld_summary
+from repowise.core.analysis.finding_registry import (
+ split_gated,
+ verification_label,
+ withheld_summary,
+)
from repowise.core.analysis.health.rows import field
from repowise.core.references import path_identity, stable_entity_id
@@ -101,6 +105,18 @@ class FindingFilters:
# Kinds the finding-type registry keeps off this surface. Applied before
# anything is counted, so no total describes a finding the caller cannot see.
withheld_kinds: frozenset[str] = frozenset()
+ # Shows the findings a language gate holds back (``LANGUAGE_GATES``).
+ include_unverified: bool = False
+
+ def split_gated(self, findings: list) -> tuple[list, dict[str, dict]]:
+ """``(shown rows, {gated language: count/reason})``."""
+ return split_gated(
+ "dead_code",
+ findings,
+ kind="kind",
+ get=field,
+ include_unverified=self.include_unverified,
+ )
def split_withheld(self, findings: list) -> tuple[list, dict[str, dict]]:
"""``(shown rows, {withheld kind: count/status/reason})``."""
@@ -194,9 +210,10 @@ def build_summary(
filtered_count: int,
filters: FindingFilters,
withheld: dict[str, dict],
+ gated: dict[str, dict] | None = None,
) -> dict[str, Any]:
"""The summary block: *counts* from :func:`summary_counts`, plus what the
- filters kept."""
+ filters kept and what the registry held back."""
summary: dict[str, Any] = {
"total_findings": counts["total_findings"],
"filtered_findings": filtered_count,
@@ -207,6 +224,8 @@ def build_summary(
filters.summarize(summary)
if withheld:
summary["withheld_types"] = withheld
+ if gated:
+ summary["gated"] = {**gated, "opt_in": {"include_unverified": True}}
return summary
diff --git a/packages/core/src/repowise/core/analysis/finding_registry.py b/packages/core/src/repowise/core/analysis/finding_registry.py
index 1ac343a4b..c6b2513c0 100644
--- a/packages/core/src/repowise/core/analysis/finding_registry.py
+++ b/packages/core/src/repowise/core/analysis/finding_registry.py
@@ -16,13 +16,23 @@ persisted and scored, and the raw CLI analysis still reports them.
A type moves back to ``validated`` only when its measured precision clears the
family floor; the measurement fields record the evidence either way.
+
+:data:`LANGUAGE_GATES` is the same switch for one layer on one language: a
+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.
"""
from __future__ import annotations
-from collections.abc import Iterable, Mapping
+from collections.abc import Callable, Iterable, Mapping
from dataclasses import dataclass
-from typing import Literal
+from pathlib import PurePosixPath
+from typing import Any, Literal
+
+from repowise.core.ingestion.models import EXTENSION_TO_LANGUAGE
FindingStatus = Literal["validated", "provisional", "hidden"]
@@ -80,6 +90,174 @@ REGISTRY: dict[str, FindingTypeStatus] = {
}
+#: The serving layers a gate can apply to. ``health`` is every health finding
+#: (performance findings included); ``refactoring`` is plans and the
+#: opportunities composed from them; ``performance`` is performance
+#: opportunities; ``dead_code`` is every dead-code finding, safe-to-delete or not.
+GateLayer = Literal["health", "refactoring", "performance", "dead_code"]
+
+
+@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.
+ 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.
+ cause: str
+ #: The kinds gated, or ``None`` for every kind of the layer.
+ kinds: frozenset[str] | None = None
+
+
+_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"
+_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."),
+)
+
+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.",
+ ),
+)
+
+
+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)
+
+
+def language_of(path: str) -> str | None:
+ """The language tag a stored path's extension maps to, or ``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."""
+ language = language_of(path)
+ if language is None:
+ return None
+ for gate in gates_on(layer):
+ if gate.language == language and (gate.kinds is None or kind in gate.kinds):
+ return gate
+ return None
+
+
+def is_served(
+ layer: GateLayer, finding_type: Any, path: str, excluded: frozenset[str]
+) -> bool:
+ """A row of *finding_type* on *path* reaches a default surface: its type is
+ not in *excluded* (an :func:`excluded_types` result) and no gate holds back
+ *layer* on its language."""
+ return finding_type not in excluded and gate_for(layer, path, finding_type) is None
+
+
+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))
+
+
+def language_label(language: str) -> str:
+ """The display name of a language tag (``csharp`` reads ``C#``)."""
+ from repowise.core.ingestion.languages import REGISTRY
+
+ spec = REGISTRY.get(language)
+ return spec.display_name if spec is not None else language
+
+
+def held_back_note(languages: Iterable[str]) -> str:
+ """The served sentence for rows held back on *languages*."""
+ names = [language_label(language) for language in languages]
+ return f"Held back on {', '.join(names)} files pending verification."
+
+
+def gated_summary(layer: GateLayer, counts: Mapping[str, int]) -> dict[str, dict]:
+ """``{language: {count, reason}}`` for each gated language with rows on
+ *layer*, so a surface says what it held back. The reason says only that
+ the layer is held back pending verification there."""
+ out: dict[str, dict] = {}
+ for gate in gates_on(layer):
+ count = counts.get(gate.language, 0)
+ if count:
+ out[gate.language] = {"count": count, "reason": held_back_note([gate.language])}
+ return out
+
+
+def split_gated(
+ layer: GateLayer,
+ rows: Iterable[Any],
+ *,
+ kind: str,
+ get: Callable[[Any, str], Any] = getattr,
+ include_unverified: bool = False,
+) -> 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.
+ ``include_unverified`` keeps every row and reports nothing held back.
+ """
+ if include_unverified:
+ return list(rows), {}
+ shown: list[Any] = []
+ counts: dict[str, int] = {}
+ for row in rows:
+ gate = gate_for(layer, get(row, "file_path") or "", get(row, kind))
+ if gate is None:
+ shown.append(row)
+ else:
+ counts[gate.language] = counts.get(gate.language, 0) + 1
+ return shown, gated_summary(layer, counts)
+
+
def status_of(finding_type: str) -> FindingTypeStatus:
return REGISTRY.get(finding_type, _VALIDATED)
@@ -124,12 +302,22 @@ def withheld_summary(counts: Mapping[str, int], excluded: Iterable[str]) -> dict
__all__ = [
+ "LANGUAGE_GATES",
"REGISTRY",
"UNVERIFIED_LABEL",
"FindingStatus",
"FindingTypeStatus",
+ "GateLayer",
+ "LanguageGate",
"excluded_types",
+ "gate_for",
+ "gated_extensions",
+ "gated_summary",
+ "gates_on",
+ "is_served",
"is_shown",
+ "language_of",
+ "split_gated",
"status_of",
"verification_label",
"withheld_summary",
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/serving.py b/packages/core/src/repowise/core/analysis/health/refactoring/serving.py
index 00f43cfd0..cdb4ac853 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/serving.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/serving.py
@@ -15,6 +15,7 @@ from collections.abc import Iterable, Mapping, Sequence
from dataclasses import dataclass
from typing import Any
+from repowise.core.analysis.finding_registry import gate_for
from repowise.core.analysis.health import queue_rules
from repowise.core.analysis.health.effort import EFFORT_ORDER
from repowise.core.analysis.health.queue_rules import Facet, FilterRule, SortKeys
@@ -301,18 +302,33 @@ def evidence_block(
return block
-def summary_payload(row: Any | None) -> dict[str, Any]:
- """The Level-1 rollup from the stored summary row."""
+def _gated_lead(lead: Any, include_unverified: bool) -> bool:
+ """True when the stored lead sits on a file a language gate holds back."""
+ return bool(
+ lead
+ and not include_unverified
+ and gate_for("refactoring", lead.get("file_path") or "", lead.get("lead_refactoring_type"))
+ )
+
+
+def summary_payload(row: Any | None, *, include_unverified: bool = False) -> dict[str, Any]:
+ """The Level-1 rollup from the stored summary row.
+
+ A lead on a gated language is not named (``lead`` is ``None``); the stored
+ totals still count every opportunity.
+ """
if row is None:
return dict(UNAVAILABLE)
payload = _loads_dict(field(row, "summary_json"))
+ if _gated_lead(payload.get("lead"), include_unverified):
+ payload["lead"] = None
payload["status"] = "available"
payload["refactoring_model_version"] = field(row, "refactoring_model_version")
payload["analyzed_commit"] = field(row, "analyzed_commit")
return payload
-def directive_from_summary(row: Any | None) -> dict[str, Any]:
+def directive_from_summary(row: Any | None, *, include_unverified: bool = False) -> dict[str, Any]:
"""The Level-0 lead from the stored summary row: one opportunity, and the
exact call that opens it."""
if row is None:
@@ -320,6 +336,19 @@ def directive_from_summary(row: Any | None) -> dict[str, Any]:
payload = _loads_dict(field(row, "summary_json"))
lead = payload.get("lead")
total = int(payload.get("opportunities_total") or 0)
+ if _gated_lead(lead, include_unverified):
+ # Deliberate shortcut: the finalizer stores one lead, so a gated lead
+ # is withheld rather than replaced by the best shown opportunity.
+ # Upgrade path: store the best lead per gate state at finalize time.
+ return {
+ "status": "clear",
+ "reason": "lead_in_gated_language",
+ "detail": (
+ "The leading refactoring opportunity is on a file held back pending "
+ "verification for its language; include unverified results to see it."
+ ),
+ "opportunities_total": total,
+ }
if not lead:
# The finalizer never leads with a test file, so opportunities
# without a lead are all in tests.
@@ -353,20 +382,27 @@ def directive_from_summary(row: Any | None) -> dict[str, Any]:
"arguments": {"opportunity_id": lead.get("opportunity_id")},
},
}
- # The honest half. A file's plans very often answer a different question
- # from the one that made it the worst file, and saying so beats routing
- # an agent to cleanup it will read as the fix.
+ note = _addresses_note(addresses, lead.get("lead_biomarker"))
+ if note:
+ directive["note"] = note
+ return directive
+
+
+def _addresses_note(addresses: bool | None, lead_biomarker: str | None) -> str | None:
+ """The honest half. A file's plans very often answer a different question
+ from the one that made it the worst file, and saying so beats routing an
+ agent to cleanup it will read as the fix."""
if addresses is False:
- directive["note"] = (
- f"These steps do not address {lead.get('lead_biomarker')!r}, this file's "
+ return (
+ f"These steps do not address {lead_biomarker!r}, this file's "
"dominant finding. Treat them as related cleanup, not the fix for it."
)
- elif addresses is None:
- directive["note"] = (
+ if addresses is None:
+ return (
"No dominant finding was recorded for this file, so whether these steps "
"address it is unknown rather than no."
)
- return directive
+ return None
def next_actions(row: Any, steps: list[dict[str, Any]]) -> list[dict[str, Any]]:
diff --git a/packages/core/src/repowise/core/generation/editor_files/fetcher.py b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
index ba965b434..c06b21299 100644
--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py
+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
@@ -26,6 +26,7 @@ from repowise.core.generation.entry_points import rank_entry_points
from repowise.core.index_scope import load_index_scope, resolve_index_scope
from repowise.core.persistence import crud
from repowise.core.persistence.crud.analysis.fix_first import load_fix_first
+from repowise.core.persistence.crud.analysis.shown import ungated
from repowise.core.persistence.models import (
DecisionRecord,
GitMetadata,
@@ -446,6 +447,7 @@ class EditorFileDataFetcher:
HealthFinding.status == "open",
HealthFinding.dimension == "performance",
HealthFinding.biomarker_type.not_in(excluded_types()),
+ ungated("health", HealthFinding.file_path, HealthFinding.biomarker_type),
)
)
).scalar_one()
diff --git a/packages/core/src/repowise/core/generation/page_generator/helpers.py b/packages/core/src/repowise/core/generation/page_generator/helpers.py
index 553b274dc..851e9a0be 100644
--- a/packages/core/src/repowise/core/generation/page_generator/helpers.py
+++ b/packages/core/src/repowise/core/generation/page_generator/helpers.py
@@ -17,7 +17,7 @@ from typing import Any
from repowise.core.analysis.dead_code.deletion_gate import effective_safe_to_delete
from repowise.core.analysis.decisions.scope import binds_to_paths
-from repowise.core.analysis.finding_registry import excluded_types
+from repowise.core.analysis.finding_registry import excluded_types, gate_for
from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY
from repowise.core.ingestion.models import ParsedFile
@@ -232,13 +232,14 @@ def _select_clone_representatives(
def build_dead_code_map(dead_code_report: Any | None) -> dict[str, list[dict]]:
"""Index dead-code findings by file path for per-page lookup.
- Kinds the finding-type registry withholds never reach a page prompt.
+ Kinds the finding-type registry withholds, and findings on a language it
+ gates for dead code, never reach a page prompt.
"""
dead_code_by_file: dict[str, list[dict]] = {}
withheld = excluded_types()
if dead_code_report is not None and getattr(dead_code_report, "findings", None):
for f in dead_code_report.findings:
- if str(f.kind) in withheld:
+ if str(f.kind) in withheld or gate_for("dead_code", f.file_path, str(f.kind)):
continue
dead_code_by_file.setdefault(f.file_path, []).append(
{
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
index f731b7527..f32f368eb 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
@@ -99,6 +99,7 @@ from .health import (
)
from .performance import (
finalize_performance_opportunities,
+ gated_performance_counts,
get_health_finding_by_public_id,
get_performance_opportunity,
get_performance_plan_rows,
@@ -156,6 +157,7 @@ __all__ = [
"finalize_refactoring_opportunities",
"finalize_refactoring_suggestions",
"finding_data_from_row",
+ "gated_performance_counts",
"get_average_health",
"get_coverage_summary",
"get_dead_code_findings",
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py b/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py
index 28095983f..9c0a43693 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py
@@ -21,6 +21,7 @@ from repowise.core.analysis.finding_registry import excluded_types
from ...models import DeadCodeFinding, _new_uuid
from .._shared import _BATCH_SIZE, _finding_file_path
from ..repository import stamp_analysis_ran
+from .shown import gated_counts, shown, ungated
def _dead_code_row_kwargs(finding: Any, repository_id: str) -> dict:
@@ -232,12 +233,15 @@ async def get_dead_code_findings(
safe_to_delete: bool | None = None,
limit: int | None = None,
include_withheld: bool = False,
+ include_unverified: bool = False,
file_paths: Sequence[str] | None = None,
) -> list[DeadCodeFinding]:
"""Return dead code findings filtered by kind, confidence, and status.
Kinds the finding-type registry withholds are left out unless
``include_withheld``; naming a provisional ``kind`` is an explicit request.
+ Files of a language the registry gates for dead code are left out unless
+ ``include_unverified``, which also opts into every provisional kind.
``safe_to_delete`` and ``limit`` exist so a caller that wants a short
preview does not have to load every open finding in the repository and
@@ -253,7 +257,15 @@ async def get_dead_code_findings(
if kind is not None:
q = q.where(DeadCodeFinding.kind == kind)
if not include_withheld:
- q = q.where(DeadCodeFinding.kind.not_in(excluded_types(requested=[kind] if kind else ())))
+ q = q.where(
+ shown(
+ "dead_code",
+ DeadCodeFinding.kind,
+ DeadCodeFinding.file_path,
+ requested=[kind] if kind else (),
+ include_unverified=include_unverified,
+ )
+ )
if safe_to_delete is not None:
q = q.where(DeadCodeFinding.safe_to_delete.is_(safe_to_delete))
if file_paths is not None:
@@ -282,16 +294,38 @@ async def update_dead_code_status(
return finding
-async def get_dead_code_summary(session: AsyncSession, repository_id: str) -> dict:
- """Return aggregate dead code statistics."""
+async def get_dead_code_summary(
+ session: AsyncSession, repository_id: str, *, include_unverified: bool = False
+) -> dict:
+ """Return aggregate dead code statistics over the findings a surface shows.
+
+ ``gated`` counts the open findings a language gate held back, by language.
+ """
+ scope = (
+ DeadCodeFinding.repository_id == repository_id,
+ DeadCodeFinding.status == "open",
+ DeadCodeFinding.kind.not_in(excluded_types(include_provisional=include_unverified)),
+ )
result = await session.execute(
select(DeadCodeFinding).where(
- DeadCodeFinding.repository_id == repository_id,
- DeadCodeFinding.status == "open",
- DeadCodeFinding.kind.not_in(excluded_types()),
+ *scope,
+ ungated(
+ "dead_code",
+ DeadCodeFinding.file_path,
+ DeadCodeFinding.kind,
+ include_unverified=include_unverified,
+ ),
)
)
findings = list(result.scalars().all())
+ gated = await gated_counts(
+ session,
+ "dead_code",
+ DeadCodeFinding,
+ *scope,
+ kind_col=DeadCodeFinding.kind,
+ include_unverified=include_unverified,
+ )
summary: dict[str, int] = {"high": 0, "medium": 0, "low": 0}
total_lines = 0
@@ -324,4 +358,5 @@ async def get_dead_code_summary(session: AsyncSession, repository_id: str) -> di
"deletable_lines": deletable_lines,
"total_lines": total_lines,
"by_kind": by_kind,
+ "gated": gated,
}
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py b/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py
index a82250a93..9ac4feac4 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py
@@ -75,6 +75,7 @@ from ...models import (
from ...read_snapshots import decode_or_none, read_snapshot, refresh_snapshot, snapshot_key
from ...sql import json_text
from .plain_rows import plain_rows, row_shape
+from .refactoring import shown_plan_predicate
from .refactoring_recommendations import repository_checkout, validation_inputs
#: Files read for plan-less finding items, by open code-shape deduction.
@@ -453,7 +454,13 @@ async def _plans(
s.evidence_json,
s.plan_json,
s.rank_json,
- ).where(s.repository_id == repo_id, or_(*wanted))
+ ).where(
+ s.repository_id == repo_id,
+ or_(*wanted),
+ # The registry's withheld types, as on every plan list. Fix
+ # first is its own measured lens, so no language gate applies.
+ shown_plan_predicate(include_unverified=True),
+ )
)
)
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 05503e269..2644aa195 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
@@ -48,6 +48,7 @@ from ...models import (
)
from .._shared import _BATCH_SIZE
from .plain_rows import plain_rows
+from .shown import shown
def _health_finding_row_kwargs(finding: Any, repository_id: str) -> dict:
@@ -493,6 +494,7 @@ async def get_health_findings(
exclude_dimensions: tuple[str, ...] | None = None,
status: str = "open",
include_withheld: bool = False,
+ include_unverified: bool = False,
limit: int | None = None,
) -> list[HealthFinding]:
"""Findings for one repository: worth doing first ahead of lower-priority
@@ -501,7 +503,10 @@ async def get_health_findings(
Finding types the registry withholds (``finding_registry``) are left out,
so every surface built on this read shows only what has earned a place; a
provisional type named in ``biomarker_type`` is an explicit request and is
- returned. ``include_withheld`` is for analysis that must see every row.
+ returned. Files of a language the registry gates for health findings are
+ left out too, unless ``include_unverified`` (which also opts into every
+ provisional type). ``include_withheld`` is for analysis that must see every
+ row.
``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``
@@ -536,7 +541,15 @@ async def get_health_findings(
if types:
q = q.where(HealthFinding.biomarker_type.in_(types))
if not include_withheld:
- q = q.where(HealthFinding.biomarker_type.not_in(excluded_types(requested=types)))
+ q = q.where(
+ shown(
+ "health",
+ HealthFinding.biomarker_type,
+ HealthFinding.file_path,
+ requested=types,
+ include_unverified=include_unverified,
+ )
+ )
if file_path is not None:
q = q.where(HealthFinding.file_path == file_path)
if file_paths is not None:
@@ -750,7 +763,7 @@ async def _open_finding_totals_rows(session: AsyncSession, repository_id: str) -
.where(
HealthFinding.repository_id == repository_id,
HealthFinding.status == "open",
- HealthFinding.biomarker_type.not_in(excluded_types()),
+ shown("health", HealthFinding.biomarker_type, HealthFinding.file_path),
)
.order_by(HealthFinding.health_impact.desc(), HealthFinding.id)
)
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/performance.py b/packages/core/src/repowise/core/persistence/crud/analysis/performance.py
index f2c9745c2..f48cc9cad 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/performance.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/performance.py
@@ -30,6 +30,7 @@ from ...models import (
)
from ...sql import order_by, rule_predicate
from .refactoring import _refactoring_row_kwargs
+from .shown import gated_counts, ungated
if TYPE_CHECKING:
from ....analysis.execution_roles import ExecutionRoles
@@ -491,13 +492,25 @@ async def get_performance_opportunity(
return result.scalars().first()
-def _predicates(repository_id: str, **params: Any) -> list[Any]:
- """The ``WHERE`` for *params* over open rows, built from the serving layer's filter table."""
+def _predicates(
+ repository_id: str, *, include_unverified: bool = False, **params: Any
+) -> list[Any]:
+ """The ``WHERE`` for *params* over open rows, built from the serving layer's filter table.
+
+ Opportunities on a file of a language the registry gates for performance
+ are left out unless ``include_unverified``.
+ """
from ....analysis.health.perf.serving import FILTERS
from ....analysis.health.queue_rules import active_filters
return [
PerformanceOpportunity.repository_id == repository_id,
+ ungated(
+ "performance",
+ PerformanceOpportunity.file_path,
+ PerformanceOpportunity.biomarker_type,
+ include_unverified=include_unverified,
+ ),
*(
rule_predicate(PerformanceOpportunity, rule, value)
for rule, value in active_filters(FILTERS, {"status": "open", **params})
@@ -520,6 +533,7 @@ async def list_performance_opportunities(
sort: str = "rank",
limit: int = 20,
offset: int = 0,
+ include_unverified: bool = False,
) -> tuple[list[PerformanceOpportunity], int]:
"""One page in the requested order, plus the exact total behind it.
@@ -538,6 +552,7 @@ async def list_performance_opportunities(
roles=roles,
queue_eligible=queue_eligible,
file_paths=file_paths,
+ include_unverified=include_unverified,
)
total = int(
(
@@ -567,6 +582,7 @@ async def performance_facet_counts(
repository_id: str,
*,
file_paths: tuple[str, ...] | None = None,
+ include_unverified: bool = False,
) -> list[tuple[str, str | None, str, str, str, str, str, int]]:
"""Grouped counts over every open opportunity, in one aggregate statement.
@@ -580,7 +596,11 @@ async def performance_facet_counts(
columns = tuple(getattr(PerformanceOpportunity, name) for name in FACET_FIELDS)
result = await session.execute(
select(*columns, func.count())
- .where(*_predicates(repository_id, file_paths=file_paths))
+ .where(
+ *_predicates(
+ repository_id, file_paths=file_paths, include_unverified=include_unverified
+ )
+ )
.group_by(*columns)
)
return [tuple(row) for row in result.all()]
@@ -604,6 +624,21 @@ class PerformanceFileRollup(NamedTuple):
"""Lowest ``rank_position`` on the file, so a map can rank files by cause."""
+async def gated_performance_counts(
+ session: AsyncSession, repository_id: str, *, include_unverified: bool = False
+) -> dict[str, dict]:
+ """The open opportunities a language gate holds back, by language."""
+ return await gated_counts(
+ session,
+ "performance",
+ PerformanceOpportunity,
+ PerformanceOpportunity.repository_id == repository_id,
+ PerformanceOpportunity.status == "open",
+ kind_col=PerformanceOpportunity.biomarker_type,
+ include_unverified=include_unverified,
+ )
+
+
async def performance_file_rollups(
session: AsyncSession,
repository_id: str,
@@ -812,6 +847,7 @@ async def get_health_finding_by_public_id(
__all__ = [
"finalize_performance_opportunities",
+ "gated_performance_counts",
"get_health_finding_by_public_id",
"get_performance_opportunity",
"get_performance_plan_rows",
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py
index 3a7ae180d..2f406bdad 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py
@@ -17,6 +17,7 @@ from typing import TYPE_CHECKING, Any
from sqlalchemy import (
Select,
+ and_,
bindparam,
case,
func,
@@ -32,6 +33,7 @@ from ....analysis.finding_registry import excluded_types
from ...models import RefactoringSuggestion, _new_uuid, _now_utc
from ...sql import rule_predicate
from .._shared import _BATCH_SIZE, _finding_file_path
+from .shown import gated_counts, ungated
if TYPE_CHECKING:
from datetime import datetime
@@ -465,15 +467,49 @@ async def get_refactoring_suggestion(
return result.scalar_one_or_none()
-def shown_plan_predicate() -> Any:
- """Plans whose source biomarker the finding registry does not withhold.
+def _registry_shown_plan() -> Any:
+ return or_(
+ RefactoringSuggestion.source_biomarker.is_(None),
+ RefactoringSuggestion.source_biomarker.not_in(excluded_types()),
+ )
+
+
+def shown_plan_predicate(*, include_unverified: bool = False) -> Any:
+ """Plans whose source biomarker the finding registry does not withhold, on
+ files of a language no gate holds refactoring back on.
Plans are persisted whatever the registry says; every surface that lists
them filters here. A plan with no source biomarker (structural) is shown.
+ ``include_unverified`` opts into the gated languages.
"""
- return or_(
- RefactoringSuggestion.source_biomarker.is_(None),
- RefactoringSuggestion.source_biomarker.not_in(excluded_types()),
+ return and_(
+ _registry_shown_plan(),
+ ungated(
+ "refactoring",
+ RefactoringSuggestion.file_path,
+ RefactoringSuggestion.refactoring_type,
+ include_unverified=include_unverified,
+ ),
+ )
+
+
+async def gated_plan_counts(
+ session: AsyncSession,
+ repository_id: str,
+ *,
+ status: str = "open",
+ include_unverified: bool = False,
+) -> dict[str, dict]:
+ """The plans a language gate holds back, by language (see ``shown.gated_counts``)."""
+ return await gated_counts(
+ session,
+ "refactoring",
+ RefactoringSuggestion,
+ RefactoringSuggestion.repository_id == repository_id,
+ RefactoringSuggestion.status == status,
+ _registry_shown_plan(),
+ kind_col=RefactoringSuggestion.refactoring_type,
+ include_unverified=include_unverified,
)
@@ -484,11 +520,12 @@ def _suggestion_filters(
file_paths: list[str] | None,
min_confidence: str | None,
status: str,
+ include_unverified: bool = False,
) -> list[Any]:
predicates: list[Any] = [
RefactoringSuggestion.repository_id == repository_id,
RefactoringSuggestion.status == status,
- shown_plan_predicate(),
+ shown_plan_predicate(include_unverified=include_unverified),
]
if refactoring_type is not None:
predicates.append(RefactoringSuggestion.refactoring_type == refactoring_type)
@@ -512,10 +549,11 @@ async def get_refactoring_suggestions(
status: str = "open",
limit: int | None = None,
offset: int | None = None,
+ include_unverified: bool = False,
) -> list[RefactoringSuggestion]:
"""Return refactoring suggestions, highest recovered impact first.
- Plans from a registry-withheld biomarker are left out
+ Plans from a registry-withheld biomarker or a gated language are left out
(:func:`shown_plan_predicate`). *limit* / *offset* page in SQL. Both default to ``None``, which returns the
whole filtered set exactly as before, because the callers that still rank
and page in memory have not been rewired yet (R4).
@@ -527,6 +565,7 @@ async def get_refactoring_suggestions(
file_paths=file_paths,
min_confidence=min_confidence,
status=status,
+ include_unverified=include_unverified,
)
)
# Secondary keys (file_path, target_symbol) make the read order stable for
@@ -553,6 +592,7 @@ async def count_refactoring_suggestions(
file_paths: list[str] | None = None,
min_confidence: str | None = None,
status: str = "open",
+ include_unverified: bool = False,
) -> int:
"""The total behind a page, counted in SQL rather than by materializing it."""
q = (
@@ -565,6 +605,7 @@ async def count_refactoring_suggestions(
file_paths=file_paths,
min_confidence=min_confidence,
status=status,
+ include_unverified=include_unverified,
)
)
)
@@ -672,6 +713,7 @@ async def ranked_refactoring_suggestions(
min_confidence: str | None = None,
filters: Mapping[str, Any] | None = None,
view: str = "canonical",
+ include_unverified: bool = False,
) -> list[RefactoringSuggestion] | None:
"""The open plans in persisted rank order.
@@ -689,6 +731,7 @@ async def ranked_refactoring_suggestions(
file_paths=None,
min_confidence=min_confidence,
status="open",
+ include_unverified=include_unverified,
)
unranked = await session.execute(
select(RefactoringSuggestion.id)
@@ -707,7 +750,11 @@ async def ranked_refactoring_suggestions(
async def summarize_open_plans(
- session: AsyncSession, repository_id: str, *, min_confidence: str | None = None
+ session: AsyncSession,
+ repository_id: str,
+ *,
+ min_confidence: str | None = None,
+ include_unverified: bool = False,
) -> dict[str, Any]:
"""The plan board's chip counts over the open plans, from narrow columns.
@@ -733,6 +780,7 @@ async def summarize_open_plans(
file_paths=None,
min_confidence=min_confidence,
status="open",
+ include_unverified=include_unverified,
)
)
)
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py
index 43da1a493..8b83a706e 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py
@@ -31,6 +31,7 @@ from ...models import (
_now_utc,
)
from ...sql import order_by, rule_predicate
+from .shown import gated_counts, ungated
if TYPE_CHECKING:
from ....analysis.health.refactoring.opportunity import (
@@ -619,11 +620,15 @@ async def _write_summary(
# ---------------------------------------------------------------------------
-def _opportunity_filters(repository_id: str, **params: Any) -> list[Any]:
+def _opportunity_filters(
+ repository_id: str, *, include_unverified: bool = False, **params: Any
+) -> list[Any]:
"""The ``WHERE`` for *params*, built from the serving layer's filter table.
Only the current model's rows are served: an older model's ids are never
- composed again, so a row of one is history, not queue.
+ composed again, so a row of one is history, not queue. Opportunities on a
+ file of a language the registry gates for refactoring are left out unless
+ ``include_unverified``.
"""
from ....analysis.health.queue_rules import active_filters
from ....analysis.health.refactoring.identity import REFACTORING_MODEL_VERSION
@@ -632,6 +637,12 @@ def _opportunity_filters(repository_id: str, **params: Any) -> list[Any]:
return [
RefactoringOpportunity.repository_id == repository_id,
RefactoringOpportunity.refactoring_model_version == REFACTORING_MODEL_VERSION,
+ ungated(
+ "refactoring",
+ RefactoringOpportunity.file_path,
+ RefactoringOpportunity.lead_refactoring_type,
+ include_unverified=include_unverified,
+ ),
*(
rule_predicate(RefactoringOpportunity, rule, value)
for rule, value in active_filters(FILTERS, params)
@@ -639,6 +650,28 @@ def _opportunity_filters(repository_id: str, **params: Any) -> list[Any]:
]
+async def gated_opportunity_counts(
+ session: AsyncSession,
+ repository_id: str,
+ *,
+ status: str = "open",
+ include_unverified: bool = False,
+) -> dict[str, dict]:
+ """The current-model opportunities a language gate holds back, by language."""
+ from ....analysis.health.refactoring.identity import REFACTORING_MODEL_VERSION
+
+ return await gated_counts(
+ session,
+ "refactoring",
+ RefactoringOpportunity,
+ RefactoringOpportunity.repository_id == repository_id,
+ RefactoringOpportunity.refactoring_model_version == REFACTORING_MODEL_VERSION,
+ RefactoringOpportunity.status == status,
+ kind_col=RefactoringOpportunity.lead_refactoring_type,
+ include_unverified=include_unverified,
+ )
+
+
async def list_refactoring_opportunities(
session: AsyncSession,
repository_id: str,
@@ -657,12 +690,14 @@ async def list_refactoring_opportunities(
order: str | None = None,
limit: int = 20,
offset: int = 0,
+ include_unverified: bool = False,
) -> tuple[list[RefactoringOpportunity], int]:
"""One page and its total: two statements, whatever the row count."""
from ....analysis.health.refactoring.serving import sort_keys
predicates = _opportunity_filters(
repository_id,
+ include_unverified=include_unverified,
status=status,
lead_types=lead_types,
confidence=confidence,
@@ -903,6 +938,7 @@ async def owning_refactoring_opportunity(
__all__ = [
"finalize_refactoring_opportunities",
+ "gated_opportunity_counts",
"get_refactoring_opportunity",
"get_refactoring_summary",
"list_refactoring_opportunities",
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/shown.py b/packages/core/src/repowise/core/persistence/crud/analysis/shown.py
new file mode 100644
index 000000000..b177aa623
--- /dev/null
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/shown.py
@@ -0,0 +1,93 @@
+"""The finding registry as SQL: what a serving read may show.
+
+``finding_registry`` decides by finding type (``excluded_types``) and by layer
+and language (``LANGUAGE_GATES``). Reads that list or count rows for a surface
+filter here, so every surface agrees on what is held back. Reads by id and the
+writers do not: a held-back row is still stored and addressable.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from typing import Any
+
+from sqlalchemy import and_, case, func, not_, or_, select, true
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from ....analysis.finding_registry import (
+ GateLayer,
+ excluded_types,
+ gated_extensions,
+ gated_summary,
+ gates_on,
+)
+
+
+def _cells(layer: GateLayer, path_col: Any, kind_col: Any) -> list[tuple[str, Any]]:
+ """``(language, row matches that gate)`` for each gate on *layer*."""
+ cells = []
+ 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:
+ match = and_(match, kind_col.in_(sorted(gate.kinds)))
+ cells.append((gate.language, match))
+ return cells
+
+
+def ungated(
+ layer: GateLayer, path_col: Any, kind_col: Any = None, *, include_unverified: bool = False
+) -> Any:
+ """Rows of *layer* no language gate holds back (everything when opted in)."""
+ cells = [] if include_unverified else _cells(layer, path_col, kind_col)
+ return not_(or_(*(match for _, match in cells))) if cells else true()
+
+
+def shown(
+ layer: GateLayer,
+ kind_col: Any,
+ path_col: Any,
+ *,
+ requested: Iterable[str] = (),
+ include_unverified: bool = False,
+) -> Any:
+ """Rows whose type the registry shows and whose language no gate holds back.
+
+ *kind_col* holds a registry type (a biomarker type or a dead-code kind).
+ ``include_unverified`` opts into provisional types and gated languages alike.
+ """
+ return and_(
+ kind_col.not_in(
+ excluded_types(requested=requested, include_provisional=include_unverified)
+ ),
+ ungated(layer, path_col, kind_col, include_unverified=include_unverified),
+ )
+
+
+async def gated_counts(
+ session: AsyncSession,
+ layer: GateLayer,
+ model: Any,
+ *where: Any,
+ kind_col: Any = None,
+ include_unverified: bool = False,
+) -> dict[str, dict]:
+ """What the gates on *layer* hold back among *model* rows matching *where*.
+
+ ``{language: {count, reason}}``, from one grouped count, so a
+ 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)
+ if not cells:
+ return {}
+ language = case(*((match, lang) for lang, match in cells))
+ rows = await session.execute(
+ select(language, func.count())
+ .select_from(model)
+ .where(*where, or_(*(match for _, match in cells)))
+ .group_by(language)
+ )
+ return gated_summary(layer, {lang: int(n) for lang, n in rows.all()})
+
+
+__all__ = ["gated_counts", "shown", "ungated"]
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
index ec427cc68..fa5ec2a2f 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
@@ -52,6 +52,7 @@ from repowise.core.persistence.crud import (
load_coverage_for_repo,
serialize_doc_drift_reference_row,
)
+from repowise.core.persistence.crud.analysis.shown import ungated
from repowise.core.persistence.models import (
GraphEdge,
GraphNode,
@@ -733,6 +734,7 @@ async def _resolve_health(
HealthFinding.file_path == file_path,
HealthFinding.status == "open",
HealthFinding.biomarker_type.not_in(excluded_types()),
+ ungated("health", HealthFinding.file_path, HealthFinding.biomarker_type),
)
.order_by(HealthFinding.health_impact.desc())
.limit(2)
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 47e3f8e49..e50592c74 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
@@ -68,6 +68,7 @@ async def _get_dead_code_all_repos(
merged_findings: list[dict] = []
count_parts: list[dict[str, Any]] = []
merged_withheld: dict[str, dict] = {}
+ merged_gated: dict[str, dict] = {}
for ctx in contexts:
async with get_session(ctx.session_factory) as session:
@@ -79,9 +80,11 @@ async def _get_dead_code_all_repos(
_get_exclude_spec(ctx.path),
)
repo_findings, repo_withheld = filters.split_withheld(repo_findings)
- for name, entry in repo_withheld.items():
- merged = merged_withheld.setdefault(name, {**entry, "count": 0})
- merged["count"] += entry["count"]
+ repo_findings, repo_gated = filters.split_gated(repo_findings)
+ for into, held in ((merged_withheld, repo_withheld), (merged_gated, repo_gated)):
+ for name, entry in held.items():
+ merged = into.setdefault(name, {**entry, "count": 0})
+ merged["count"] += entry["count"]
git_meta_map = await _load_git_meta_map(session, repository.id, repo_findings)
@@ -92,7 +95,11 @@ async def _get_dead_code_all_repos(
count_parts.append(summary_counts(repo_findings))
summary = build_summary(
- merge_summary_counts(count_parts), len(merged_findings), filters, merged_withheld
+ merge_summary_counts(count_parts),
+ len(merged_findings),
+ filters,
+ merged_withheld,
+ merged_gated,
)
tiers = build_tiers(merged_findings, limit, tier)
adjust_cross_repo(tiers, _cross_repo_lookup())
@@ -164,6 +171,7 @@ async def get_dead_code(
no_unreachable: bool = False,
no_unused_exports: bool = False,
finding_id: str | None = None,
+ include_unverified: bool = False,
) -> dict:
"""Unused exports, unreachable files, zombie packages — tiered by confidence.
@@ -188,6 +196,8 @@ async def get_dead_code(
include_zombie_packages: monorepo package findings (default true).
no_unreachable: skip file-level reachability findings.
no_unused_exports: skip public-export findings.
+ include_unverified: also show provisional kinds and languages held
+ back pending verification (``summary.gated`` counts them).
finding_id: stable ``id`` emitted by a dead-code finding.
"""
# MCP transport rejects payloads above ~25k tokens. A single serialized
@@ -221,8 +231,10 @@ async def get_dead_code(
# Naming a kind, or ``include_internals`` for ``unused_internal``, is the
# explicit request a provisional kind needs; a hidden kind stays out.
withheld_kinds=excluded_types(
- requested=[k for k in (kind, "unused_internal" if include_internals else None) if k]
+ requested=[k for k in (kind, "unused_internal" if include_internals else None) if k],
+ include_provisional=include_unverified,
),
+ include_unverified=include_unverified,
)
def _maybe_limit_note(target: dict[str, Any]) -> None:
@@ -267,19 +279,22 @@ async def get_dead_code(
# Fetch all open findings for summary computation. Withheld kinds are
# read too, so the summary can count what it leaves out.
- all_findings, withheld = filters.split_withheld(
+ every_shown_kind, withheld = filters.split_withheld(
await get_dead_code_findings(session, repository.id, include_withheld=True)
)
+ # A lookup by id still answers for a gated finding; lists do not show it.
+ all_findings, gated = filters.split_gated(every_shown_kind)
- # Phase 4: load git metadata for "last meaningful change" enrichment
- git_meta_map = await _load_git_meta_map(session, repository.id, all_findings)
+ # Phase 4: load git metadata for "last meaningful change" enrichment,
+ # over the gated rows too so a lookup by id is enriched the same way.
+ git_meta_map = await _load_git_meta_map(session, repository.id, every_shown_kind)
reference_repository = ctx.alias or repository.name
if finding_id:
match = next(
(
row
- for row in all_findings
+ for row in every_shown_kind
if finding_id in {row.id, dead_code_finding_id(row, reference_repository)}
),
None,
@@ -315,7 +330,7 @@ async def get_dead_code(
)
tiers = build_tiers(serialized, limit, tier, on_overflow=_keep_overflow)
- summary = build_summary(summary_counts(all_findings), len(filtered), filters, withheld)
+ summary = build_summary(summary_counts(all_findings), len(filtered), filters, withheld, gated)
adjust_cross_repo(tiers, _cross_repo_lookup(), ctx.alias)
result: dict[str, Any] = {"summary": summary, "tiers": tiers}
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/findings.py b/packages/server/src/repowise/server/mcp_server/tool_health/findings.py
index 3e2e9831a..2c8a37e45 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/findings.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/findings.py
@@ -9,6 +9,7 @@ from sqlalchemy import select
from repowise.core.analysis.health.worth import LOW_PRIORITY_LABEL, finding_priorities
from repowise.core.persistence.crud.analysis.plain_rows import plain_rows
+from repowise.core.persistence.crud.analysis.shown import gated_counts, ungated
from repowise.core.persistence.models import HealthFinding
from repowise.server.mcp_server.tool_health.population import Population
from repowise.server.mcp_server.tool_health.request import HealthRequest
@@ -79,6 +80,19 @@ def _tiered(rows: list[Any], measured_over: list[Any]) -> tuple[list[Any], dict[
def _open_findings(repository: Any, req: HealthRequest) -> tuple[Any, ...]:
+ return (
+ *_open_typed(repository, req),
+ ungated(
+ "health",
+ HealthFinding.file_path,
+ HealthFinding.biomarker_type,
+ include_unverified=req.include_unverified,
+ ),
+ )
+
+
+def _open_typed(repository: Any, req: HealthRequest) -> tuple[Any, ...]:
+ """Open findings of a type the registry shows, before any language gate."""
return (
HealthFinding.repository_id == repository.id,
HealthFinding.status == "open",
@@ -86,6 +100,23 @@ def _open_findings(repository: Any, req: HealthRequest) -> tuple[Any, ...]:
)
+async def gated_findings(
+ session: Any, repository: Any, pop: Population, req: HealthRequest
+) -> dict[str, dict]:
+ """The open findings a language gate held back from this call, by language."""
+ where = list(_open_typed(repository, req))
+ if pop.scoped:
+ where.append(HealthFinding.file_path.in_(pop.effective_targets))
+ return await gated_counts(
+ session,
+ "health",
+ HealthFinding,
+ *where,
+ kind_col=HealthFinding.biomarker_type,
+ include_unverified=req.include_unverified,
+ )
+
+
async def load_targeted_findings(
session: Any, repository: Any, pop: Population, req: HealthRequest
) -> FindingSets:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py b/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
index d23a330bc..4677d1cec 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
@@ -40,10 +40,12 @@ from repowise.core.persistence.crud import (
)
from repowise.core.persistence.crud.analysis.fix_first import load_fix_first, queue_view
from repowise.core.persistence.crud.analysis.queue_counts import unit_counts
+from repowise.core.persistence.crud.analysis.refactoring import gated_plan_counts
from repowise.core.persistence.models import HealthFileMetric
from repowise.server.mcp_server._helpers import filter_rows_by_attr
from repowise.server.mcp_server.tool_health.findings import (
FindingSets,
+ gated_findings,
load_dashboard_findings,
load_targeted_findings,
read_accuracy_rows,
@@ -104,6 +106,8 @@ class HealthData:
test_metric_rows: list[HealthFileMetric] = field(default_factory=list)
#: Dashboard only: files in neither list, by the scope reason that left them out.
worst_files_hidden: dict[str, int] = field(default_factory=dict)
+ # What a language gate held back, ``{layer: {language: {count, ...}}}``.
+ gated: dict[str, dict] = field(default_factory=dict)
async def load_health_data(
@@ -179,9 +183,30 @@ async def load_health_data(
if "top_findings" in req.only_set and not pop.nothing_resolved:
counts = await unit_counts(session, repository.id, "findings", file_paths=pop.target_paths)
data.finding_counts = counts.as_dict()
+ data.gated = await _read_gated(session, req, data)
return data
+async def _read_gated(session: Any, req: HealthRequest, data: HealthData) -> dict[str, dict]:
+ """What a language gate held back, per layer this call read."""
+ refactoring = (
+ data.refactoring.page.gated
+ if data.refactoring.page
+ # Plans only: the queue was not read, so count the plans it held back.
+ else await gated_plan_counts(
+ session, data.repository.id, include_unverified=req.include_unverified
+ )
+ if req.plans_requested
+ else {}
+ )
+ layers = {
+ "health": await gated_findings(session, data.repository, data.pop, req),
+ "refactoring": refactoring,
+ "performance": data.performance.page.gated if data.performance.page else {},
+ }
+ return {layer: counts for layer, counts in layers.items() if counts}
+
+
def _scope_reasons(metrics: list[HealthFileMetric]) -> dict[str, str | None]:
"""Each file's scope exclusion (``test``, ``tooling``, ``generated``...), ``None``
in scope: Fix first's rule on Fix first's inputs, the row's flag and origin.
@@ -268,10 +293,10 @@ async def _read_pillars(
linkage, and facets are the shared service's; this tool caps the
collection, pages it, and serializes what comes back."""
performance_service = PerformanceHealthService(
- session, repository.id, reference_repository
+ session, repository.id, reference_repository, include_unverified=req.include_unverified
)
refactoring_service = RefactoringHealthService(
- session, repository.id, reference_repository
+ session, repository.id, reference_repository, include_unverified=req.include_unverified
)
refactoring = await _refactoring_blocks(
refactoring_service,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/request.py b/packages/server/src/repowise/server/mcp_server/tool_health/request.py
index 855ee6a7b..97b817bc9 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/request.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/request.py
@@ -55,7 +55,8 @@ _KNOWN_INCLUDES = frozenset(
"defect",
"maintainability",
"advisory",
- # Opts into provisional finding types, each labelled "unverified".
+ # Opts into provisional finding types, each labelled "unverified", and
+ # into the layers a language gate holds back.
"unverified",
# The shared legend for deficit points and percentiles, in ``_meta``.
"semantics",
@@ -105,6 +106,7 @@ class HealthRequest:
withheld_types: frozenset[str] = field(init=False)
#: The caller passed ``limit``: a response grows past a default only when asked.
limit_explicit: bool = field(init=False)
+ include_unverified: bool = field(init=False)
def __post_init__(self) -> None:
self.limit_explicit = self.limit is not None
@@ -122,7 +124,8 @@ class HealthRequest:
self.dimension_filter = self.include_set & set(ALL_DIMENSIONS)
# Finding types the registry keeps off this surface, dropped at the read
# so no list, lead or total counts one.
- self.withheld_types = excluded_types(include_provisional="unverified" in self.include_set)
+ self.include_unverified = "unverified" in self.include_set
+ self.withheld_types = excluded_types(include_provisional=self.include_unverified)
# Performance findings carry zero impact, so an impact-ranked list
# leaves them out unless asked for; the performance blocks rank them.
self.ranked_dimensions = self.dimension_filter or _RANKED_DIMENSIONS_DEFAULT
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 14097d709..5817940b9 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
@@ -251,6 +251,7 @@ async def get_health(
await _attach_repository_analysis_meta(session, repository, result["_meta"])
else:
_attach_health_analysis_meta(result["_meta"], data.pop.all_metrics)
+ _attach_gated(result["_meta"], data)
pager.report_omissions(result, omission_collector)
omission_collector.attach(result)
_attach_semantics(result, req)
@@ -259,6 +260,13 @@ async def get_health(
return result
+def _attach_gated(meta: dict[str, Any], data: HealthData) -> None:
+ """What a language gate held back, in ``_meta`` so no ``only`` projection
+ drops it: an agent must read "held back", never "nothing found"."""
+ if data.gated:
+ meta["gated"] = {**data.gated, "opt_in": {"include": ["unverified"]}}
+
+
def _attach_semantics(result: dict[str, Any], req: HealthRequest) -> None:
"""The unit legend, on request: it is the same on every call."""
if "semantics" in req.include_set:
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 6740bc79b..dfeba6857 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
@@ -7,6 +7,7 @@ from typing import Any
from sqlalchemy import select
from repowise.core.analysis.finding_registry import excluded_types
+from repowise.core.persistence.crud.analysis.shown import ungated
from repowise.core.persistence.database import get_session
from repowise.server.mcp_server import _state
from repowise.server.mcp_server._budget import OmissionCollector, cap_collection
@@ -357,6 +358,7 @@ 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),
)
.order_by(HealthFinding.health_impact.desc())
)
diff --git a/packages/server/src/repowise/server/routers/_repo_summary.py b/packages/server/src/repowise/server/routers/_repo_summary.py
index 2bcc18fbe..9d5158da8 100644
--- a/packages/server/src/repowise/server/routers/_repo_summary.py
+++ b/packages/server/src/repowise/server/routers/_repo_summary.py
@@ -13,6 +13,7 @@ from sqlalchemy import case, func, select
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.persistence.crud.analysis.shown import ungated
from repowise.core.persistence.models import (
DeadCodeFinding,
GitMetadata,
@@ -79,6 +80,7 @@ async def _dead_export_figures(session: AsyncSession) -> _Figures:
.where(
DeadCodeFinding.kind == "unused_export",
DeadCodeFinding.status == "open",
+ ungated("dead_code", DeadCodeFinding.file_path, DeadCodeFinding.kind),
)
.group_by(DeadCodeFinding.repository_id)
)
diff --git a/packages/server/src/repowise/server/routers/_unverified.py b/packages/server/src/repowise/server/routers/_unverified.py
new file mode 100644
index 000000000..0778b08c7
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/_unverified.py
@@ -0,0 +1,13 @@
+"""The opt-in that shows what the finding registry holds back by default."""
+
+from __future__ import annotations
+
+from fastapi import Query
+
+UnverifiedQuery = Query(
+ False,
+ description=(
+ "Also return provisional finding types and the per-language layers held back "
+ "pending verification. Without it, a response counts what it held back in `gated`."
+ ),
+)
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 42aea7d9c..ae03b9bc6 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
@@ -7,12 +7,14 @@ from typing import Any
from fastapi import Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.finding_registry import split_gated
from repowise.core.analysis.health.perf.coverage import supported_perf_languages
from repowise.core.analysis.health.suggestions import suggestion_for as _suggestion_for
from repowise.core.analysis.health.trends import file_trend
from repowise.core.persistence import crud
from repowise.server.deps import get_db_session
+from .._unverified import UnverifiedQuery
from ._router import router
from .breakdown import _score_breakdown_from_findings
from .counts import CountsQuery, project
@@ -145,13 +147,21 @@ async def file_score_breakdown(
repo_id: str,
file_path: str = Query(..., description="File path to break down"),
counts: str = CountsQuery,
+ include_unverified: bool = UnverifiedQuery,
session: AsyncSession = Depends(get_db_session),
) -> dict:
repo = await crud.get_repository(session, repo_id)
if repo is None:
raise HTTPException(status_code=404, detail="Repository not found")
metrics = await crud.get_health_metrics(session, repo_id, file_paths=[file_path])
- findings = await crud.get_health_findings(session, repo_id, file_path=file_path)
+ findings = await crud.get_health_findings(
+ session, repo_id, file_path=file_path, include_unverified=True
+ )
+ # The score counts every finding; a gated one is held back from the list
+ # and the breakdown, and ``gated`` says how many.
+ findings, gated = split_gated(
+ "health", findings, kind="biomarker_type", include_unverified=include_unverified
+ )
# 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.
@@ -175,6 +185,7 @@ async def file_score_breakdown(
"metric": _metric_to_dict(metric, _primary_and_magnitude(findings)) if metric else None,
"breakdown": breakdown,
"findings": finding_dicts,
+ "gated": gated,
"suggestions": {b: _suggestion_for(b) for b in {f.biomarker_type for f in findings}},
"trend": _file_trend_to_dict(file_trend(snapshots, file_path)),
"signals": _file_signals_to_dict(await _load_file_signals(session, repo_id, file_path)),
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 5f604d0aa..767431348 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
@@ -17,6 +17,7 @@ from repowise.server.schemas import (
HealthFindingWithSymbolResponse,
)
+from .._unverified import UnverifiedQuery
from ._router import router
from .counts import CountsQuery
from .loaders import _attach_symbol_ids
@@ -51,6 +52,7 @@ async def list_health_findings(
limit: int = Query(100, ge=1, le=1000),
scope: str = ScopeQuery,
counts: str = CountsQuery,
+ include_unverified: bool = UnverifiedQuery,
session: AsyncSession = Depends(get_db_session),
) -> list[dict]:
"""Findings worth doing first, then lower-priority ones labelled with why
@@ -93,6 +95,7 @@ async def list_health_findings(
exclude_dimensions=(
tuple(sorted(ZERO_IMPACT_DIMENSIONS)) if ranks_everything else None
),
+ include_unverified=include_unverified,
)
# 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:
diff --git a/packages/server/src/repowise/server/routers/code_health/overview_routes.py b/packages/server/src/repowise/server/routers/code_health/overview_routes.py
index 44d064b28..4a75cd267 100644
--- a/packages/server/src/repowise/server/routers/code_health/overview_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/overview_routes.py
@@ -7,6 +7,7 @@ from datetime import datetime
from fastapi import Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.finding_registry import split_gated
from repowise.core.analysis.health.aggregation import (
biomarker_breakdown,
module_rollups,
@@ -22,6 +23,7 @@ from repowise.core.persistence.crud.analysis.queue_counts import all_unit_counts
from repowise.server.deps import get_db_session
from repowise.server.mcp_server._meta import resolve_indexed_commit
+from .._unverified import UnverifiedQuery
from ._router import router
from .counts import CountsQuery, project
from .loaders import _attach_symbol_ids
@@ -54,9 +56,15 @@ async def health_overview(
limit: int = Query(20, ge=1, le=200),
scope: str = ScopeQuery,
counts: str = CountsQuery,
+ include_unverified: bool = UnverifiedQuery,
session: AsyncSession = Depends(get_db_session),
) -> dict:
- """KPIs + lowest-scoring files + per-module rollup + meta."""
+ """KPIs + lowest-scoring files + per-module rollup + meta.
+
+ Findings on a language the registry gates for health findings still rank
+ the files (the scores count them) and feed the defect-accuracy check, but
+ are not listed or counted; ``summary.gated`` says how many were held back.
+ """
repo = await crud.get_repository(session, repo_id)
if repo is None:
raise HTTPException(status_code=404, detail="Repository not found")
@@ -66,12 +74,15 @@ async def health_overview(
# worst-first ranking, and the findings read is the most expensive of the
# two — so the route was paying for each of them twice per request.
metrics = await crud.get_health_metrics(session, repo_id)
- findings = await crud.get_health_findings(session, repo_id)
+ findings = await crud.get_health_findings(session, repo_id, include_unverified=True)
metrics, findings = narrow(scope, metrics, findings)
# Every figure below is computed from these two lists, so projecting here
# is what keeps the headline, the distribution, the hotspot figure and the
# work the page lists all describing the same thing.
- metrics, findings, unscored = project(counts, metrics, findings)
+ metrics, scored_findings, unscored = project(counts, metrics, findings)
+ findings, gated = split_gated(
+ "health", scored_findings, kind="biomarker_type", include_unverified=include_unverified
+ )
summary = await crud.get_health_summary(
session, repo_id, metrics=metrics, findings=findings
)
@@ -103,6 +114,7 @@ async def health_overview(
"counts": counts,
"unscored_files": unscored,
"band": band_for(float(avg)) if avg is not None else None,
+ "gated": gated,
}
distribution = health_distribution(metric_dicts)
@@ -118,10 +130,10 @@ async def health_overview(
# ranking needs each file's whole depth, or the floor-tied band comes out in
# a different order than the worst-files list beside it. Folded once and
# shared with the module rollup.
- deductions = deduction_by_path(findings)
+ deductions = deduction_by_path(scored_findings)
defect_accuracy = compute_defect_accuracy(
metric_dicts,
- [_finding_to_dict(f) for f in findings if f.biomarker_type == "prior_defect"],
+ [_finding_to_dict(f) for f in scored_findings if f.biomarker_type == "prior_defect"],
deductions=deductions,
)
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 1e4c75e5c..2e38ffc6d 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
@@ -17,17 +17,22 @@ 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
+from .._unverified import UnverifiedQuery
from ._router import router
-def _service(session: AsyncSession, repo_id: str) -> PerformanceHealthService:
+def _service(
+ session: AsyncSession, repo_id: str, *, include_unverified: bool = False
+) -> PerformanceHealthService:
"""Bind the shared service to this repository.
The repository token only scopes the agent-address-space plan reference,
which this surface strips: a plan here is addressed by the row id its own
detail route resolves.
"""
- return PerformanceHealthService(session, repo_id, repo_id)
+ return PerformanceHealthService(
+ session, repo_id, repo_id, include_unverified=include_unverified
+ )
_EVIDENCE_PER_ITEM = 8
@@ -90,6 +95,7 @@ async def list_performance_opportunities(
),
limit: int = Query(20, ge=1, le=100),
offset: int = Query(0, ge=0),
+ include_unverified: bool = UnverifiedQuery,
session: AsyncSession = Depends(get_db_session),
) -> dict[str, Any]:
"""One bounded page over the materialized causal read model.
@@ -110,7 +116,7 @@ async def list_performance_opportunities(
limit=limit,
offset=offset,
)
- page = await _service(session, repo_id).page(
+ page = await _service(session, repo_id, include_unverified=include_unverified).page(
query, evidence_per_item=_EVIDENCE_PER_ITEM, with_facets=True, with_summary=True
)
return {
@@ -121,6 +127,7 @@ async def list_performance_opportunities(
"facets": page.facets,
"summary": page.summary,
"counts": page.counts,
+ "gated": page.gated,
**({"ignored_arguments": ignored} if ignored else {}),
}
diff --git a/packages/server/src/repowise/server/routers/dead_code.py b/packages/server/src/repowise/server/routers/dead_code.py
index 43ca4fcb7..bdf64b1ef 100644
--- a/packages/server/src/repowise/server/routers/dead_code.py
+++ b/packages/server/src/repowise/server/routers/dead_code.py
@@ -11,6 +11,7 @@ from repowise.core.analysis.dead_code.risk_factors import (
)
from repowise.core.persistence import crud
from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.routers._unverified import UnverifiedQuery
from repowise.server.schemas import (
DeadCodeAnalyzeResponse,
DeadCodeFindingResponse,
@@ -36,6 +37,7 @@ async def list_dead_code(
status: str = Query("open"),
safe_only: bool = Query(False),
limit: int = Query(100, ge=1, le=500),
+ include_unverified: bool = UnverifiedQuery,
session: AsyncSession = Depends(get_db_session),
) -> list[DeadCodeFindingResponse]:
"""List dead code findings for a repository."""
@@ -45,6 +47,7 @@ async def list_dead_code(
kind=kind,
min_confidence=min_confidence,
status=status,
+ include_unverified=include_unverified,
)
if safe_only:
findings = [
@@ -109,10 +112,13 @@ async def analyze_dead_code(
)
async def dead_code_summary(
repo_id: str,
+ include_unverified: bool = UnverifiedQuery,
session: AsyncSession = Depends(get_db_session),
) -> DeadCodeSummaryResponse:
"""Get aggregate dead code statistics for a repository."""
- summary = await crud.get_dead_code_summary(session, repo_id)
+ summary = await crud.get_dead_code_summary(
+ session, repo_id, include_unverified=include_unverified
+ )
analyzed_at = await dead_code_analyzed_at(session, repo_id)
return DeadCodeSummaryResponse(**summary, analyzed_at=analyzed_at)
diff --git a/packages/server/src/repowise/server/routers/files.py b/packages/server/src/repowise/server/routers/files.py
index ebba66e2a..2838d63ea 100644
--- a/packages/server/src/repowise/server/routers/files.py
+++ b/packages/server/src/repowise/server/routers/files.py
@@ -26,6 +26,7 @@ from repowise.core.analysis.health.trends import file_trend
from repowise.core.ids import is_external
from repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPES
from repowise.core.persistence import crud
+from repowise.core.persistence.crud.analysis.shown import ungated
from repowise.core.persistence.decision_graph import get_governing_decisions
from repowise.core.persistence.models import (
DeadCodeFinding,
@@ -461,6 +462,7 @@ async def file_detail(
DeadCodeFinding.file_path == file_path,
DeadCodeFinding.status == "open",
DeadCodeFinding.kind.not_in(excluded_types()),
+ ungated("dead_code", DeadCodeFinding.file_path, DeadCodeFinding.kind),
)
)
)
diff --git a/packages/server/src/repowise/server/routers/graph/neighborhoods.py b/packages/server/src/repowise/server/routers/graph/neighborhoods.py
index b7a07ecd1..eaddc06f5 100644
--- a/packages/server/src/repowise/server/routers/graph/neighborhoods.py
+++ b/packages/server/src/repowise/server/routers/graph/neighborhoods.py
@@ -7,6 +7,7 @@ from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.ingestion.models import TEMPORAL_EDGE_TYPES
+from repowise.core.persistence.crud.analysis.shown import ungated
from repowise.core.persistence.models import (
DeadCodeFinding,
GitMetadata,
@@ -205,6 +206,7 @@ async def dead_code_graph(
select(DeadCodeFinding).where(
DeadCodeFinding.repository_id == repo_id,
DeadCodeFinding.status == "open",
+ ungated("dead_code", DeadCodeFinding.file_path, DeadCodeFinding.kind),
DeadCodeFinding.kind == "unreachable_file",
)
)
diff --git a/packages/server/src/repowise/server/routers/overview.py b/packages/server/src/repowise/server/routers/overview.py
index 109c844dd..00f6082e0 100644
--- a/packages/server/src/repowise/server/routers/overview.py
+++ b/packages/server/src/repowise/server/routers/overview.py
@@ -26,6 +26,7 @@ from repowise.core.analysis.health.scoring import hotspot_health
from repowise.core.forges import read_remote_url, strip_credentials
from repowise.core.persistence import crud
from repowise.core.persistence.crud.analysis.queue_counts import unit_counts
+from repowise.core.persistence.crud.analysis.shown import ungated
from repowise.core.persistence.models import (
DeadCodeFinding,
GenerationJob,
@@ -225,6 +226,7 @@ async def overview_summary(
DeadCodeFinding.repository_id == repo_id,
DeadCodeFinding.kind == "unused_export",
DeadCodeFinding.status == "open",
+ ungated("dead_code", DeadCodeFinding.file_path, DeadCodeFinding.kind),
)
)
or 0
diff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.py
index 7dfc5eac4..bc3003ff8 100644
--- a/packages/server/src/repowise/server/routers/refactoring.py
+++ b/packages/server/src/repowise/server/routers/refactoring.py
@@ -31,9 +31,10 @@ from repowise.core.analysis.health.refactoring.serving import (
parse_query,
)
from repowise.core.persistence import crud
-from repowise.core.persistence.crud.analysis.refactoring import ALLOWED_STATUSES
+from repowise.core.persistence.crud.analysis.refactoring import ALLOWED_STATUSES, gated_plan_counts
from repowise.server.deps import get_db_session, verify_api_key
from repowise.server.routers._local_git import local_repo_path
+from repowise.server.routers._unverified import UnverifiedQuery
from repowise.server.schemas import (
GenerateCodeRequest,
GenerateCodeResponse,
@@ -85,6 +86,7 @@ async def get_refactoring_targets(
view: Literal["canonical", "file_spread"] = Query(
"canonical", description="Named ordering view; canonical is the product default"
),
+ include_unverified: bool = UnverifiedQuery,
session: AsyncSession = Depends(get_db_session),
) -> RefactoringTargetsResponse:
"""Ranked refactoring plans for the repo, filterable by type, confidence,
@@ -95,7 +97,7 @@ async def get_refactoring_targets(
honor *min_confidence* — so the summary and the plan list stay consistent
under a confidence filter.
"""
- body = await _service(session, repo_id).ranked_plans(
+ body = await _service(session, repo_id, include_unverified=include_unverified).ranked_plans(
PlanListQuery(
refactoring_type=refactoring_type,
min_confidence=min_confidence,
@@ -103,7 +105,10 @@ async def get_refactoring_targets(
view=view,
)
)
- return RefactoringTargetsResponse(**body)
+ return RefactoringTargetsResponse(
+ **body,
+ gated=await gated_plan_counts(session, repo_id, include_unverified=include_unverified),
+ )
# ---------------------------------------------------------------------------
@@ -113,8 +118,12 @@ async def get_refactoring_targets(
# ---------------------------------------------------------------------------
-def _service(session: AsyncSession, repo_id: str) -> RefactoringHealthService:
- return RefactoringHealthService(session, repo_id, repo_id)
+def _service(
+ session: AsyncSession, repo_id: str, *, include_unverified: bool = False
+) -> RefactoringHealthService:
+ return RefactoringHealthService(
+ session, repo_id, repo_id, include_unverified=include_unverified
+ )
@router.get(
@@ -154,6 +163,7 @@ async def get_refactoring_opportunities(
),
limit: int = Query(20, ge=1, le=100),
offset: int = Query(0, ge=0),
+ include_unverified: bool = UnverifiedQuery,
session: AsyncSession = Depends(get_db_session),
) -> dict[str, Any]:
"""One page of composed opportunities, with facets and the rollup.
@@ -177,7 +187,7 @@ async def get_refactoring_opportunities(
offset=offset,
scope=scope,
)
- page = await _service(session, repo_id).page(
+ page = await _service(session, repo_id, include_unverified=include_unverified).page(
query,
steps_per_item=step_preview if step_preview > 0 else None,
with_facets=True,
@@ -193,6 +203,7 @@ async def get_refactoring_opportunities(
"summary": page.summary,
"scope": page.scope,
"counts": page.counts,
+ "gated": page.gated,
}
# ``hidden`` restates ``counts.excluded`` for the board; remove once the
# web reads ``counts`` (UI adoption).
@@ -206,10 +217,11 @@ async def get_refactoring_opportunities(
@router.get("/{repo_id}/refactoring/summary", response_model=RefactoringRollupResponse)
async def get_refactoring_rollup(
repo_id: str,
+ include_unverified: bool = UnverifiedQuery,
session: AsyncSession = Depends(get_db_session),
) -> dict[str, Any]:
"""The repository rollup and its one lead, by primary key."""
- service = _service(session, repo_id)
+ service = _service(session, repo_id, include_unverified=include_unverified)
return {"summary": await service.summary(), "directive": await service.directive()}
diff --git a/packages/server/src/repowise/server/routers/repos.py b/packages/server/src/repowise/server/routers/repos.py
index 86f9fda18..6344ce14d 100644
--- a/packages/server/src/repowise/server/routers/repos.py
+++ b/packages/server/src/repowise/server/routers/repos.py
@@ -15,6 +15,7 @@ from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.persistence import crud
+from repowise.core.persistence.crud.analysis.shown import ungated
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import (
DeadCodeFinding,
@@ -416,6 +417,7 @@ async def get_repo_stats(
DeadCodeFinding.repository_id == repo_id,
DeadCodeFinding.kind == "unused_export",
DeadCodeFinding.status == "open",
+ ungated("dead_code", DeadCodeFinding.file_path, DeadCodeFinding.kind),
),
0,
)
diff --git a/packages/server/src/repowise/server/schemas/code_quality.py b/packages/server/src/repowise/server/schemas/code_quality.py
index 8171bb2fa..f246420db 100644
--- a/packages/server/src/repowise/server/schemas/code_quality.py
+++ b/packages/server/src/repowise/server/schemas/code_quality.py
@@ -101,6 +101,8 @@ class DeadCodeSummaryResponse(BaseModel):
by_kind: dict
# When dead-code analysis last ran; None = never ran or unknown (not all-clear).
analyzed_at: datetime | None = None
+ #: Open findings a language gate held back, ``{language: {count, reason}}``.
+ gated: dict = {}
class SecurityFindingResponse(BaseModel):
diff --git a/packages/server/src/repowise/server/schemas/refactoring.py b/packages/server/src/repowise/server/schemas/refactoring.py
index 797531be8..3e053ff31 100644
--- a/packages/server/src/repowise/server/schemas/refactoring.py
+++ b/packages/server/src/repowise/server/schemas/refactoring.py
@@ -45,6 +45,8 @@ class RefactoringOpportunitiesResponse(BaseModel):
hidden: RefactoringHiddenCounts | None = None
#: The plans' count vocabulary over the open inventory (``queue.counts``).
counts: QueueCounts | None = None
+ #: Open opportunities a language gate held back, by language.
+ gated: dict[str, dict[str, Any]] | None = None
class RefactoringRollupResponse(BaseModel):
@@ -218,6 +220,8 @@ class RefactoringSummary(BaseModel):
class RefactoringTargetsResponse(BaseModel):
summary: RefactoringSummary
plans: list[RefactoringPlanResponse]
+ #: Open plans a language gate held back, by language.
+ gated: dict[str, dict[str, Any]] = {}
class RefactoringSettings(BaseModel):
diff --git a/packages/server/src/repowise/server/services/attention.py b/packages/server/src/repowise/server/services/attention.py
index 1429dff14..037491752 100644
--- a/packages/server/src/repowise/server/services/attention.py
+++ b/packages/server/src/repowise/server/services/attention.py
@@ -27,6 +27,7 @@ from repowise.core.analysis.dead_code.risk_factors import REVIEW_ONLY_KINDS
from repowise.core.analysis.finding_registry import excluded_types
from repowise.core.analysis.health.scoring import HISTORY_CATEGORY, biomarker_category
from repowise.core.persistence.crud.analysis.refactoring import shown_plan_predicate
+from repowise.core.persistence.crud.analysis.shown import ungated
from repowise.core.persistence.models import (
DeadCodeFinding,
DocDriftFinding,
@@ -83,6 +84,7 @@ 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),
)
rows = (
await session.execute(
diff --git a/packages/server/src/repowise/server/services/c4_builder/__init__.py b/packages/server/src/repowise/server/services/c4_builder/__init__.py
index b0feae31f..4803b9b01 100644
--- a/packages/server/src/repowise/server/services/c4_builder/__init__.py
+++ b/packages/server/src/repowise/server/services/c4_builder/__init__.py
@@ -36,6 +36,7 @@ from repowise.core.persistence.crud import (
get_kg_project_meta,
get_kg_tour_steps,
)
+from repowise.core.persistence.crud.analysis.shown import ungated
from repowise.core.persistence.models import DeadCodeFinding, GitMetadata
from repowise.core.support_paths import is_support_path
from repowise.core.test_paths import is_test_related_path
@@ -432,6 +433,7 @@ async def _per_file_signals(session: AsyncSession, repo_id: str) -> dict[str, di
select(DeadCodeFinding.file_path).where(
DeadCodeFinding.repository_id == repo_id,
DeadCodeFinding.status == "open",
+ ungated("dead_code", DeadCodeFinding.file_path, DeadCodeFinding.kind),
DeadCodeFinding.kind == "unreachable_file",
)
)
@@ -549,6 +551,7 @@ async def _annotate_container_signals(
select(DeadCodeFinding.file_path).where(
DeadCodeFinding.repository_id == repo_id,
DeadCodeFinding.status == "open",
+ ungated("dead_code", DeadCodeFinding.file_path, DeadCodeFinding.kind),
DeadCodeFinding.kind == "unreachable_file",
)
)
diff --git a/packages/server/src/repowise/server/services/c4_builder/architecture.py b/packages/server/src/repowise/server/services/c4_builder/architecture.py
index 4b37454ec..894c61393 100644
--- a/packages/server/src/repowise/server/services/c4_builder/architecture.py
+++ b/packages/server/src/repowise/server/services/c4_builder/architecture.py
@@ -29,6 +29,7 @@ from repowise.core.persistence.crud import (
upsert_kg_project_meta,
upsert_kg_tour_steps,
)
+from repowise.core.persistence.crud.analysis.shown import ungated
from repowise.core.persistence.models import DeadCodeFinding, GitMetadata, Page
from .models import (
@@ -483,6 +484,7 @@ async def build_architecture_view(
select(DeadCodeFinding.file_path).where(
DeadCodeFinding.repository_id == repo_id,
DeadCodeFinding.status == "open",
+ ungated("dead_code", DeadCodeFinding.file_path, DeadCodeFinding.kind),
DeadCodeFinding.kind == "unreachable_file",
)
)
diff --git a/packages/server/src/repowise/server/services/module_health.py b/packages/server/src/repowise/server/services/module_health.py
index 55a6cf543..139feb489 100644
--- a/packages/server/src/repowise/server/services/module_health.py
+++ b/packages/server/src/repowise/server/services/module_health.py
@@ -26,6 +26,7 @@ from repowise.core.analysis.module_health import (
summarize,
)
from repowise.core.persistence.crud import code_file_rows
+from repowise.core.persistence.crud.analysis.shown import ungated
from repowise.core.persistence.models import (
DeadCodeFinding,
DecisionRecord,
@@ -59,6 +60,7 @@ async def aggregate_modules(session: AsyncSession, repo_id: str) -> dict[str, Mo
select(DeadCodeFinding.file_path, DeadCodeFinding.lines).where(
DeadCodeFinding.repository_id == repo_id,
DeadCodeFinding.kind.not_in(excluded_types()),
+ ungated("dead_code", DeadCodeFinding.file_path, DeadCodeFinding.kind),
)
)
).all()
@@ -144,6 +146,7 @@ async def build_single_file_health(
DeadCodeFinding.repository_id == repo_id,
DeadCodeFinding.file_path == file_path,
DeadCodeFinding.kind.not_in(excluded_types()),
+ ungated("dead_code", DeadCodeFinding.file_path, DeadCodeFinding.kind),
)
)
).one()
diff --git a/packages/server/src/repowise/server/services/node_signals.py b/packages/server/src/repowise/server/services/node_signals.py
index 4e156669d..f9f6177e2 100644
--- a/packages/server/src/repowise/server/services/node_signals.py
+++ b/packages/server/src/repowise/server/services/node_signals.py
@@ -17,6 +17,7 @@ from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.decisions.scope import SCOPE_BASIS_FOOTPRINT
+from repowise.core.persistence.crud.analysis.shown import ungated
from repowise.core.persistence.models import (
DeadCodeFinding,
DecisionRecord,
@@ -87,6 +88,7 @@ async def collect_node_signals(
dead_q = select(DeadCodeFinding).where(
DeadCodeFinding.repository_id == repo_id,
DeadCodeFinding.status == "open",
+ ungated("dead_code", DeadCodeFinding.file_path, DeadCodeFinding.kind),
DeadCodeFinding.kind == "unreachable_file",
)
if node_ids is not None:
diff --git a/packages/server/src/repowise/server/services/owner_profile.py b/packages/server/src/repowise/server/services/owner_profile.py
index 940e2701e..9f3f4cbdb 100644
--- a/packages/server/src/repowise/server/services/owner_profile.py
+++ b/packages/server/src/repowise/server/services/owner_profile.py
@@ -19,6 +19,7 @@ from repowise.core.analysis.owners import (
silo_modules,
)
from repowise.core.persistence.crud import code_file_rows
+from repowise.core.persistence.crud.analysis.shown import ungated
from repowise.core.persistence.models import (
DeadCodeFinding,
GitCommit,
@@ -51,6 +52,7 @@ async def aggregate_owners(
).where(
DeadCodeFinding.repository_id == repo_id,
DeadCodeFinding.kind.not_in(excluded_types()),
+ ungated("dead_code", DeadCodeFinding.file_path, DeadCodeFinding.kind),
)
)
).all()
diff --git a/packages/server/src/repowise/server/services/performance_health.py b/packages/server/src/repowise/server/services/performance_health.py
index 5861396a3..2094232ec 100644
--- a/packages/server/src/repowise/server/services/performance_health.py
+++ b/packages/server/src/repowise/server/services/performance_health.py
@@ -36,6 +36,7 @@ from repowise.core.analysis.health.perf.serving import (
)
from repowise.core.analysis.health.refactoring.serving import evidence_block
from repowise.core.persistence.crud import (
+ gated_performance_counts,
get_performance_opportunity,
get_performance_plan_rows,
get_performance_summary,
@@ -60,15 +61,29 @@ class PerformancePage:
ignored_arguments: dict[str, str] = field(default_factory=dict)
#: The causes' count vocabulary (``queue.counts``) in the query's files.
counts: dict[str, Any] = field(default_factory=dict)
+ #: Open opportunities a language gate held back, ``{language: {count, ...}}``.
+ gated: dict[str, dict] = field(default_factory=dict)
class PerformanceHealthService:
- """Query, page, detail, facets, plan linkage, and recovery, in one place."""
+ """Query, page, detail, facets, plan linkage, and recovery, in one place.
- def __init__(self, session: AsyncSession, repository_id: str, repository: str) -> None:
+ Lists, counts, facets and the headline leave out what a language gate holds
+ back unless ``include_unverified``; a lookup by id never does.
+ """
+
+ def __init__(
+ self,
+ session: AsyncSession,
+ repository_id: str,
+ repository: str,
+ *,
+ include_unverified: bool = False,
+ ) -> None:
self._session = session
self._repository_id = repository_id
self._repository = repository
+ self._include_unverified = include_unverified
# -- collection --------------------------------------------------------
@@ -103,6 +118,7 @@ class PerformanceHealthService:
sort=query.sort,
limit=query.limit,
offset=query.offset,
+ include_unverified=self._include_unverified,
)
links = await self._plan_links(rows)
evidence = await self._evidence_for(rows, evidence_per_item)
@@ -136,6 +152,7 @@ class PerformanceHealthService:
file_paths=query.file_paths,
)
).as_dict(),
+ gated=await self.gated(),
)
async def _evidence_for(
@@ -171,7 +188,10 @@ class PerformanceHealthService:
async def _facets(self, query: PerformanceQuery) -> dict[str, list[dict[str, Any]]]:
"""Counts per filter value, each cross-filtered by the *other* filters."""
grouped = await performance_facet_counts(
- self._session, self._repository_id, file_paths=query.file_paths
+ self._session,
+ self._repository_id,
+ file_paths=query.file_paths,
+ include_unverified=self._include_unverified,
)
return fold_facets(grouped, query)
@@ -194,10 +214,23 @@ class PerformanceHealthService:
if base["status"] == "unavailable":
return base
base["repository_total"] = base["total"]
- if contexts is None:
+ gated = await self.gated()
+ if contexts is None and not gated:
return base
- grouped = await performance_facet_counts(self._session, self._repository_id)
- return rescope_summary(base, grouped, contexts)
+ # The stored rollup counts gated rows too, so with any held back the
+ # headline is recounted from the same gated facet aggregate.
+ grouped = await performance_facet_counts(
+ self._session, self._repository_id, include_unverified=self._include_unverified
+ )
+ if contexts is None:
+ contexts = frozenset(group[0] for group in grouped)
+ return {**rescope_summary(base, grouped, contexts), "gated": gated}
+
+ async def gated(self) -> dict[str, dict]:
+ """Open opportunities a language gate holds back; empty when opted in."""
+ return await gated_performance_counts(
+ self._session, self._repository_id, include_unverified=self._include_unverified
+ )
# -- detail ------------------------------------------------------------
diff --git a/packages/server/src/repowise/server/services/refactoring_health.py b/packages/server/src/repowise/server/services/refactoring_health.py
index 931b9aec1..a90f210c5 100644
--- a/packages/server/src/repowise/server/services/refactoring_health.py
+++ b/packages/server/src/repowise/server/services/refactoring_health.py
@@ -53,6 +53,7 @@ from repowise.core.persistence.crud.analysis.refactoring import (
summarize_open_plans,
)
from repowise.core.persistence.crud.analysis.refactoring_opportunities import (
+ gated_opportunity_counts,
get_refactoring_opportunity,
get_refactoring_summary,
list_refactoring_opportunities,
@@ -91,6 +92,8 @@ class RefactoringPage:
hidden: dict[str, Any] | None = None
#: The plans' count vocabulary (``queue.counts``) in the query's files.
counts: dict[str, Any] = field(default_factory=dict)
+ #: Open opportunities a language gate held back, ``{language: {count, ...}}``.
+ gated: dict[str, dict] = field(default_factory=dict)
@dataclass(frozen=True, slots=True)
@@ -106,6 +109,8 @@ class RefactoringPlanPage:
scope: str = "all"
hidden: dict[str, Any] | None = None
counts: dict[str, Any] = field(default_factory=dict)
+ #: Open opportunities a language gate held back, ``{language: {count, ...}}``.
+ gated: dict[str, dict] = field(default_factory=dict)
def _filters(query: RefactoringQuery) -> dict[str, Any]:
@@ -161,12 +166,28 @@ class PlanListQuery:
class RefactoringHealthService:
- """Query, page, detail and headline over the materialized opportunities."""
+ """Query, page, detail and headline over the materialized opportunities.
- def __init__(self, session: AsyncSession, repository_id: str, repository: str) -> None:
+ Lists, counts, facets and the lead leave out what a language gate holds
+ back unless ``include_unverified``; a lookup by id never does.
+ """
+
+ def __init__(
+ self,
+ session: AsyncSession,
+ repository_id: str,
+ repository: str,
+ *,
+ include_unverified: bool = False,
+ ) -> None:
self._session = session
self._repository_id = repository_id
self._repository = repository
+ self._include_unverified = include_unverified
+
+ def _filters(self, query: RefactoringQuery) -> dict[str, Any]:
+ """The store's filter arguments for *query*, under this service's gate."""
+ return {**_filters(query), "include_unverified": self._include_unverified}
# -- queue ------------------------------------------------------------
@@ -192,7 +213,7 @@ class RefactoringHealthService:
write) says which opportunities it takes, and one id-only read of the
filtered set counts what it leaves out, by reason.
"""
- filters, hidden = await self._scope(query, _filters(query))
+ filters, hidden = await self._scope(query, self._filters(query))
rows, total = await list_refactoring_opportunities(
self._session,
self._repository_id,
@@ -222,6 +243,7 @@ class RefactoringHealthService:
scope=query.scope,
hidden=hidden,
counts=await self._counts(query, len(items)),
+ gated=await self.gated(),
)
async def plan_page(self, query: RefactoringQuery) -> RefactoringPlanPage:
@@ -234,7 +256,7 @@ class RefactoringHealthService:
so a page that folds some reads on until it holds ``limit`` rows;
offsets and the total still count every plan.
"""
- filters, hidden = await self._scope(query, _filters(query))
+ filters, hidden = await self._scope(query, self._filters(query))
counts = await refactoring_step_counts(
self._session,
self._repository_id,
@@ -271,6 +293,7 @@ class RefactoringHealthService:
scope=query.scope,
hidden=hidden,
counts=await self._counts(query, len(touched)),
+ gated=await self.gated(),
)
async def _scope(
@@ -318,8 +341,20 @@ class RefactoringHealthService:
# -- headline ---------------------------------------------------------
async def summary(self) -> dict[str, Any]:
- """The Level-1 rollup, read by primary key."""
- return summary_payload(await get_refactoring_summary(self._session, self._repository_id))
+ """The Level-1 rollup, read by primary key, plus what the gates hold back."""
+ payload = summary_payload(
+ await get_refactoring_summary(self._session, self._repository_id),
+ include_unverified=self._include_unverified,
+ )
+ if payload.get("status") == "available":
+ payload["gated"] = await self.gated()
+ return payload
+
+ async def gated(self) -> dict[str, dict]:
+ """Open opportunities a language gate holds back; empty when opted in."""
+ return await gated_opportunity_counts(
+ self._session, self._repository_id, include_unverified=self._include_unverified
+ )
async def directive(self) -> dict[str, Any]:
"""The Level-0 lead: one opportunity, and the exact call that opens it.
@@ -328,7 +363,8 @@ class RefactoringHealthService:
statement for it and never touches the queue.
"""
return directive_from_summary(
- await get_refactoring_summary(self._session, self._repository_id)
+ await get_refactoring_summary(self._session, self._repository_id),
+ include_unverified=self._include_unverified,
)
# -- detail -----------------------------------------------------------
@@ -448,15 +484,22 @@ class RefactoringHealthService:
min_confidence=query.min_confidence,
filters=query.filters(),
view=query.view,
+ include_unverified=self._include_unverified,
)
if stored is not None:
chips = await summarize_open_plans(
- self._session, self._repository_id, min_confidence=query.min_confidence
+ self._session,
+ self._repository_id,
+ min_confidence=query.min_confidence,
+ include_unverified=self._include_unverified,
)
plans = [stored_recommendation(row).as_dict() for row in stored]
else:
rows = await get_refactoring_suggestions(
- self._session, self._repository_id, min_confidence=query.min_confidence
+ self._session,
+ self._repository_id,
+ min_confidence=query.min_confidence,
+ include_unverified=self._include_unverified,
)
chips = summarize_plans(rows)
kept = [row for row in rows if keep(PLAN_FILTERS, row, query.filters())]
diff --git a/packages/types/src/dead-code.ts b/packages/types/src/dead-code.ts
index 2dfba3beb..dc9f5049d 100644
--- a/packages/types/src/dead-code.ts
+++ b/packages/types/src/dead-code.ts
@@ -8,6 +8,8 @@
* first segment of `file_path`.
*/
+import type { GatedByLanguage } from "./health.js";
+
export type DeadCodeStatus = "open" | "acknowledged" | "resolved" | "false_positive";
/**
@@ -124,4 +126,6 @@ export interface DeadCodeSummary {
* report it, and a zero then reads as clean.
*/
analyzed_at?: string | null;
+ /** What a language gate held back, by language. Empty or absent when nothing was. */
+ gated?: GatedByLanguage;
}
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 0a0b0c663..f51133868 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -914,6 +914,7 @@ export interface DeadCodeSummaryResponse {
total_lines: number;
by_kind: Record<string, unknown>;
analyzed_at?: string | null;
+ gated?: Record<string, unknown>;
}
/** A link from a decision to a governed file or module. */
@@ -2747,6 +2748,7 @@ export interface RefactoringOpportunitiesResponse {
scope?: "fix_first" | "all";
hidden?: RefactoringHiddenCounts | null;
counts?: QueueCounts | null;
+ gated?: Record<string, Record<string, unknown>> | null;
}
/**
@@ -2902,6 +2904,7 @@ export interface RefactoringSummary {
export interface RefactoringTargetsResponse {
summary: RefactoringSummary;
plans: RefactoringPlanResponse[];
+ gated?: Record<string, Record<string, unknown>>;
}
export interface RefactoringTypeCount {
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index a7a6f9a37..306b2404b 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -658,6 +658,14 @@ export interface PerformanceDefaultQueue {
excluded: Partial<Record<PerformanceQueueExclusion, number>>;
}
+/**
+ * A layer held back pending verification on a language is left out on files
+ * of that language unless the caller opts in (`include_unverified`). Keyed by
+ * language tag (`java`, `csharp`, `c`, `cpp`, `kotlin`, `swift`); `reason`
+ * is the sentence to show.
+ */
+export type GatedByLanguage = Record<string, { count: number; reason: string }>;
+
export interface PerformanceOpportunitySummary {
/** `current` once materialized, `stale_model` after a model bump, or
* `unavailable` when this index has not been analyzed yet. */
@@ -684,11 +692,15 @@ export interface PerformanceOpportunitySummary {
/** Why the queue is not current, when it is not. */
reason?: string;
detail?: string;
+ /** What a language gate held back, by language. Empty or absent when nothing was. */
+ gated?: GatedByLanguage;
}
export interface PerformanceOpportunityPage extends Paginated<PerformanceOpportunity> {
summary: PerformanceOpportunitySummary;
facets: PerformanceFacets;
+ /** What a language gate held back, by language. Empty or absent when nothing was. */
+ gated?: GatedByLanguage;
/** Filter values the server did not recognize, named rather than dropped. */
ignored_arguments?: Record<string, string>;
/** The causes' count vocabulary over the open inventory in the queried files. */
@@ -777,6 +789,8 @@ export interface HealthOverviewSummary {
counts?: HealthCounts;
/** Files a code-shape reading cannot answer for, having no recorded split. */
unscored_files?: number;
+ /** What a language gate held back, by language. Empty or absent when nothing was. */
+ gated?: GatedByLanguage;
}
export interface HealthOverviewResponse {
@@ -949,6 +963,8 @@ export interface FileBreakdownCategory {
export interface HealthFileBreakdownResponse {
file_path: string;
+ /** What a language gate held back, by language. Empty or absent when nothing was. */
+ gated?: GatedByLanguage;
metric: HealthFileMetric | null;
/** `null` for a file with no score (no health dialect for its language). */
breakdown: {
diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.ts
index 7e65fc1b0..97170053f 100644
--- a/packages/types/src/refactoring.ts
+++ b/packages/types/src/refactoring.ts
@@ -2,6 +2,7 @@
import type { ActionCommand } from "./actions.js";
import type { FixExclusion } from "./fix-first.js";
+import type { GatedByLanguage } from "./health.js";
import type { QueueCounts } from "./queue.js";
export type RefactoringType =
@@ -332,6 +333,8 @@ export interface RefactoringSummary {
export interface RefactoringTargets {
summary: RefactoringSummary;
plans: RefactoringPlan[];
+ /** What a language gate held back, by language. Empty or absent when nothing was. */
+ gated?: GatedByLanguage;
}
export interface GeneratedSpan {
@@ -599,8 +602,11 @@ export interface RefactoringRollupAvailable {
by_confidence: Record<string, number>;
by_status: Record<string, number>;
addresses_primary_problem: { yes: number; no: number; unknown: number };
- /** The same lead the directive reads; null when nothing is open. */
+ /** The same lead the directive reads; null when nothing is open, or when
+ * it is on a gated language. */
lead: RefactoringDirectiveLead | null;
+ /** What a language gate held back, by language. Empty or absent when nothing was. */
+ gated?: GatedByLanguage;
refactoring_model_version: number;
analyzed_commit: string | null;
/** Present on the MCP block only. */
@@ -635,7 +641,10 @@ export type RefactoringDirective =
| RefactoringDirectiveAvailable
| {
status: "clear";
- reason: "no_open_opportunities" | "only_test_file_opportunities";
+ reason:
+ | "no_open_opportunities"
+ | "only_test_file_opportunities"
+ | "lead_in_gated_language";
detail: string;
opportunities_total: number;
}
@@ -676,6 +685,8 @@ export interface RefactoringOpportunityPage {
hidden?: RefactoringHiddenCounts;
/** The plans' count vocabulary over the open inventory in the queried files. */
counts?: QueueCounts;
+ /** What a language gate held back, by language. Empty or absent when nothing was. */
+ gated?: GatedByLanguage;
}
/** ``GET /api/repos/{repo_id}/refactoring/summary``. */
diff --git a/tests/unit/health/test_language_gates_core.py b/tests/unit/health/test_language_gates_core.py
new file mode 100644
index 000000000..c1b998cbc
--- /dev/null
+++ b/tests/unit/health/test_language_gates_core.py
@@ -0,0 +1,47 @@
+"""Core surfaces built from rows in memory honour the layer x language gates."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+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
+
+
+def _dead(path: str) -> dict:
+ return {"id": path, "kind": "unused_export", "file_path": path, "symbol_name": "old",
+ "lines": 5, "safe_to_delete": True, "status": "open"}
+
+
+def test_actions_never_offer_a_gated_deletion():
+ rows = [_dead(p) for p in ("src/a.py", "src/A.cs", "src/a.cpp", "app/A.kt", "App/A.swift")]
+ dead = build_dead(rows, {})
+ assert [d.file_path for d in dead["dead"]] == ["src/a.py"]
+
+
+def test_wiki_prompts_never_carry_gated_dead_code():
+ finding = SimpleNamespace(
+ kind="unreachable_file", reason="no imports", confidence=0.9, safe_to_delete=True,
+ symbol_name=None, symbol_kind=None,
+ )
+ report = SimpleNamespace(
+ findings=[
+ SimpleNamespace(**vars(finding), file_path="src/Form.cs"),
+ SimpleNamespace(**vars(finding), file_path="src/form.py"),
+ ]
+ )
+ assert set(build_dead_code_map(report)) == {"src/form.py"}
+
+
+def test_change_review_says_when_gated_findings_were_not_compared():
+ def finding(path: str) -> HealthFindingData:
+ return HealthFindingData("complex_method", Severity.HIGH, path, "f", 1, 9, {}, 1.0)
+
+ assert len(_limits([finding("src/a.py")])) == 1
+ note = _limits([finding("src/a.py"), finding("src/A.java"), finding("src/A.cs")])[-1]
+ assert "C#, Java files" in note and "pending verification" in note
+ assert "precision" not in note
+ # Kotlin is gated for dead code only, so its health findings are compared.
+ assert len(_limits([finding("app/A.kt")])) == 1
diff --git a/tests/unit/persistence/test_actions_build.py b/tests/unit/persistence/test_actions_build.py
index 0bfa5d0f1..01006f783 100644
--- a/tests/unit/persistence/test_actions_build.py
+++ b/tests/unit/persistence/test_actions_build.py
@@ -236,6 +236,7 @@ def test_only_a_recent_authored_code_shape_regression_is_a_candidate() -> None:
"a test file": {"file_path": "tests/test_a.py"},
"a history marker": {"biomarker_type": "change_entropy"},
"a hidden marker": {"biomarker_type": "dry_violation"},
+ "a gated language": {"file_path": "src/A.java"},
}
files = {"tests/test_a.py": SimpleNamespace(is_test=True)}
diff --git a/tests/unit/server/mcp/test_language_gates.py b/tests/unit/server/mcp/test_language_gates.py
new file mode 100644
index 000000000..29b22f031
--- /dev/null
+++ b/tests/unit/server/mcp/test_language_gates.py
@@ -0,0 +1,279 @@
+"""Layer x language gates: a layer measured below the precision bar on a
+language is held back on that language's files, everywhere, unless the caller
+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.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+
+import pytest
+
+from repowise.core.analysis import finding_registry
+from repowise.core.analysis.finding_registry import (
+ LANGUAGE_GATES,
+ LanguageGate,
+ gate_for,
+ gated_extensions,
+ language_of,
+ split_gated,
+)
+from repowise.core.persistence.models import DeadCodeFinding
+
+
+def test_audited_languages_are_gated_on_every_layer():
+ for layer in ("health", "refactoring", "performance", "dead_code"):
+ 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 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)
+
+
+def test_kotlin_and_swift_are_gated_for_dead_code_only():
+ for path in ("app/Main.kt", "build.gradle.kts", "App/ContentView.swift"):
+ assert gate_for("dead_code", path) is not None, path
+ for layer in ("health", "refactoring", "performance"):
+ assert gate_for(layer, path) is None, (layer, path)
+
+
+def test_every_gate_names_a_language_with_extensions_and_a_cause():
+ for gate in LANGUAGE_GATES:
+ assert gated_extensions(gate.language), gate.language
+ assert gate.cause and gate.corpus and gate.measured_on
+ assert gate.precision is None or 0.0 <= gate.precision < 0.9
+ assert language_of("x/Y.JAVA") == "java"
+
+
+def test_served_reason_says_pending_verification_not_a_measurement():
+ rows = [{"file_path": p, "kind": "unused_export"} for p in ("A.cs", "B.kt", "C.swift")]
+ _, gated = split_gated("dead_code", rows, kind="kind", get=lambda r, k: r[k])
+ assert set(gated) == {"csharp", "kotlin", "swift"}
+ assert gated["csharp"] == {
+ "count": 1,
+ "reason": "Held back on C# files pending verification.",
+ }
+ for entry in gated.values():
+ assert "%" not in entry["reason"] and "precision" not in entry["reason"]
+
+
+def test_a_gate_can_name_kinds(monkeypatch):
+ monkeypatch.setattr(
+ finding_registry,
+ "LANGUAGE_GATES",
+ (
+ LanguageGate(
+ "dead_code", "csharp", 0.1, "test", "2026-10-02", "test",
+ kinds=frozenset({"unreachable_file"}),
+ ),
+ ),
+ )
+ assert gate_for("dead_code", "A.cs", "unreachable_file") is not None
+ assert gate_for("dead_code", "A.cs", "unused_export") is None
+ assert gate_for("health", "A.cs", "complex_method") is None
+
+
+def test_split_gated_counts_what_it_holds_back():
+ rows = [
+ {"file_path": "A.java", "kind": "unused_export"},
+ {"file_path": "B.java", "kind": "unused_export"},
+ {"file_path": "c.py", "kind": "unused_export"},
+ ]
+ shown, gated = split_gated("dead_code", rows, kind="kind", get=lambda r, k: r[k])
+ assert [r["file_path"] for r in shown] == ["c.py"]
+ assert gated["java"]["count"] == 2 and gated["java"]["reason"]
+
+
+# ---------------------------------------------------------------------------
+# Seeds
+# ---------------------------------------------------------------------------
+
+
+async def _seed_java_health(session, rid: str) -> None:
+ from repowise.core.persistence.crud import upsert_health_findings, upsert_health_metrics
+
+ gated = ["src/Billing.java"]
+ await upsert_health_metrics(
+ session,
+ rid,
+ [
+ {
+ "file_path": "src/Billing.java",
+ "score": 3.0,
+ "max_ccn": 30,
+ "max_nesting": 6,
+ "nloc": 400,
+ "has_test_file": False,
+ "module": "billing",
+ }
+ ],
+ )
+ await upsert_health_findings(
+ session,
+ rid,
+ [
+ {
+ "file_path": "src/Billing.java",
+ "biomarker_type": "complex_method",
+ "severity": "critical",
+ "function_name": "charge",
+ "line_start": 10,
+ "line_end": 200,
+ "details": {"ccn": 30},
+ "health_impact": 3.0,
+ "reason": "charge has cyclomatic complexity 30",
+ }
+ ],
+ file_paths=gated,
+ )
+ await session.commit()
+
+
+async def _seed_gated_dead_code(
+ session, rid: str, paths: tuple[str, ...] = ("src/Billing.java", "src/Ui/Form.cs")
+) -> None:
+ now = datetime.now(UTC)
+ for i, path in enumerate(paths):
+ session.add(
+ DeadCodeFinding(
+ id=f"gated{i}",
+ repository_id=rid,
+ kind="unreachable_file",
+ file_path=path,
+ confidence=0.9,
+ reason="No imports found",
+ lines=80,
+ safe_to_delete=True,
+ status="open",
+ analyzed_at=now,
+ )
+ )
+ await session.commit()
+
+
+# ---------------------------------------------------------------------------
+# Readers
+# ---------------------------------------------------------------------------
+
+
+async def test_crud_readers_hold_back_gated_rows(session, health_data):
+ from repowise.core.persistence.crud import (
+ 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)
+
+ paths = {f.file_path for f in await get_health_findings(session, health_data)}
+ assert "src/Billing.java" not in paths and "src/auth/service.py" in paths
+ opted = {
+ f.file_path
+ for f in await get_health_findings(session, health_data, include_unverified=True)
+ }
+ assert "src/Billing.java" in opted
+
+ dead = {f.file_path for f in await get_dead_code_findings(session, health_data)}
+ assert not dead & {"src/Billing.java", "src/Ui/Form.cs"}
+ assert "src/legacy/old_auth.py" in dead
+ summary = await get_dead_code_summary(session, health_data)
+ assert summary["gated"]["java"]["count"] == 1
+ assert summary["gated"]["csharp"]["count"] == 1
+ assert summary["total_findings"] == 3
+ opted_summary = await get_dead_code_summary(session, health_data, include_unverified=True)
+ assert opted_summary["total_findings"] == 5 and opted_summary["gated"] == {}
+
+
+async def test_crud_dead_code_holds_back_kotlin_and_swift(session, health_data):
+ from repowise.core.persistence.crud import get_dead_code_findings, get_dead_code_summary
+
+ gated = ("app/src/main/Feed.kt", "App/Views/Timeline.swift")
+ await _seed_gated_dead_code(session, health_data, gated)
+
+ dead = {f.file_path for f in await get_dead_code_findings(session, health_data)}
+ assert not dead & set(gated) and "src/legacy/old_auth.py" in dead
+ summary = await get_dead_code_summary(session, health_data)
+ assert summary["gated"]["kotlin"]["count"] == 1
+ assert summary["gated"]["swift"]["count"] == 1
+ opted = {
+ f.file_path
+ for f in await get_dead_code_findings(session, health_data, include_unverified=True)
+ }
+ assert set(gated) <= opted
+
+
+async def test_get_health_holds_back_gated_findings_and_says_so(setup_mcp, session, health_data):
+ from repowise.server.mcp_server import get_health
+
+ await _seed_java_health(session, health_data)
+
+ default = await get_health(only=["top_findings"], limit=50)
+ files = {f["file_path"] for f in default["top_findings"]}
+ assert "src/Billing.java" not in files and "src/auth/service.py" in files
+ gated = default["_meta"]["gated"]
+ assert gated["health"]["java"]["count"] == 1
+ assert gated["opt_in"] == {"include": ["unverified"]}
+
+ opted = await get_health(only=["top_findings"], include=["unverified"], limit=50)
+ assert "src/Billing.java" in {f["file_path"] for f in opted["top_findings"]}
+ assert "gated" not in opted["_meta"]
+
+ # Targeted at the gated file: nothing listed, and the count says why.
+ targeted = await get_health(targets=["src/Billing.java"])
+ assert not targeted.get("findings")
+ assert targeted["_meta"]["gated"]["health"]["java"]["count"] == 1
+
+
+async def test_get_dead_code_holds_back_gated_findings_and_says_so(setup_mcp, session, health_data):
+ from repowise.server.mcp_server import get_dead_code
+
+ await _seed_gated_dead_code(session, health_data)
+
+ def _paths(result):
+ return {f["file_path"] for t in result["tiers"].values() for f in t["findings"]}
+
+ default = await get_dead_code(min_confidence=0.0)
+ assert not _paths(default) & {"src/Billing.java", "src/Ui/Form.cs"}
+ assert "src/legacy/old_auth.py" in _paths(default)
+ gated = default["summary"]["gated"]
+ assert gated["java"]["count"] == 1 and gated["csharp"]["count"] == 1
+ assert gated["opt_in"] == {"include_unverified": True}
+
+ opted = await get_dead_code(min_confidence=0.0, include_unverified=True)
+ assert {"src/Billing.java", "src/Ui/Form.cs"} <= _paths(opted)
+ assert "gated" not in opted["summary"]
+
+ # A lookup by id still answers for a gated finding.
+ found = await get_dead_code(finding_id="gated0")
+ assert found["resolved"] is True
+
+
+async def test_get_dead_code_holds_back_kotlin_and_swift(setup_mcp, session, health_data):
+ from repowise.server.mcp_server import get_dead_code
+
+ gated = ("app/src/main/Feed.kt", "App/Views/Timeline.swift")
+ await _seed_gated_dead_code(session, health_data, gated)
+
+ def _paths(result):
+ return {f["file_path"] for t in result["tiers"].values() for f in t["findings"]}
+
+ default = await get_dead_code(min_confidence=0.0)
+ assert not _paths(default) & set(gated)
+ held = default["summary"]["gated"]
+ assert held["kotlin"]["count"] == 1 and held["swift"]["count"] == 1
+ assert held["swift"]["reason"] == "Held back on Swift files pending verification."
+ opted = await get_dead_code(min_confidence=0.0, include_unverified=True)
+ assert set(gated) <= _paths(opted)
diff --git a/tests/unit/server/test_language_gates_rest.py b/tests/unit/server/test_language_gates_rest.py
new file mode 100644
index 000000000..b175fd300
--- /dev/null
+++ b/tests/unit/server/test_language_gates_rest.py
@@ -0,0 +1,195 @@
+"""REST surfaces honour the layer x language gates.
+
+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.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from typing import Any
+
+from httpx import AsyncClient
+
+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
+from repowise.core.persistence.models import DeadCodeFinding
+from tests.unit.server.conftest import create_test_repo
+
+JAVA = "src/Billing.java"
+PY = "src/billing.py"
+
+
+def _finding(path: str, function_name: str) -> dict[str, Any]:
+ return {
+ "file_path": path,
+ "biomarker_type": "complex_method",
+ "severity": "high",
+ "function_name": function_name,
+ "line_start": 10,
+ "line_end": 30,
+ "details": {"ccn": 16},
+ "health_impact": 3.0,
+ "reason": "seeded",
+ "dimension": "defect",
+ }
+
+
+def _plan(path: str, symbol: str) -> dict[str, Any]:
+ return {
+ "refactoring_type": "extract_method",
+ "file_path": path,
+ "target_symbol": symbol,
+ "line_start": 10,
+ "line_end": 30,
+ "plan": {"extracted_name": f"_{symbol}_part", "span": {"start": 12, "end": 28}},
+ "evidence": {"ccn_removed": 6, "slice_nloc": 20},
+ "impact_delta": 1.0,
+ "effort_bucket": "S",
+ "blast_radius": {"scope": "local"},
+ "confidence": "high",
+ "source_biomarker": "complex_method",
+ }
+
+
+def _perf(path: str) -> HealthFindingData:
+ return HealthFindingData(
+ biomarker_type="io_in_loop",
+ severity=Severity.MEDIUM,
+ file_path=path,
+ function_name="run",
+ line_start=10,
+ line_end=10,
+ details={
+ "boundary_kind": "db",
+ "cross_function": True,
+ "path": [f"{path}::run", "src/db.py::fetch"],
+ "resolution_basis": "reliable-edge",
+ },
+ health_impact=0.0,
+ reason="Database work repeats for every loop iteration.",
+ dimension="performance",
+ )
+
+
+async def _seed(client: AsyncClient, app) -> str:
+ repo_id = (await create_test_repo(client))["id"]
+ perf = [_perf(JAVA), _perf(PY)]
+ link_performance_findings(perf)
+ async with app.state.session_factory() as session:
+ await crud.save_health_metrics(
+ session,
+ repo_id,
+ [
+ {"file_path": p, "score": 4.0, "max_ccn": 16, "max_nesting": 2, "nloc": 100}
+ for p in (JAVA, PY)
+ ],
+ )
+ await crud.save_health_findings(
+ session, repo_id, [_finding(JAVA, "charge"), _finding(PY, "charge"), *perf]
+ )
+ await crud.save_refactoring_suggestions(
+ session, repo_id, [_plan(JAVA, "charge"), _plan(PY, "charge")]
+ )
+ await crud.finalize_refactoring_opportunities(session, repo_id, analyzed_commit="c" * 40)
+ await crud.finalize_performance_opportunities(session, repo_id, analyzed_commit="c" * 40)
+ now = datetime.now(UTC)
+ for i, path in enumerate((JAVA, PY)):
+ session.add(
+ DeadCodeFinding(
+ id=f"dead{i}",
+ repository_id=repo_id,
+ kind="unused_export",
+ file_path=path,
+ symbol_name="old",
+ symbol_kind="function",
+ confidence=0.9,
+ reason="no callers",
+ lines=10,
+ safe_to_delete=True,
+ status="open",
+ analyzed_at=now,
+ )
+ )
+ await session.commit()
+ return repo_id
+
+
+async def _get(client: AsyncClient, url: str, **params: Any) -> Any:
+ resp = await client.get(url, params=params)
+ assert resp.status_code == 200, resp.text
+ return resp.json()
+
+
+def _paths(rows: list[dict]) -> set[str]:
+ return {row["file_path"] for row in rows}
+
+
+async def test_health_findings_and_overview(client: AsyncClient, app) -> None:
+ repo_id = await _seed(client, app)
+ base = f"/api/repos/{repo_id}/health"
+
+ assert _paths(await _get(client, f"{base}/findings")) == {PY}
+ assert JAVA in _paths(await _get(client, f"{base}/findings", include_unverified=True))
+
+ overview = await _get(client, f"{base}/overview")
+ assert JAVA not in _paths(overview["top_findings"])
+ assert overview["summary"]["gated"]["java"]["count"] == 2
+ # The score still counts the gated finding, so the file still ranks.
+ assert JAVA in _paths(overview["files"])
+ opted = await _get(client, f"{base}/overview", include_unverified=True)
+ assert JAVA in _paths(opted["top_findings"]) and opted["summary"]["gated"] == {}
+
+ drawer = await _get(client, f"{base}/files/breakdown", file_path=JAVA)
+ assert drawer["findings"] == [] and drawer["gated"]["java"]["count"] == 2
+
+
+async def test_dead_code_list_and_summary(client: AsyncClient, app) -> None:
+ repo_id = await _seed(client, app)
+ base = f"/api/repos/{repo_id}/dead-code"
+
+ assert _paths(await _get(client, base)) == {PY}
+ assert _paths(await _get(client, base, include_unverified=True)) == {PY, JAVA}
+ summary = await _get(client, f"{base}/summary")
+ assert summary["total_findings"] == 1 and summary["gated"]["java"]["count"] == 1
+ assert (await _get(client, f"{base}/summary", include_unverified=True))["gated"] == {}
+
+
+async def test_refactoring_plans_opportunities_and_rollup(client: AsyncClient, app) -> None:
+ repo_id = await _seed(client, app)
+ base = f"/api/repos/{repo_id}/refactoring"
+
+ # The extract plan, and the performance plan the perf finalizer wrote.
+ every = (await _get(client, f"{base}/targets", include_unverified=True))["plans"]
+ java_plans = sum(1 for plan in every if plan["file_path"] == JAVA)
+ assert java_plans >= 1
+ targets = await _get(client, f"{base}/targets")
+ assert _paths(targets["plans"]) == {PY}
+ assert targets["gated"]["java"]["count"] == java_plans
+
+ queue = await _get(client, f"{base}/opportunities", scope="all")
+ assert _paths(queue["items"]) == {PY} and queue["gated"]["java"]["count"] == 1
+ opted = await _get(client, f"{base}/opportunities", scope="all", include_unverified=True)
+ assert _paths(opted["items"]) == {PY, JAVA} and opted["gated"] == {}
+
+ rollup = await _get(client, f"{base}/summary")
+ assert rollup["summary"]["gated"]["java"]["count"] == 1
+ lead = rollup["summary"]["lead"]
+ assert lead is None or lead["file_path"] == PY
+
+
+async def test_performance_queue(client: AsyncClient, app) -> None:
+ repo_id = await _seed(client, app)
+ url = f"/api/repos/{repo_id}/health/performance-opportunities"
+
+ # Named filters leave the default queue, which takes no unmeasured cause.
+ every = {"context": "all", "proof": "unproven", "role": "all"}
+ page = await _get(client, url, **every)
+ assert JAVA not in {i.get("file_path") for i in page["items"]}
+ assert page["gated"]["java"]["count"] == 1
+ # The headline is recounted without the gated cause.
+ assert page["summary"]["total"] == page["total"]
+ opted = await _get(client, url, **every, include_unverified=True)
+ assert opted["total"] == page["total"] + 1 and opted["gated"] == {}