Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(mcp): stop shipping raw doubles and two scales under one key (#1631)
Raghav Chamadiya2b2d7cbf042b
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 7fb12e13b..ac7403de4 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -395,7 +395,9 @@ Modification risk assessment for files or a set of changed files.| `changed_files` | list[string] | No | Files in a PR/changeset for blast radius analysis; passing this switches the response into PR-directive mode || `repo` | string | No | *(workspace only)* Target repo alias |-**Returns:** Per-file risk score (0-10), hotspot status, dependent count, co-change partners, blast radius, recommended reviewers, test gap analysis, security signals. In workspace mode, enriched with cross-repo co-change partners and contract dependencies.+**Returns:** Per-file `hotspot_score` (0-1 churn percentile), `health_score` (0-10), hotspot status, dependent count, co-change partners (each with a recency-decayed `weight`, not an integer count), blast radius, recommended reviewers, test gap analysis, security signals. In workspace mode, enriched with cross-repo co-change partners and contract dependencies.++> **Scales.** Ratios derived from ownership or percentile columns are 0-1 (`hotspot_score`, `owner_pct`, `recent_owner_pct`); coverage and gap fields are 0-100 (`coverage_pct`, `branch_coverage_pct`, `share_of_repo_gap_pct`, `change_entropy_pct`, `churn_percentile`). The `_pct` suffix alone does not tell you which — check this table. Every emitted float is rounded to 4 significant digits.When `changed_files` is passed, the response leads with a `directive` block. Its core lists are the local blast radius: `will_break` (production files that depend on the diff and are likely to break), `will_break_tests` (test files impacted the same way, kept separate so a burst of broken tests doesn't crowd production impact out of the capped list), `missing_cochanges` (historical co-changers absent from the diff), `missing_tests` (changed files without test coverage), and `tests_to_run` (the positive complement of `missing_tests`: the tests the per-test coverage map proves execute the changed files, as pytest-runnable ids to validate the change; empty until a coverage map is ingested with `repowise coverage add`). In workspace mode that directive also carries the cross-repo fallout of the changed repo:diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.mdindex 115cba618..ff2fee4aa 100644--- a/docs/architecture/ARCHITECTURE.md+++ b/docs/architecture/ARCHITECTURE.md@@ -858,7 +858,10 @@ tracked file, it computes:without an import relationship. Reveals hidden structural coupling.- **Derived signals** — `is_hotspot` (top-quartile decayed churn AND absoluteactivity floors: >= 3 commits in 90d with real line movement), `is_stable`- (>10 commits, 0 in 90 days), `churn_percentile` (0.0–1.0)+ (>10 commits, 0 in 90 days), `churn_percentile` (0.0–1.0 **as stored**;+ normalized to 0–100 at the HTTP and MCP boundaries — see+ `code-health.md` §5.1. The one exception is `get_risk.hotspot_score`, which+ deliberately passes the stored 0–1 through under its own name.)**Performance targets:**- 3,000 files, 10K commits → < 3 minutesdiff --git a/packages/cli/src/repowise/cli/commands/risk_cmd.py b/packages/cli/src/repowise/cli/commands/risk_cmd.pyindex b7a0746ca..0531940f7 100644--- a/packages/cli/src/repowise/cli/commands/risk_cmd.py+++ b/packages/cli/src/repowise/cli/commands/risk_cmd.py@@ -291,8 +291,8 @@ def _render_card(name: str, card: dict) -> None:link = " [dim](imports)[/dim]" if p.get("has_import_link") else ""# A recency-decayed weight rather than a raw tally, so it is not an# integer; ``:g`` keeps a whole number whole and trims the rest.- count = p.get("count", 0)- shown = f"{float(count):.1f}".rstrip("0").rstrip(".") if count else "0"+ weight = p.get("weight", 0)+ shown = f"{float(weight):.1f}".rstrip("0").rstrip(".") if weight else "0"console.print(f" {escape(str(p.get('file_path', '')))} [dim]x{shown}[/dim]{link}")@@ -565,7 +565,7 @@ def risk_command(sign = "+" if d.contribution >= 0 else ""table.add_row(d.label,- f"{d.value:g}",+ "-" if d.value is None else f"{d.value:g}",f"[{push_color}]{sign}{d.contribution:.2f}[/{push_color}]",)console.print(table)diff --git a/packages/core/src/repowise/core/analysis/change_risk/model.py b/packages/core/src/repowise/core/analysis/change_risk/model.pyindex 3132982bb..c720365ab 100644--- a/packages/core/src/repowise/core/analysis/change_risk/model.py+++ b/packages/core/src/repowise/core/analysis/change_risk/model.py@@ -74,7 +74,7 @@ class RiskDriver:"""One feature's contribution to the change-risk logit."""feature: str- value: float # raw feature value+ value: float | None # raw feature value; None when the feature is unknowncontribution: float # signed push on the logit (coef * standardized value)label: str # human-readable explanation@@ -176,11 +176,13 @@ def score_change(features: ChangeFeatures) -> ChangeRisk:raw = getattr(features, name)if raw is None:# Unknown feature (e.g. author experience on a diff-only caller):- # contribute nothing rather than impute, and say so.+ # contribute nothing rather than impute, and say so. The value is+ # None, not NaN — NaN is not JSON, and every serializing boundary+ # would otherwise have to strip it back out one by one.drivers.append(RiskDriver(feature=name,- value=float("nan"),+ value=None,contribution=0.0,label=f"{name} (unknown)",)diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/change_entropy.py b/packages/core/src/repowise/core/analysis/health/biomarkers/change_entropy.pyindex f193f61ec..9e2996e01 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/change_entropy.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/change_entropy.py@@ -82,7 +82,11 @@ class ChangeEntropyDetector:line_end=None,details={"change_entropy": round(entropy, 4),- "change_entropy_pct": round(percentile, 3),+ # 0-100, matching FileSignals._entropy_pct and every other+ # emitted copy of this field. The stored column is 0-1, and+ # emitting it raw here put two scales under one key in a+ # single get_health response.+ "change_entropy_pct": round(percentile * 100.0, 1),"commit_count_90d": commits_90d,},reason=(diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/churn_risk.py b/packages/core/src/repowise/core/analysis/health/biomarkers/churn_risk.pyindex fb9bdf7a3..114f85afa 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/churn_risk.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/churn_risk.py@@ -92,7 +92,11 @@ class ChurnRiskDetector:line_end=None,details={"relative_churn": round(relative_churn, 2),- "churn_percentile": round(churn_pct, 3),+ # 0-100, matching churn_complexity._churn_pct and every+ # other emitted copy. The stored column is 0-1; emitting it+ # raw here put two scales under one key in a single+ # get_health response.+ "churn_percentile": round(churn_pct * 100.0, 1),"lines_added_90d": added,"lines_deleted_90d": deleted,"commit_count_90d": commits_90d,diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.pyindex 6a1e73387..995614d7e 100644--- a/packages/server/src/repowise/server/mcp_server/__init__.py+++ b/packages/server/src/repowise/server/mcp_server/__init__.py@@ -85,6 +85,32 @@ _LAZY_ATTRS: dict[str, tuple[str, str]] = {_surface_applied = False+def tool_middleware(fn: Any) -> Any:+ """Compose the layers wrapped around every registered MCP tool.++ Each layer is signature-preserving, so the tool schemas are unchanged.+ Ordering, innermost first:++ 1. ``shield`` — no exception may escape to FastMCP as a protocol-level+ isError (an early isError teaches the agent to abandon the server for+ the whole session), so it must see the raw tool.+ 2. ``quantize`` — rounds every float in the response. Outside the shield so+ shaped error responses are covered too, and inside the savings layer so+ the ledger measures the payload as actually delivered.+ 3. ``instrument`` — savings/telemetry, outermost, so shaped error responses+ are still dead-end-debited in the ledger.++ Named rather than inlined at the ``apply`` call so tests can wrap a tool in+ the real composition; ``tests/unit/server/mcp/test_number_precision.py``+ relies on that to prove no raw double reaches an agent.+ """+ from repowise.server.mcp_server._failure_shield import shield+ from repowise.server.mcp_server._rounding import quantize+ from repowise.server.mcp_server._savings import instrument++ return instrument(quantize(shield(fn)))++def ensure_full_surface() -> Any:"""Import every tool module and attach the registry to the FastMCP server.@@ -109,19 +135,9 @@ def ensure_full_surface() -> Any:importlib.import_module(f"{__name__}.{module}")from repowise.core.registry import mcp_tool_registry- from repowise.server.mcp_server._failure_shield import shield as _failure_shield- from repowise.server.mcp_server._savings import instrument as _savings_instrumentfrom repowise.server.mcp_server._tool_selection import snapshot_full_surface- # ``middleware`` wraps each tool twice, both layers signature-preserving so- # the tool schemas are unchanged. The failure shield sits innermost: no- # exception may escape to FastMCP as a protocol-level isError (an early- # isError teaches the agent to abandon the server for the whole session).- # The savings layer wraps it, so shaped error responses are still- # dead-end-debited in the ledger.- mcp_tool_registry.apply(- _mcp, middleware=lambda fn: _savings_instrument(_failure_shield(fn))- )+ mcp_tool_registry.apply(_mcp, middleware=tool_middleware)# Snapshot the full registered surface so per-server tool selection# (single-repo vs workspace, config/CLI overrides) can rebuild from it.diff --git a/packages/server/src/repowise/server/mcp_server/_rounding.py b/packages/server/src/repowise/server/mcp_server/_rounding.pynew file mode 100644index 000000000..61e279fce--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/_rounding.py@@ -0,0 +1,112 @@+"""Numeric hygiene — no raw double ever reaches the agent.++Scores, ratios and graph metrics arrive from SQL and NumPy at full double+precision (``hotspot_score: 0.791581408944753``, ``pagerank:+0.0005258389771750028``). Every digit past the fourth is noise the model pays+tokens to read and cannot act on, and a wall of them makes a response harder to+skim than the same numbers rounded.++Applied as a middleware layer around every registered tool (see+``__init__.py``) rather than at each of the ~20 producing call sites, so a tool+added later cannot regress the contract by forgetting to round.++Two deliberate choices:++* **Significant digits, not decimal places.** A blanket ``round(x, 2)`` would+ flatten ``pagerank`` (~1e-4) to ``0.0`` and destroy the ranking it exists to+ express. Rounding to four significant digits is scale-free: it shortens+ ``0.791581408944753`` to ``0.7916`` and ``0.0005258389771750028`` to+ ``0.0005258``, and leaves an already-rounded value untouched.+* **Non-finite becomes ``None``.** ``NaN``/``Infinity`` are not JSON — Python+ emits them as bare literals a strict parser rejects. ``None`` is the honest+ encoding of "no value" and every consumer already handles null.++The pass is idempotent, so re-rounding a cached payload is harmless.+"""++from __future__ import annotations++import contextlib+import functools+import inspect+import logging+import math+from collections.abc import Callable+from typing import Any++logger = logging.getLogger(__name__)++#: Significant digits kept on every emitted float.+#:+#: Four is the smallest width that preserves ordering on the values agents rank+#: by: fused ``relevance_score`` neighbours differ in the third significant+#: digit (2.9508 vs 2.9032), and percentile-derived scores cluster in the+#: high 0.9s (0.9956 vs 0.9967 vs 0.9997) where three digits would tie them.+_SIG_DIGITS = 4++#: Ceiling on decimal places, so a denormal cannot produce an absurd literal.+_MAX_DECIMALS = 12+++def round_float(value: float, sig: int = _SIG_DIGITS) -> float | None:+ """Round *value* to *sig* significant digits; non-finite becomes ``None``."""+ if math.isnan(value) or math.isinf(value):+ return None+ if value == 0.0:+ return 0.0+ exponent = math.floor(math.log10(abs(value)))+ decimals = min(sig - 1 - exponent, _MAX_DECIMALS)+ if decimals <= 0:+ # Magnitudes at or above 10**sig are already coarser than the target+ # precision; rounding to 0 dp keeps them float-typed without widening.+ return float(round(value, 0))+ return round(value, decimals)+++def round_numbers(obj: Any, sig: int = _SIG_DIGITS) -> Any:+ """Recursively round every float in *obj*, in place where possible.++ ``bool`` is a subclass of ``int`` and neither is touched — line numbers,+ counts and flags keep their exact type. Mutating dicts and lists in place+ avoids copying a large payload; the operation is idempotent, so a shared or+ cached structure is safe to pass through more than once.+ """+ if isinstance(obj, float):+ return round_float(obj, sig)+ if isinstance(obj, dict):+ for key, val in obj.items():+ obj[key] = round_numbers(val, sig)+ return obj+ if isinstance(obj, list):+ for i, val in enumerate(obj):+ obj[i] = round_numbers(val, sig)+ return obj+ if isinstance(obj, tuple):+ return tuple(round_numbers(v, sig) for v in obj)+ return obj+++def quantize(fn: Callable[..., Any]) -> Callable[..., Any]:+ """Wrap an async MCP tool *fn* so its response carries no raw doubles.++ Signature-preserving, and never fatal: a payload this cannot walk is+ returned untouched rather than failing the call.+ """+ if not inspect.iscoroutinefunction(fn):+ return fn++ tool = getattr(fn, "__name__", "tool")++ @functools.wraps(fn)+ async def _wrapped(*args: Any, **kwargs: Any) -> Any:+ result = await fn(*args, **kwargs)+ try:+ return round_numbers(result)+ except Exception: # pragma: no cover - defensive; rounding never breaks a tool+ logger.debug("mcp float rounding failed for %s", tool, exc_info=True)+ return result++ # Preserve the original signature so FastMCP builds the correct tool schema.+ with contextlib.suppress(ValueError, TypeError): # pragma: no cover - exotic callables+ _wrapped.__signature__ = inspect.signature(fn) # type: ignore[attr-defined]+ return _wrappeddiff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.pyindex 4ff8a0e1e..81d64de72 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/assessment.py@@ -255,6 +255,10 @@ def _build_co_changes(meta: Any, import_related: set[str], exclude_spec: Any) ->Larger lists make MCP responses verbose without adding signal: top-5 capturesthe bulk of the temporal-coupling mass and keeps tool output tight for agents.++ The strength field is emitted as ``weight``, not ``count``: the stored value+ is a recency-decayed sum (``exp(-age_days / tau)`` per shared commit), so it+ is fractional. Named ``count`` it read as "5.52 co-changes" to every agent."""partners = json.loads(meta.co_change_partners_json)partners_sorted = sorted(@@ -266,7 +270,7 @@ def _build_co_changes(meta: Any, import_related: set[str], exclude_spec: Any) ->[{"file_path": p.get("file_path", p.get("path", "")),- "count": p.get("co_change_count", p.get("count", 0)),+ "weight": p.get("co_change_count", p.get("count", 0)),"last_co_change": p.get("last_co_change"),"has_import_link": p.get("file_path", p.get("path", "")) in import_related,}diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.pyindex ab2c3fe01..a745bae20 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py@@ -39,9 +39,9 @@ async def get_risk() -> dict:"""What history says about touching these files — bug fixes, churn, owners.- Fuses git temporal signals (churn percentile, trend, bus factor) with- graph topology (dependents, co-changes, impact surface) and security- findings. Consult before editing a bug-fixed or busy file. Pass+ Fuses git temporal signals (``hotspot_score``/``owner_pct`` are 0-1; trend;+ bus factor) with graph topology (dependents, co-changes, impact surface)+ and security findings. Consult before editing a bug-fixed or busy file. Passchanged_files for PR mode: the response leads with a directive block(will_break, missing_cochanges, missing_tests, tests_to_run) — read itfirst. tests_to_run is coverage-backed: the tests the per-test map provesdiff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.pyindex 95fbec1bf..857186f52 100644--- a/packages/server/src/repowise/server/routers/git.py+++ b/packages/server/src/repowise/server/routers/git.py@@ -209,7 +209,7 @@ def _commit_detail_from_row(drivers = [RiskDriverResponse(feature=d.feature,- value=None if d.value != d.value else d.value, # drop NaN (unknown feature)+ value=d.value, # already None for an unknown featurecontribution=d.contribution,label=d.label,)@@ -751,7 +751,7 @@ def get_risk_range(drivers=[RiskDriverResponse(feature=d.feature,- value=None if d.value != d.value else d.value, # drop NaN (unknown feature)+ value=d.value, # already None for an unknown featurecontribution=d.contribution,label=d.label,)diff --git a/tests/unit/cli/test_search_collapse.py b/tests/unit/cli/test_search_collapse.pyindex 31614deb7..6ef6565f8 100644--- a/tests/unit/cli/test_search_collapse.py+++ b/tests/unit/cli/test_search_collapse.py@@ -118,7 +118,7 @@ RISK_PAYLOAD = {"co_change_partners": [{"file_path": "packages/core/src/repowise/core/persistence/models.py",- "count": 19.13,+ "weight": 19.13,"last_co_change": "2026-08-01","has_import_link": True,}diff --git a/tests/unit/health/test_organizational_biomarkers.py b/tests/unit/health/test_organizational_biomarkers.pyindex 1cfc207b1..6f7b53aa4 100644--- a/tests/unit/health/test_organizational_biomarkers.py+++ b/tests/unit/health/test_organizational_biomarkers.py@@ -339,7 +339,10 @@ def test_change_entropy_fires_on_high_percentile():out = ChangeEntropyDetector().detect(_ctx(meta))assert len(out) == 1assert out[0].severity == "medium" # 0.80 <= pct < 0.90- assert out[0].details["change_entropy_pct"] == 0.88+ # Stored 0-1 in, emitted 0-100 out: the detail shares its key with+ # FileSignals.change_entropy_pct, which has always been 0-100, and the two+ # land in the same get_health response.+ assert out[0].details["change_entropy_pct"] == 88.0def test_change_entropy_escalates_to_critical_on_hotspot():diff --git a/tests/unit/server/mcp/test_failure_shield.py b/tests/unit/server/mcp/test_failure_shield.pyindex 996eb6b20..f4cbd7824 100644--- a/tests/unit/server/mcp/test_failure_shield.py+++ b/tests/unit/server/mcp/test_failure_shield.py@@ -175,17 +175,24 @@ def test_sync_callables_pass_through():assert shield(sync_fn) is sync_fn-def test_server_composes_shield_into_middleware():+async def test_server_composes_shield_into_middleware():"""Pin the __init__.py wiring: every registered tool goes through theshield. Without this, a refactor could silently drop the composition and- reopen the isError-on-every-tool hole."""- import inspect as _inspect+ reopen the isError-on-every-tool hole.- import repowise.server.mcp_server as mcp_mod+ Asserted through behaviour rather than by matching the composition's+ source text, so reordering or renaming the layers cannot fail this while+ the guarantee still holds — nor pass while it does not.+ """+ from repowise.server.mcp_server import tool_middleware++ async def exploding_tool() -> dict:+ raise RuntimeError("boom")- source = _inspect.getsource(mcp_mod)- assert "_failure_shield" in source- assert "_savings_instrument(_failure_shield(fn))" in source+ result = await tool_middleware(exploding_tool)()+ assert isinstance(result, dict), "an exception escaped the shield"+ assert "boom" not in repr(result).lower() or "error" in repr(result).lower()# ---------------------------------------------------------------------------diff --git a/tests/unit/server/mcp/test_number_precision.py b/tests/unit/server/mcp/test_number_precision.pynew file mode 100644index 000000000..e80d3ea86--- /dev/null+++ b/tests/unit/server/mcp/test_number_precision.py@@ -0,0 +1,307 @@+"""No raw double, and no two scales under one key, ever reach an agent.++Two regressions this file exists to prevent, both found by dogfooding the+live MCP surface:++1. **Full-precision floats.** ``hotspot_score: 0.791581408944753`` and+ ``pagerank: 0.0005258389771750028`` shipped verbatim from SQL/NumPy. Every+ digit past the fourth is tokens the agent pays for and cannot act on. Fixed+ centrally in ``_rounding.quantize``, composed into every tool by+ ``tool_middleware`` — so the guard here wraps tools in the *real*+ composition rather than asserting per-field, and a tool added later is+ covered without touching this file.++2. **One key, two scales.** ``change_entropy_pct`` was 0-1 in+ ``get_health.findings[].details`` and 0-100 in ``metrics[].signals`` of the+ same response; ``churn_percentile`` likewise. An agent reading 0.973 as a+ percentage reports "0.97%" for a 97th-percentile file.+"""++from __future__ import annotations++import math++import pytest++from repowise.server.mcp_server._rounding import round_float, round_numbers++# Mirrors _rounding._SIG_DIGITS. Duplicated deliberately: if someone widens the+# constant, this suite should fail and make them justify it, not silently+# follow along.+_SIG_DIGITS = 4+++# ---------------------------------------------------------------------------+# The rounding primitives+# ---------------------------------------------------------------------------+++ ("raw", "expected"),+ [+ # The two values that prompted the fix.+ (0.791581408944753, 0.7916),+ (0.0005258389771750028, 0.0005258),+ # Significant digits, not decimal places: a small magnitude keeps its+ # ranking information instead of collapsing to 0.0.+ (0.00012927455637682034, 0.0001293),+ (1.2345678e-08, 1.235e-08),+ # Already short, or exactly representable: unchanged.+ (0.92, 0.92),+ (8.7, 8.7),+ (100.0, 100.0),+ (0.0, 0.0),+ # Large magnitudes stay float-typed and do not gain width.+ (1149.5, 1150.0),+ (536836.0, 536836.0),+ # Sign is preserved.+ (-0.791581408944753, -0.7916),+ ],+)+def test_round_float_keeps_four_significant_digits(raw, expected):+ assert round_float(raw) == pytest.approx(expected, rel=1e-12)++[email protected]("bad", [float("nan"), float("inf"), float("-inf")])+def test_non_finite_becomes_none(bad):+ """NaN/Infinity are not JSON — a strict parser rejects the bare literal."""+ assert round_float(bad) is None+++def test_round_numbers_walks_nested_payloads():+ payload = {+ "targets": {+ "a.py": {+ "hotspot_score": 0.791581408944753,+ "impact_surface": [{"pagerank": 0.0005258389771750028}],+ "co_change": ({"count": 5.5199999999}, 1.23456789),+ }+ }+ }+ out = round_numbers(payload)+ target = out["targets"]["a.py"]+ assert target["hotspot_score"] == 0.7916+ assert target["impact_surface"][0]["pagerank"] == 0.0005258+ assert target["co_change"][0]["count"] == 5.52+ assert target["co_change"][1] == 1.235+++def test_ints_and_bools_are_not_touched():+ """Line numbers, counts and flags must keep their exact type."""+ payload = {"line_start": 30, "is_hotspot": True, "bus_factor": 1, "name": "x"}+ out = round_numbers(dict(payload))+ assert out == payload+ assert isinstance(out["line_start"], int)+ assert isinstance(out["is_hotspot"], bool)+++def test_rounding_is_idempotent():+ once = round_numbers({"score": 0.791581408944753})+ twice = round_numbers(dict(once))+ assert once == twice+++# ---------------------------------------------------------------------------+# The guard that survives new tools: the real middleware composition+# ---------------------------------------------------------------------------+++def _offending_floats(obj, path="$"):+ """Every float in *obj* carrying more than _SIG_DIGITS significant digits.++ Returns ``(path, value)`` pairs so a failure names the exact field.+ """+ bad = []+ if isinstance(obj, bool | int):+ return bad+ if isinstance(obj, float):+ # Non-finite is never valid JSON; anything the rounder would change+ # still carries digits the agent pays for.+ if math.isnan(obj) or math.isinf(obj) or obj != round_float(obj):+ bad.append((path, obj))+ return bad+ if isinstance(obj, dict):+ for key, val in obj.items():+ bad.extend(_offending_floats(val, f"{path}.{key}"))+ return bad+ if isinstance(obj, list | tuple):+ for i, val in enumerate(obj):+ bad.extend(_offending_floats(val, f"{path}[{i}]"))+ return bad+ return bad+++def test_the_detector_actually_detects():+ """Guard the guard — a walker that never fires would make this file inert."""+ assert _offending_floats({"a": {"b": [0.791581408944753]}}) == [+ ("$.a.b[0]", 0.791581408944753)+ ]+ assert _offending_floats({"a": float("nan")})+ assert _offending_floats({"ok": 0.7916, "n": 12, "flag": True}) == []+++async def test_tool_middleware_rounds_a_tool_response():+ """The composition wired in ``ensure_full_surface`` must include rounding.++ Wraps a stand-in tool in the real ``tool_middleware`` so removing the+ quantize layer fails here rather than silently shipping raw doubles.+ """+ from repowise.server.mcp_server import tool_middleware++ async def get_thing(): # stands in for a registered tool+ return {"result": {"hotspot_score": 0.791581408944753, "n": 3}}++ wrapped = tool_middleware(get_thing)+ out = await wrapped()+ assert out["result"]["hotspot_score"] == 0.7916+ assert out["result"]["n"] == 3+ assert _offending_floats(out) == []+++async def test_middleware_preserves_the_tool_signature():+ """FastMCP builds each tool's schema from its signature."""+ import inspect++ from repowise.server.mcp_server import tool_middleware++ async def get_thing(targets: list[str], limit: int = 5) -> dict:+ return {}++ assert inspect.signature(tool_middleware(get_thing)) == inspect.signature(get_thing)+++#: A full-precision percentile, as ``PERCENT_RANK()`` actually returns it.+#: The seeded fixture values (0.92, 0.65) are already short, so a payload scan+#: over stock fixtures passes with or without the fix — this is what makes the+#: end-to-end assertion below bite.+_RAW_PERCENTILE = 0.791581408944753+++async def test_real_tool_payload_rounds_a_seeded_raw_double(setup_mcp):+ """End-to-end over a real payload, through the real middleware.++ ``get_risk`` is the worst historical offender: hotspot_score, owner_pct,+ recent_owner_pct and impact_surface[].pagerank all shipped raw. Seeding the+ git row with a genuine ``PERCENT_RANK()`` output proves the rounding runs on+ the real path, not just on a synthetic dict.+ """+ import sqlalchemy as sa++ import repowise.server.mcp_server as mcp_mod+ from repowise.core.persistence.models import GitMetadata+ from repowise.server.mcp_server import get_risk, tool_middleware++ async with mcp_mod._session_factory() as session:+ await session.execute(+ sa.update(GitMetadata)+ .where(GitMetadata.file_path == "src/auth/service.py")+ .values(churn_percentile=_RAW_PERCENTILE)+ )+ await session.commit()++ raw = await get_risk(["src/auth/service.py"])+ assert raw["targets"]["src/auth/service.py"]["hotspot_score"] == _RAW_PERCENTILE, (+ "fixture no longer carries the raw value — this test would be vacuous"+ )++ out = await tool_middleware(get_risk)(["src/auth/service.py"])+ assert out["targets"]["src/auth/service.py"]["hotspot_score"] == 0.7916+ offenders = _offending_floats(out, "$get_risk")+ assert not offenders, f"raw doubles in get_risk: {offenders[:5]}"+++async def test_other_tool_payloads_carry_no_raw_doubles(setup_mcp):+ """Breadth pass over the remaining high-float tools."""+ from repowise.server.mcp_server import get_context, get_dead_code, tool_middleware++ for tool, args in ((get_context, (["src/auth/service.py"],)), (get_dead_code, ())):+ out = await tool_middleware(tool)(*args)+ offenders = _offending_floats(out, f"${tool.__name__}")+ assert not offenders, f"raw doubles in {tool.__name__}: {offenders[:5]}"+++# ---------------------------------------------------------------------------+# One key, one scale+# ---------------------------------------------------------------------------+++def test_change_entropy_pct_is_zero_to_one_hundred():+ """The biomarker detail must match FileSignals._entropy_pct's contract."""+ from repowise.core.analysis.health.signals import _entropy_pct++ stored = 0.973 # the column is 0-1+ assert _entropy_pct(stored) == 97.3+ assert round(stored * 100.0, 1) == _entropy_pct(stored)+++def test_churn_percentile_is_zero_to_one_hundred():+ from repowise.core.analysis.health.churn_complexity import _churn_pct++ assert _churn_pct(0.989) == 98.9+++def _file_context(**git_meta):+ from repowise.core.analysis.health.biomarkers.base import FileContext++ return FileContext(+ file_path="src/app.py",+ language="python",+ nloc=10,+ has_test_file=False,+ module="src",+ git_meta=git_meta,+ )+++def test_change_entropy_biomarker_emits_percentile_on_the_zero_to_one_hundred_scale():+ """Stored 0-1 in, emitted 0-100 out — the same contract FileSignals uses.++ 0.973 must not reach the agent as ``0.973`` beside a ``metrics[].signals``+ copy of the same field reading ``97.3``.+ """+ from repowise.core.analysis.health.biomarkers.change_entropy import BIOMARKER++ results = BIOMARKER.detect(+ _file_context(change_entropy=3.5264, change_entropy_pct=0.973, commit_count_90d=10)+ )+ assert results, "detector did not fire — preconditions changed, fix the fixture"+ assert results[0].details["change_entropy_pct"] == 97.3+++def test_churn_risk_biomarker_emits_percentile_on_the_zero_to_one_hundred_scale():+ from repowise.core.analysis.health.biomarkers.churn_risk import BIOMARKER++ results = BIOMARKER.detect(+ _file_context(+ churn_percentile=0.989,+ lines_added_90d=427,+ lines_deleted_90d=538,+ commit_count_90d=5,+ is_hotspot=True,+ )+ )+ assert results, "detector did not fire — preconditions changed, fix the fixture"+ assert results[0].details["churn_percentile"] == 98.9+++# ---------------------------------------------------------------------------+# NaN at the source, not stripped per-boundary+# ---------------------------------------------------------------------------+++def test_unknown_change_risk_feature_is_none_not_nan():+ """``exp`` is unknown on a diff-only caller; NaN there is not valid JSON."""+ import json++ from repowise.core.analysis.change_risk.model import ChangeFeatures, score_change++ risk = score_change(ChangeFeatures(la=10, ld=2, nf=1, nd=1, ns=1, entropy=0.5, exp=None))+ exp_driver = next(d for d in risk.drivers if d.feature == "exp")+ assert exp_driver.value is None++ payload = [{"feature": d.feature, "value": d.value} for d in risk.top_drivers]+ json.dumps(payload, allow_nan=False) # raises ValueError if a NaN survives