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.

fix(health): nine get_health defects — silent projection, unbounded response, undifferentiating headline (#1414)

Raghav Chamadiya23cfd68b3c93
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index a8d2615c3..173a25084 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -115,7 +115,7 @@ Resolve refs with `repowise expand <ref>` from a shell, or
| `index_age_days` | Days since the last `repowise update` |
| `indexed_commit` | Short (12-char) SHA the index was built against |
| `live_head` | Only when it differs from `indexed_commit` |
-| `stale_warning` | Only on a real signal: HEAD mismatch, or age over ~90 days when git is unreachable |
+| `stale_warning` | Only on a real signal: HEAD mismatch **that actually changed files**, or age over ~90 days when git is unreachable. Two commits with identical trees (an empty commit, a no-op merge) report `index_behind` instead |
| `embedder`, `embedder_degraded`, `embedder_warning` | Only when the embedder fell back to a mock/degraded mode |
Silence on these fields means the index is current; don't infer staleness from their absence. `list_repos`, `get_architecture`, `get_blast_radius`, and `get_conformance` don't carry a freshness envelope at all.
@@ -507,7 +507,7 @@ code-health merge-gate judges it on.
|-----------|------|----------|-------------|
| `targets` | list[string] | No | File paths, or `module:foo` to expand a module's file set. Empty means dashboard mode. |
| `include` | list[string] | No | Opt-in blocks (default response stays lean): `"biomarkers"` (findings in dashboard mode), `"refactoring"` (structured, graph-aware refactoring plans; see below), `"trend"` (snapshot diff + declining / predicted-decline alerts), `"coverage"`, `"accuracy"` (the "does the score find the bugs?" stat, dashboard mode), `"signals"` (per-file process / people / topology signals, targeted mode), `"churn_complexity"` (churn x complexity quadrant points, dashboard mode), and a dimension name (`"performance"` / `"defect"` / `"maintainability"`) to filter findings to that pillar. |
-| `only` | list[string] | No | Keep just these top-level keys. `include` adds blocks, `only` subtracts them. `mode`, `_meta` and each kept list's `*_total` sibling always survive. The `include` block names work as aliases: `biomarkers`→`findings`, `accuracy`→`defect_accuracy`, `refactoring`→`refactoring_plans`. `signals` has no top-level key (it merges into `metrics[].signals`), so it is reported in `unknown_only_keys` — in targeted mode, where `signals` applies, name `metrics` instead. |
+| `only` | list[string] | No | Keep just these top-level keys. `include` adds blocks, `only` subtracts them. `mode`, `_meta`, `unresolved`, `known_modules` and each kept list's `*_total` sibling always survive. The three `include` **block** names work as aliases: `biomarkers`→`findings`, `accuracy`→`defect_accuracy`, `refactoring`→`refactoring_plans`. The `include` **dimension** names (`performance`, `defect`, `maintainability`) do not — they filter rows inside several blocks and have no single key to resolve to, so they land in `unknown_only_keys`. Nor does `signals`, which merges into `metrics[].signals` — in targeted mode, where `signals` applies, name `metrics` instead. |
| `repo` | string | No | *(workspace only)* Target repo alias |
| `limit` | int | No | Max rows in **every** ranked list (default 20, capped at 50). `0` means no rows; the `*_total` siblings still report the true counts. |
@@ -530,9 +530,28 @@ named in `unresolved` with a reason (`not_indexed` → run `repowise update`,
`known_modules`), so an empty `findings` list means healthy and nothing else. A
target set that resolves to nothing still answers in targeted mode rather than
falling back to the repo dashboard. Every capped list carries a `*_total`
-sibling — including under `only`, which retains it automatically — and
+sibling — including under `only`, which retains it automatically. `unresolved`
+and `known_modules` survive any `only` projection too, for the same reason
+`mode` does: a caller who has to ask for the error report in order to see it
+does not have an error report.
+
`_meta.health_analyzed_at` dates the health pass, which is separate from
-indexing and can lag it.
+indexing and can lag it, and `_meta.health_analyzed_commit` says which commit
+those scores were computed against. The incremental update path rescores only
+the files that changed, so the metrics table can hold rows from several passes
+at once; when it does, `_meta.health_analyzed_commits_distinct` says how many
+and the reported commit is the newest pass's. Both fields are omitted rather
+than guessed when no row records a commit.
+
+**The response is bounded.** `include` only *adds* blocks, and the dashboard's
+five ranked lists compose: `include=['refactoring']` on a mid-size repo lands
+near the host's tool-result cap, past which the host rejects the whole result
+and you get nothing. Pair `include` with `only` —
+`get_health(include=['refactoring'], only=['refactoring_plans'])` is the call
+`directive.plan_via` names. Anything that would still overflow is trimmed
+longest-ranked-list-first and reported in `_meta.truncated_to_fit`
+(`{block: rows_dropped}`), never silently; the `*_total` siblings still describe
+what was there, and re-requesting one block with `only` recovers it.
**Test material is bucketed, not hidden.** Every metric row carries `is_test`
(distinct from `has_test_file`: "is this file a test" vs "is this file tested").
@@ -562,6 +581,32 @@ make that actionable rather than a mystery:
(dashboard mode) is the top-N ranked by it, distinct from `worst_files`, which
sorts by raw score and ranks a 30-line file at 1.0 equal to a 1,200-line file at
1.0 that moves the average ~40x more.
+- `weighted_deficit`, `directive.recovers_points` and
+ `gap_analysis.weighted_gap_points` share one unit — *score-points x NLOC* —
+ which compares against itself and nothing else. Every `high_leverage_files`
+ row and the `directive` also carry `share_of_repo_gap_pct`, the same quantity
+ with a denominator; that plus `gap_analysis.files_to_reach_target` is what
+ answers "is this worth doing".
+- `kpis.non_code_files` and `kpis.average_health_code_only` say how much of the
+ headline is markdown/JSON/YAML. No biomarker walks those files, so they score
+ a mechanical 10.0 meaning "nothing looked at this" — on this repo, 233 of
+ 3,314 rows, lifting `average_health` from 7.31 to 7.47. `average_health`
+ itself deliberately still counts them, so the tool, the badge, the snapshots
+ and the web UI all report the same number.
+
+**One score, not two.** A metric row carries `score` (the defect dimension and
+the headline), `maintainability_score` and `performance_score`. There is no
+`defect_score` in the response: it was set from the same value as `score` on
+every row, and two names for one number cost a reader a source dive to pick
+between them. The field to rank on is neither — it is `weighted_deficit`.
+
+**`primary_biomarker` names a discrete cause.** It prefers the strongest
+*discrete* finding over a continuous one. `coverage_gradient` fires on every
+file that has coverage data at all, so on a well-covered repo it used to win the
+max-impact tiebreak nearly everywhere and headline the list with "N% of lines
+uncovered" — true, and equally true of every other file. The gradient still
+counts in full toward `total_deduction` and the score, and still leads a file
+that has no discrete finding.
The opt-in enrichments:
diff --git a/packages/core/alembic/versions/0050_health_analyzed_commit.py b/packages/core/alembic/versions/0050_health_analyzed_commit.py
new file mode 100644
index 000000000..85fd69768
--- /dev/null
+++ b/packages/core/alembic/versions/0050_health_analyzed_commit.py
@@ -0,0 +1,49 @@
+"""Record the commit each health metric row was scored against.
+
+``_meta`` already reports ``indexed_commit`` and ``health_analyzed_at``, but
+nothing said *which commit* the health scores describe. Health runs as its own
+pass and can lag the index, so ``repositories.head_commit`` does not answer it:
+a response could show a current index next to scores computed several commits
+earlier and look entirely fresh.
+
+Per-row rather than per-repo because the incremental path
+(``upsert_health_metrics``) rewrites only the files that changed, so the table
+legitimately holds rows from several passes at once. ``get_health`` reports the
+newest pass's commit plus a count of how many others are still represented,
+instead of picking one and implying the whole table agrees.
+
+NULL on every row written before this column existed, which reads as "not
+recorded" — the field is simply omitted from ``_meta`` rather than guessed at.
+
+``init_db``'s additive schema reconciler picks the column up from the model for
+local SQLite stores that never run Alembic; this migration covers the managed
+Postgres ones.
+
+Revision ID: 0050
+Revises: 0049
+Create Date: 2026-08-11
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0050"
+down_revision: str | None = "0049"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "health_file_metrics",
+ sa.Column("analyzed_commit", sa.String(length=40), nullable=True),
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("health_file_metrics", "analyzed_commit")
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/__init__.py b/packages/core/src/repowise/core/analysis/health/biomarkers/__init__.py
index aac4ed3e3..397d8d210 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/__init__.py
@@ -3,12 +3,13 @@
from __future__ import annotations
from .base import Biomarker, BiomarkerResult, FileContext
-from .registry import detect_all, registered_biomarkers
+from .registry import continuous_biomarkers, detect_all, registered_biomarkers
__all__ = [
"Biomarker",
"BiomarkerResult",
"FileContext",
+ "continuous_biomarkers",
"detect_all",
"registered_biomarkers",
]
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gradient.py b/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gradient.py
index 9378092af..6a1410220 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gradient.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gradient.py
@@ -47,6 +47,12 @@ _COVERAGE_MEDIUM = 70.0
class CoverageGradientDetector:
name = "coverage_gradient"
category = "test_coverage_gradient"
+ # Declares what the ``deduction`` override below already makes true: this
+ # fires on every file that has coverage data at all, so its magnitude ranks
+ # files against each other but never answers "why this file". Readers that
+ # pick one headline biomarker per file consult ``continuous_biomarkers()``
+ # to prefer a discrete cause.
+ continuous = True
def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
cov = ctx.line_coverage_pct
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
index 2a2a250d6..64b548ece 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
@@ -123,6 +123,19 @@ _DETECTOR_FACTORIES: list[type[Biomarker]] = [
]
+def continuous_biomarkers() -> frozenset[str]:
+ """Names of detectors whose deduction is continuous rather than gated.
+
+ A continuous biomarker fires on *every* file that carries its input signal
+ (``coverage_gradient`` on every file with coverage data), so it wins a
+ max-impact tiebreak on files that have nothing else wrong with them and
+ tells a reader nothing about why this file rather than any other. Read off
+ the class attribute rather than listed here so a new continuous detector
+ cannot be added without this set following it.
+ """
+ return frozenset(c.name for c in _DETECTOR_FACTORIES if getattr(c, "continuous", False))
+
+
def registered_biomarkers(
*, disabled: Sequence[str] = (), extra: Sequence[Biomarker] = ()
) -> list[Biomarker]:
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 befed5d0b..d363cbbb0 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
@@ -169,6 +169,8 @@ async def save_health_metrics(
session: AsyncSession,
repository_id: str,
metrics: list[Any],
+ *,
+ analyzed_commit: str | None = None,
) -> None:
"""Replace per-file health metrics for *repository_id*.
@@ -176,6 +178,12 @@ async def save_health_metrics(
constraint on (repository_id, file_path) means we cannot leave
stale rows around without an upsert dance — delete-and-insert keeps
it simple and aligns with how dead-code findings are written.
+
+ ``analyzed_commit`` stamps every written row with the commit these scores
+ were computed against — the same pattern as ``save_coverage_files``'
+ ``ingested_commit_sha``. Health runs as its own pass and can lag the index,
+ so ``Repository.head_commit`` cannot answer "how old is this score". Omitted
+ → NULL, which reads as "not recorded" rather than "current".
"""
existing = await session.execute(
select(HealthFileMetric).where(HealthFileMetric.repository_id == repository_id)
@@ -205,6 +213,10 @@ async def save_health_metrics(
}
else:
data = dict(m)
+ # After the dict-passthrough branch so an explicit per-row value in a
+ # raw dict still wins; the sha is a property of the pass, not the row.
+ if analyzed_commit is not None:
+ data.setdefault("analyzed_commit", analyzed_commit)
session.add(
HealthFileMetric(
@@ -923,12 +935,19 @@ async def upsert_health_metrics(
session: AsyncSession,
repository_id: str,
metrics: list[Any],
+ *,
+ analyzed_commit: str | None = None,
) -> None:
"""Upsert per-file metrics; unchanged files in the table stay put.
Sibling of ``save_health_metrics`` (which delete-then-inserts the
whole repo). Used by the incremental analysis path so a partial
re-index never wipes metric rows for files that weren't touched.
+
+ ``analyzed_commit`` stamps only the rows this call rewrites, which is the
+ point of recording it per row: after a partial pass the table honestly
+ reports two commits, and ``get_health``'s ``_meta`` says so rather than
+ claiming one scoring commit for the whole repo.
"""
if not metrics:
return
@@ -960,6 +979,11 @@ async def upsert_health_metrics(
}
else:
data = dict(m)
+ # Only when the caller knows the sha. An unconditional set would push a
+ # None over a sha already on the row, so a caller that simply does not
+ # track the commit would erase the stamp a caller that does had written.
+ if analyzed_commit is not None:
+ data.setdefault("analyzed_commit", analyzed_commit)
row = by_path.get(data["file_path"])
if row is not None:
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 09f450db6..0b1839f4a 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -1231,6 +1231,13 @@ class HealthFileMetric(Base):
defect_score: Mapped[float | None] = mapped_column(Float, nullable=True)
maintainability_score: Mapped[float | None] = mapped_column(Float, nullable=True)
performance_score: Mapped[float | None] = mapped_column(Float, nullable=True)
+ # Commit this row was scored against. Health is a separate pass from indexing
+ # and can lag it, so ``Repository.head_commit`` does not answer "how old is
+ # this score". Per-row rather than per-repo because the incremental path
+ # (``upsert_health_metrics``) rewrites only the files that changed, so the
+ # table legitimately holds rows from several passes at once. NULL on every
+ # row written before this column existed.
+ analyzed_commit: Mapped[str | None] = mapped_column(String(40), nullable=True)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc
)
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index 8bec348e1..9409ae363 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -632,6 +632,26 @@ def _carry_forward_kg_enrichment(kg: Any, prior_kg: Any) -> None:
kg.tour = prior_kg.tour
+async def _analyzed_commit(session: Any, repo_id: str) -> str | None:
+ """Live HEAD of the repo being updated, for stamping health rows.
+
+ Read off disk rather than from ``Repository.head_commit``: the health pass
+ just scored the working tree, and the stored column is written by a
+ different step whose ordering relative to this one is not guaranteed.
+ ``None`` on any failure — an unstamped row reads as "not recorded", which
+ is honest, while a wrong sha would not be.
+ """
+ from repowise.core.persistence.models import Repository
+ from repowise.core.workspace.update import get_head_commit
+
+ try:
+ repo = await session.get(Repository, repo_id)
+ local_path = getattr(repo, "local_path", None) if repo else None
+ return get_head_commit(Path(local_path)) if local_path else None
+ except Exception:
+ return None
+
+
async def persist_partial_health(session: Any, repo_id: str, report: Any) -> None:
"""Upsert health findings + metrics for the changed-files subset.
@@ -649,7 +669,12 @@ async def persist_partial_health(session: Any, repo_id: str, report: Any) -> Non
changed_paths = sorted({m.file_path for m in report.metrics or []})
if not changed_paths:
return
- await upsert_health_metrics(session, repo_id, report.metrics or [])
+ await upsert_health_metrics(
+ session,
+ repo_id,
+ report.metrics or [],
+ analyzed_commit=await _analyzed_commit(session, repo_id),
+ )
await upsert_health_findings(
session, repo_id, list(report.findings or []), file_paths=changed_paths
)
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index fb5446481..be2d88ee9 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -1463,13 +1463,16 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
# ---- Health findings + per-file metrics ---------------------------------
if getattr(result, "health_report", None):
hr = result.health_report
- await save_health_metrics(session, repo_id, hr.metrics or [])
+ # Hoisted out of the coverage branch below: the same sha now stamps the
+ # metric rows, so a reader can tell how far the health pass lags the
+ # index instead of assuming the two moved together.
+ head_sha = getattr(result, "head_commit", None) or getattr(result, "commit_sha", None)
+ await save_health_metrics(session, repo_id, hr.metrics or [], analyzed_commit=head_sha)
if hr.findings:
await save_health_findings(session, repo_id, hr.findings)
# Resolved coverage rows, when a report was ingested this run.
coverage_files = getattr(hr, "coverage_files", None)
if coverage_files:
- head_sha = getattr(result, "head_commit", None) or getattr(result, "commit_sha", None)
await save_coverage_files(
session,
repo_id,
diff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.py
index 13d6f0623..9b29b765b 100644
--- a/packages/server/src/repowise/server/mcp_server/_meta.py
+++ b/packages/server/src/repowise/server/mcp_server/_meta.py
@@ -225,8 +225,13 @@ def freshness_from_repo(repository: Any | None, targets: list[str] | None = None
Conditionally emitted:
* ``live_head`` — only when it differs from the indexed commit
* ``stale_warning`` — only on a real signal (a served target changed,
- HEAD mismatch on a repo-level response, OR very old with no git)
- * ``index_behind`` — HEAD moved but no served target is affected
+ HEAD mismatch with real file changes on a repo-level response, OR very
+ old with no git)
+ * ``index_behind`` — HEAD moved but nothing the response serves is
+ affected: either no served target changed, or the two commits have
+ identical trees so *no* file changed at all. The second case used to
+ warn on every repo-level response, which is the loudest possible way to
+ be wrong about a repo that is completely current.
Defensive throughout: any missing piece is dropped rather than raised so
an upstream change to the Repository model can never poison a tool result.
@@ -257,11 +262,19 @@ def freshness_from_repo(repository: Any | None, targets: list[str] | None = None
if live_full != indexed_full:
out["live_head"] = live_full[:12]
changed = (
- _changed_files_between(local_path, indexed_full, live_full)
- if targets is not None and local_path
- else None
+ _changed_files_between(local_path, indexed_full, live_full) if local_path else None
)
- if targets is not None and changed is not None:
+ if changed is not None and not changed:
+ # HEAD moved but the two trees are identical (an empty commit, a
+ # merge that changed nothing, a tag-only move). Nothing this or
+ # any other response serves can be stale, so the repo-level
+ # warning was crying wolf on a repo that was completely current —
+ # and a warning that fires when nothing changed trains an agent
+ # to stop reading the field. Checked before the targets branch
+ # because it holds for repo-level responses too, which are
+ # exactly the ones that previously always warned.
+ out["index_behind"] = True
+ elif targets is not None and changed is not None:
if targets_hit_by_changes(targets, changed):
out["stale_warning"] = (
"A file this response serves changed after indexing — "
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.py
index 981886de1..c3c1f44d4 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py
@@ -10,7 +10,9 @@ from typing import Any
from sqlalchemy import select
+from repowise.core.analysis.health.biomarkers import continuous_biomarkers
from repowise.core.analysis.health.churn_complexity import churn_complexity_points
+from repowise.core.analysis.health.complexity.languages import LANGUAGE_MAPS
from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracy
from repowise.core.analysis.health.grading import HEALTHY_MIN, band_for
from repowise.core.analysis.health.grading import distribution as health_distribution
@@ -37,6 +39,7 @@ from repowise.core.persistence.models import (
RefactoringSuggestion,
)
from repowise.core.registry import mcp_tool_registry as mcp
+from repowise.server.mcp_server._budget import effective_char_budget
from repowise.server.mcp_server._helpers import (
_get_exclude_spec,
_get_repo,
@@ -119,6 +122,107 @@ _ONLY_ALIASES = {
_DIRECTIVE_CANDIDATES = 3
+# Deliberately not ``CHAR_BUDGET`` (8000 tokens). That ceiling is for tools that
+# *summarize*; the dashboard is a ranked report and already measures ~44k chars
+# at the documented default ``limit=20``, so budgeting it there would silently
+# halve every list on a call that has never failed. The ceiling that matters here
+# is the one whose breach is an isError: pass an effectively-unbounded
+# ``configured`` so ``effective_char_budget`` returns the host-derived cap alone
+# (25000 tokens x 0.6 x 4 chars = 60,000), and follows a narrowed
+# ``MAX_MCP_OUTPUT_TOKENS`` down.
+_HOST_CEILING = 1 << 30
+
+# Room for what the guard adds *after* it measures: ``truncated_to_fit``, the
+# recovery sentence and ``timing_ms``. Without it the report of the trim pushed
+# the response back over the ceiling the trim existed to respect — the marker
+# has to be inside the budget, not on top of it. Same shape as ``tool_why``'s
+# ``_COLLECTOR_HEADROOM_CHARS``, and generous: over-reserving costs a row.
+_TRUNCATION_MARKER_HEADROOM = 400
+
+# Every list this response can carry that grows with the repo, trimmed
+# longest-first when the whole payload would overflow the host's tool-result cap.
+# Named rather than derived from "every value that is a list" so trimming can
+# never eat a small structural list (``kpis.performance_unsupported_languages``,
+# ``unresolved``) to save bytes a growable list is responsible for.
+#
+# **This list must stay exhaustive, and the first version of it was not.** It
+# held only the eight dashboard blocks that carry a ``limit`` cap, which are the
+# lists least able to overflow — while the three genuinely unbounded ones were
+# invisible to the guard. ``metrics`` and ``trends`` are built per *target* with
+# no cap at all (a ``module:`` target expands to every file in the module), and
+# targeted ``coverage.files`` serializes the per-line ``covered_lines`` arrays
+# that dashboard mode declines to read precisely because they measured 466,874 B.
+# A guard that misses those does something worse than nothing: it trims a small
+# capped list to zero, still overflows, and stamps ``truncated_to_fit`` claiming
+# it handled the problem. **When adding a list to this response, add it here.**
+#
+# Dotted entries address one level of nesting; the flat ``result.get(k)`` scan
+# would never have found them.
+_TRIMMABLE_LISTS = (
+ "refactoring_plans",
+ "high_leverage_files",
+ "worst_files",
+ "test_findings",
+ "top_findings",
+ "findings",
+ "churn_complexity",
+ "modules",
+ "metrics",
+ "trends",
+ "coverage.files",
+ "trend.recent",
+)
+
+
+def _resolve_list(result: dict[str, Any], path: str) -> list[Any] | None:
+ """The list at a ``_TRIMMABLE_LISTS`` path, or ``None`` when absent."""
+ node: Any = result
+ for part in path.split("."):
+ if not isinstance(node, dict):
+ return None
+ node = node.get(part)
+ return node if isinstance(node, list) and node else None
+
+
+def _fit_to_budget(result: dict[str, Any], budget: int) -> dict[str, int]:
+ """Trim ranked lists until *result* fits *budget* chars. Returns what it cut.
+
+ ``include`` only ever adds a block, and the dashboard's ranked lists compose:
+ measured on this repo, bare ``include=['refactoring']`` returns ~59k chars
+ with no single list at fault (refactoring_plans 34%, high_leverage_files 16%,
+ worst_files 16%, test_findings 13%, top_findings 13%). Past the host's
+ ``MAX_MCP_OUTPUT_TOKENS`` the result is *rejected* with an isError — the
+ agent loses the whole answer — so a per-list cap that is individually
+ reasonable is not enough; something has to bound the sum.
+
+ Trims the currently-longest list, so the cut lands on whichever block is
+ actually responsible rather than on a fixed victim. Every trimmed list keeps
+ its ``*_total`` sibling, and the cut is reported in
+ ``_meta.truncated_to_fit`` — the recovery path is ``only=[...]``, which gates
+ the work as well as the payload.
+ """
+ dropped: dict[str, int] = {}
+ size = len(json.dumps(result, default=str))
+ while size > budget:
+ candidates = {k: rs for k in _TRIMMABLE_LISTS if (rs := _resolve_list(result, k))}
+ longest = max(candidates, key=lambda k: len(candidates[k]), default=None)
+ if longest is None:
+ # Nothing left to give. Better an oversized response the host may
+ # reject than a silently empty one — and _meta says what happened.
+ break
+ rows = candidates[longest]
+ # Estimate how many rows the overflow is worth from this list's own mean
+ # row size, so a 200-row overflow is not 200 whole-response
+ # re-serializations. Never more than half the list per pass: the estimate
+ # is a mean over uneven rows, and over-trimming cannot be undone.
+ per_row = max(1, len(json.dumps(rows, default=str)) // len(rows))
+ take = max(1, min(len(rows), (size - budget) // per_row, max(1, len(rows) // 2)))
+ del rows[len(rows) - take :]
+ dropped[longest] = dropped.get(longest, 0) + take
+ size = len(json.dumps(result, default=str))
+ return dropped
+
+
def _in_dimensions(row: Any, dimensions: set[str]) -> bool:
"""True when *row* belongs to one of *dimensions* (empty set -> everything).
@@ -142,13 +246,25 @@ def _leads_by_file(findings: list[Any]) -> dict[str, dict[str, Any]]:
``primary_biomarker`` / ``primary_reason`` give a low file "the one reason"
to lead with; ``total_deduction`` (summed ``health_impact``) distinguishes
two files that both floor at 1.0. Additive — the score itself is untouched.
+
+ The headline prefers the strongest **discrete** finding. A continuous
+ biomarker fires on every file carrying its input signal, so on a repo with
+ coverage data ``coverage_gradient`` wins the max-impact tiebreak nearly
+ everywhere: measured on this repo before the preference, it led 22 of the
+ top 50 ``worst_files`` and 14 of the top 50 ``high_leverage_files`` with
+ "N% of lines uncovered", which is true and tells a reader nothing about why
+ this file rather than any other. The gradient still counts in
+ ``total_deduction`` and still leads when it is a file's only finding — it
+ just stops crowding out a nameable cause.
"""
+ continuous = continuous_biomarkers()
by_file: dict[str, list[Any]] = {}
for f in findings:
by_file.setdefault(f.file_path, []).append(f)
leads: dict[str, dict[str, Any]] = {}
for path, fs in by_file.items():
- primary = max(fs, key=lambda x: x.health_impact)
+ discrete = [f for f in fs if f.biomarker_type not in continuous]
+ primary = max(discrete or fs, key=lambda x: x.health_impact)
leads[path] = {
"primary_biomarker": primary.biomarker_type,
"primary_reason": primary.reason,
@@ -184,11 +300,20 @@ def _serialize_metric(
# headline recovers if the file reaches 8.0, so ranking by it — not by
# raw score — points at the files that actually move the average. A tiny
# 1.0 file and a 1200-line 1.0 file score the same but differ 40x here.
+ # The unit is score-points x NLOC, which is meaningless on its own — the
+ # docstring and ``gap_analysis.weighted_gap_points`` give it a
+ # denominator, and every ``high_leverage_files`` row carries the same
+ # quantity as ``share_of_repo_gap_pct``.
"weighted_deficit": round(max(HEALTHY_MIN - m.score, 0.0) * max(m.nloc, 1)),
- # Per-dimension scores from the three-signal split. ``score`` is the
- # overall surfaced number (== ``defect_score`` for now);
+ # Per-dimension scores from the three-signal split. ``defect_score`` is
+ # deliberately absent: ``engine.py`` sets it and ``score`` from the same
+ # ``scores["defect"]`` value, so it was pure duplication on every row of
+ # every response — measured on this repo, 3,314 of 3,314 rows had
+ # ``score == defect_score`` and none was NULL. Two names for one number
+ # cost an agent a source read to decide which to rank on, and the one to
+ # rank on is neither (it is ``weighted_deficit``). ``score`` survives
+ # because every doc, skill and UI already names it.
# ``performance_score`` is computed but not yet surfaced as its own pillar.
- "defect_score": _round_opt(getattr(m, "defect_score", None)),
"maintainability_score": _round_opt(getattr(m, "maintainability_score", None)),
"performance_score": _round_opt(getattr(m, "performance_score", None)),
# Dominant-cause lead + pre-clamp magnitude (null when no findings for
@@ -471,11 +596,25 @@ def _perf_kpis(performance_findings: int, coverage: PerfCoverage | None) -> dict
}
+def _code_only(
+ metrics: list[HealthFileMetric], lang_by_path: dict[str, str]
+) -> list[HealthFileMetric]:
+ """The metric rows the complexity walker actually walks.
+
+ ``LANGUAGE_MAPS`` is already the repo's definition of "real code" — the perf
+ pillar uses exactly this filter so docs/config rows never dilute its
+ coverage math (``perf/coverage.py::coverage_for_metrics``). The defect
+ headline never applied it.
+ """
+ return [m for m in metrics if lang_by_path.get(m.file_path, "") in LANGUAGE_MAPS]
+
+
def _compute_kpis(
metrics: list[HealthFileMetric],
*,
performance_findings: int = 0,
coverage: PerfCoverage | None = None,
+ lang_by_path: dict[str, str] | None = None,
) -> dict[str, Any]:
if not metrics:
return {
@@ -490,9 +629,31 @@ def _compute_kpis(
total_nloc = sum(max(m.nloc, 1) for m in metrics)
avg = sum(m.score * max(m.nloc, 1) for m in metrics) / total_nloc
worst = min(metrics, key=lambda r: r.score)
+ # What the headline would read over code alone. No biomarker walks a
+ # markdown or JSON file, so those rows carry a mechanical 10.0 that means
+ # "nothing looked at this", exactly the fabricated-10.0 problem the perf
+ # pillar already surfaces rather than hides (``perf/coverage.py``). Measured
+ # on this repo: 233 of 3,314 rows are non-code, 221 of them score exactly
+ # 10.0, they are 7.5% of NLOC, and they lift ``average_health`` 7.31 -> 7.47.
+ # Surfaced rather than subtracted: ``average_health`` is what the badge, the
+ # snapshots, the trend alerts and the web UI all read, and redefining it
+ # here alone would make this tool disagree with every one of them.
+ code_kpis: dict[str, Any] = {}
+ if lang_by_path is not None:
+ code = _code_only(metrics, lang_by_path)
+ code_nloc = sum(max(m.nloc, 1) for m in code)
+ code_kpis = {
+ "non_code_files": len(metrics) - len(code),
+ "average_health_code_only": (
+ round(sum(m.score * max(m.nloc, 1) for m in code) / code_nloc, 2)
+ if code_nloc
+ else None
+ ),
+ }
return {
"file_count": len(metrics),
"average_health": round(avg, 2),
+ **code_kpis,
# NLOC-weighted (``average_health``) vs plain file mean. When these
# diverge, a few large low-scoring files are holding the headline down —
# the weighted number is what the dashboard/badge surface, and the gap
@@ -523,31 +684,30 @@ async def get_health(
No ``targets`` → repo dashboard, led by a ``directive`` naming the one file
to fix first. With ``targets`` → per-file scores + findings. Rank by
- ``weighted_deficit``, not ``score``: the score floors at 1.0 and cannot
- separate the worst band.
+ ``weighted_deficit`` (score-points x NLOC), not ``score``, which floors at
+ 1.0; ``share_of_repo_gap_pct`` is the same quantity as a percentage.
- Three dimensions per file: ``score`` (defect risk, the headline),
- ``maintainability_score``, ``performance_score`` (static I/O-in-loop / N+1
- risk, never blended in). Each finding carries its ``dimension``. Dashboard
- mode buckets test material: ``top_findings`` is production,
- ``test_findings`` the rest, each row says ``is_test``.
+ Per file: ``score`` is defect risk *and* the headline — there is no
+ ``defect_score`` — beside ``maintainability_score`` / ``performance_score``
+ (never blended in).
Args:
- targets: file paths or ``module:<name>``. Empty → dashboard mode. A
- target matching nothing is named in ``unresolved`` with a reason
- (``not_indexed`` → run ``repowise update`` | ``no_such_path`` |
- ``excluded`` | ``no_such_module``), so empty ``findings`` means
- healthy.
+ targets: file paths or ``module:<name>``. Empty → dashboard. A target
+ matching nothing is named in ``unresolved`` with a reason (so empty
+ ``findings`` means healthy); it survives any ``only``.
include: ``biomarkers`` | ``refactoring`` | ``trend`` | ``coverage`` |
``accuracy`` | ``signals`` | ``churn_complexity`` |
- ``performance``/``defect``/``maintainability`` (dimension).
- only: keep just these top-level keys — ``["directive"]`` is the cheapest
- useful call. Each kept list's ``*_total`` is retained too, and the
- ``include`` names work as aliases. Unmatched keys land in
- ``unknown_only_keys``.
+ ``performance``/``defect``/``maintainability`` (dimension). Only
+ *adds*, and the ranked lists compose — pair with ``only``, e.g.
+ ``include=['refactoring'], only=['refactoring_plans']``. Over-cap
+ responses are trimmed (``_meta.truncated_to_fit``).
+ only: keep just these top-level keys; ``["directive"]`` is cheapest and
+ ``*_total`` siblings survive. Only the three block names
+ alias (``biomarkers``/``accuracy``/``refactoring``); the dimension
+ names ``performance``/``defect``/``maintainability`` and ``signals``
+ do not, and land in ``unknown_only_keys``.
repo: usually omitted.
- limit: max rows per ranked list (max 50, ``0`` for none); each carries
- a ``*_total`` sibling so truncation is never silent.
+ limit: max rows per ranked list (max 50, ``0`` for none).
"""
started = perf_counter()
# ``0`` means none, matching the ``module_limit`` convention on the REST
@@ -612,6 +772,9 @@ async def get_health(
# Performance headline inputs (dashboard mode): filled inside the session.
perf_coverage: PerfCoverage | None = None
perf_findings_count = 0
+ # ``None`` means "not read", which is what keeps the code/non-code KPI split
+ # off targeted responses rather than reporting it over one file.
+ lang_by_path: dict[str, str] | None = None
async with get_session(ctx.session_factory) as session:
repository = await _get_repo(session)
@@ -812,6 +975,8 @@ async def get_health(
# Dashboard perf headline: coverage (how much of the analyzed code the
# perf pass ran on) + open performance-finding count. Both feed ``kpis``
# alone, so a projection that drops kpis skips the language-map read.
+ # The same map answers "how much of this headline is non-code" — one
+ # read, two KPIs.
if not scoped and wants("kpis"):
lang_by_path = await get_file_language_map(session, repository.id)
perf_coverage = coverage_for_metrics(all_metrics, lang_by_path)
@@ -1006,6 +1171,7 @@ async def get_health(
metric_rows if scoped else all_metrics,
performance_findings=perf_findings_count,
coverage=perf_coverage,
+ lang_by_path=lang_by_path,
)
if scoped:
@@ -1018,7 +1184,15 @@ async def get_health(
result: dict[str, Any] = {
"mode": "targets",
"targets": raw_targets,
+ # Deliberately NOT capped by ``limit``: the caller named these files
+ # and getting back fewer than they asked about would answer a
+ # different question. The response-size guard is what bounds it, and
+ # ``metrics_total`` is the ``*_total`` sibling that makes a trim
+ # visible — a ``module:`` target expands to every file in the module,
+ # so this is the one growable list whose length the caller cannot
+ # infer from what they passed.
"metrics": metric_payload,
+ "metrics_total": len(metric_payload),
# Capped like every other ranked list, with the total alongside so
# the truncation is visible rather than inferred from the length.
"findings": [_serialize_finding(f) for f in finding_rows[:limit]],
@@ -1103,8 +1277,28 @@ async def get_health(
# change which files the repo's "worst" are. The crowding is in the
# *finding* lists, which is where the split below happens.
"worst_files_total": len(metric_rows),
+ # The one list whose entire purpose is leverage ranking, so it is the
+ # one place ``weighted_deficit`` gets a denominator. The bare number
+ # is score-points x NLOC and answers "which is bigger" but never "is
+ # this worth doing"; the same quantity as a share of the repo's total
+ # gap does, and it is the unit ``directive`` already speaks.
"high_leverage_files": [
- _serialize_metric(m, leads.get(m.file_path), is_test=m.file_path in test_paths)
+ {
+ **_serialize_metric(
+ m, leads.get(m.file_path), is_test=m.file_path in test_paths
+ ),
+ "share_of_repo_gap_pct": (
+ round(
+ 100.0
+ * max(HEALTHY_MIN - m.score, 0.0)
+ * max(m.nloc, 1)
+ / gap["weighted_gap_points"],
+ 1,
+ )
+ if gap.get("weighted_gap_points")
+ else None
+ ),
+ }
for m in by_leverage[:limit]
],
"high_leverage_files_total": len(by_leverage),
@@ -1300,7 +1494,18 @@ async def get_health(
# ``only=["modules"]`` at ``limit=50`` returned 50 of 116 modules with
# no ``modules_total`` to say so. Retaining it is not the caller's job —
# a caller who knew to ask for the total would not need the guarantee.
- keep = set(only_list) | {"mode"} | {f"{k}_total" for k in only_list}
+ # ``unresolved`` / ``known_modules`` survive any projection, for the same
+ # reason ``mode`` does. They are the block that stops an empty result
+ # reading as "this file is healthy" (A1), and projecting them away put a
+ # typo'd target straight back to silent: ``targets=["does/not/exist.py"],
+ # only=["metrics"]`` returned ``metrics: []`` and nothing else. A caller
+ # who has to ask for the error report in order to see it does not have an
+ # error report.
+ keep = (
+ set(only_list)
+ | {"mode", "unresolved", "known_modules"}
+ | {f"{k}_total" for k in only_list}
+ )
# A key that does not exist in this response is named rather than
# quietly yielding an empty one — same rule as ``unresolved`` above.
# A misspelled projection is otherwise indistinguishable from a block
@@ -1319,9 +1524,33 @@ async def get_health(
# When the health pass last ran, which is a separate pass from indexing and
# can lag it. ``_build_meta``'s fields all describe the *index*, so a stale
# health row was previously invisible.
- analyzed = [m.updated_at for m in all_metrics if getattr(m, "updated_at", None)]
+ analyzed = [m for m in all_metrics if getattr(m, "updated_at", None)]
if analyzed:
- result["_meta"]["health_analyzed_at"] = max(analyzed).isoformat()
+ latest = max(analyzed, key=lambda m: m.updated_at)
+ result["_meta"]["health_analyzed_at"] = latest.updated_at.isoformat()
+ # The commit the health rows were scored against. Distinct from
+ # ``indexed_commit``: the incremental path upserts only the files that
+ # changed (``upsert_health_metrics``), so the table can legitimately hold
+ # rows from several passes, and reporting one SHA for all of them would
+ # be a claim this read cannot support. Report the newest pass's commit,
+ # and say how many others are still represented.
+ commits = {c for m in analyzed if (c := getattr(m, "analyzed_commit", None))}
+ if latest_commit := getattr(latest, "analyzed_commit", None):
+ result["_meta"]["health_analyzed_commit"] = latest_commit[:12]
+ if len(commits) > 1:
+ result["_meta"]["health_analyzed_commits_distinct"] = len(commits)
+ # Keep the whole response under the host's tool-result cap. Applied after the
+ # projection (so ``only`` is credited for what it saved) and after ``_meta``
+ # (which the host tokenizes too), but before ``timing_ms`` so the reported
+ # time covers the trim.
+ if dropped := _fit_to_budget(
+ result, effective_char_budget(_HOST_CEILING) - _TRUNCATION_MARKER_HEADROOM
+ ):
+ result["_meta"]["truncated_to_fit"] = dropped
+ result["_meta"]["truncated_recovery"] = (
+ "Response exceeded the MCP result cap. Re-request a single block with "
+ "only=[...] — each list's *_total says what was there."
+ )
# Server-side wall clock, as ``get_context`` already reports. Without it a
# regression in here is invisible until someone profiles it by hand.
result["_meta"]["timing_ms"] = round((perf_counter() - started) * 1000, 2)
diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.py
index affda8418..c98a5344f 100644
--- a/tests/unit/server/mcp/test_health.py
+++ b/tests/unit/server/mcp/test_health.py
@@ -6,6 +6,8 @@ test data, mirroring the conftest pattern from the REST API tests.
from __future__ import annotations
+import json
+
import pytest
@@ -31,9 +33,10 @@ async def test_get_health_dashboard_surfaces_maintainability(setup_mcp, health_d
# Repo-level KPI headline for the maintainability pillar.
# NLOC-weighted: (6.0*200 + 9.0*50) / 250 = 6.6.
assert result["kpis"]["maintainability_average"] == 6.6
- # Per-file metrics carry all three dimension scores.
+ # Per-file metrics carry all three dimension scores — the defect one under
+ # its surfaced name ``score`` (there is no duplicate ``defect_score``).
worst = result["worst_files"][0]
- assert worst["defect_score"] == 4.5
+ assert worst["score"] == 4.5
assert worst["maintainability_score"] == 6.0
assert worst["performance_score"] == 9.0
# Findings are tagged with their home pillar so they can be filtered.
@@ -1154,3 +1157,481 @@ async def test_directive_plan_via_is_projected(setup_mcp, health_data):
directive = (await get_health(only=["directive"]))["directive"]
assert "only=['refactoring_plans']" in directive["plan_via"]
+
+
+async def test_only_projection_keeps_unresolved(setup_mcp, health_data):
+ """A typo'd target stays named however the response is projected.
+
+ Regression: ``only`` kept ``mode`` and its named keys and dropped everything
+ else, including ``unresolved`` — so ``targets=["does/not/exist.py"],
+ only=["metrics"]`` came back as an empty ``metrics`` list and nothing else,
+ which is exactly the "an empty result reads as healthy" failure A1 exists to
+ close. A caller who has to ask for the error report in order to see it does
+ not have an error report.
+ """
+ from repowise.server.mcp_server import get_health
+
+ result = await get_health(targets=["does/not/exist.py"], only=["metrics"])
+ assert result["metrics"] == []
+ assert result["unresolved"] == [{"target": "does/not/exist.py", "reason": "no_such_path"}]
+
+
+async def test_only_projection_keeps_known_modules(setup_mcp, health_data):
+ """``known_modules`` is the recovery path for a bad ``module:`` and rides along."""
+ from repowise.server.mcp_server import get_health
+
+ result = await get_health(targets=["module:nope"], only=["metrics"])
+ assert result["unresolved"] == [{"target": "module:nope", "reason": "no_such_module"}]
+ assert "auth" in result["known_modules"]
+
+
+async def test_metric_rows_drop_the_duplicated_defect_score(setup_mcp, health_data):
+ """``score`` *is* the defect dimension; two names for it earned nothing.
+
+ ``engine.py`` sets ``score`` and ``defect_score`` from the same
+ ``scores["defect"]`` value — measured on the live index, 3,314 of 3,314 rows
+ had them equal and none was NULL. The cost was never bytes, it was an agent
+ reading the source to decide which of the two to rank on (the answer is
+ neither: it is ``weighted_deficit``).
+ """
+ from repowise.server.mcp_server import get_health
+
+ row = (await get_health(targets=["src/auth/service.py"]))["metrics"][0]
+ assert "defect_score" not in row
+ assert row["score"] == 4.5
+ # The other two pillars are genuinely distinct numbers and stay.
+ assert row["maintainability_score"] == 6.0
+ assert row["performance_score"] == 9.0
+ for block in ("worst_files", "high_leverage_files"):
+ assert all("defect_score" not in m for m in (await get_health())[block])
+
+
+async def test_high_leverage_rows_carry_share_of_repo_gap(setup_mcp, health_data):
+ """``weighted_deficit`` is score-points x NLOC — unusable without a denominator."""
+ from repowise.server.mcp_server import get_health
+
+ result = await get_health()
+ gap = result["gap_analysis"]["weighted_gap_points"]
+ rows = result["high_leverage_files"]
+ assert rows, "fixture must have at least one file below the healthy band"
+ for row in rows:
+ assert row["share_of_repo_gap_pct"] == pytest.approx(
+ round(100.0 * row["weighted_deficit"] / gap, 1), abs=0.11
+ )
+ # The lead file's share is the same number the directive quotes. Not exact
+ # equality: `_directive` rounds `recovers_points` to an integer before
+ # dividing, the row divides the raw deficit, so the two agree to the
+ # rounding and not below it. (Flagged in review as a fixture coincidence —
+ # the fixture's deficit happens to be whole, which would have hidden a real
+ # divergence.)
+ assert rows[0]["share_of_repo_gap_pct"] == pytest.approx(
+ result["directive"]["share_of_repo_gap_pct"], abs=0.1
+ )
+
+
+async def gradient_health_data(session, populated_db: str) -> str:
+ """One file whose largest finding is the continuous coverage gradient.
+
+ Mirrors the live shape: the gradient out-weighs every discrete finding on
+ the file, so a plain max-impact pick names it.
+ """
+ from repowise.core.persistence.crud import save_health_findings, save_health_metrics
+
+ rid = populated_db
+ await save_health_metrics(
+ session,
+ rid,
+ [
+ {
+ "file_path": "src/wide.py",
+ "score": 3.0,
+ "max_ccn": 20,
+ "max_nesting": 4,
+ "nloc": 400,
+ "has_test_file": True,
+ "module": "src",
+ "line_coverage_pct": 30.0,
+ }
+ ],
+ )
+ await save_health_findings(
+ session,
+ rid,
+ [
+ {
+ "file_path": "src/wide.py",
+ "biomarker_type": "coverage_gradient",
+ "severity": "high",
+ "function_name": None,
+ "line_start": None,
+ "line_end": None,
+ "details": {},
+ "health_impact": 2.8,
+ "reason": "70% of lines uncovered (30% line coverage)",
+ },
+ {
+ "file_path": "src/wide.py",
+ "biomarker_type": "nested_complexity",
+ "severity": "medium",
+ "function_name": "run",
+ "line_start": 10,
+ "line_end": 90,
+ "details": {},
+ "health_impact": 1.1,
+ "reason": "run nests 4 levels deep",
+ },
+ ],
+ )
+ return rid
+
+
+async def test_primary_biomarker_prefers_a_discrete_cause(setup_mcp, gradient_health_data):
+ """The headline must say why *this* file, not what is true of every file.
+
+ ``coverage_gradient`` is a continuous deduction — it fires on every file
+ that has coverage data at all — so on a repo with coverage it wins the
+ max-impact tiebreak nearly everywhere. Measured on the live index before
+ this change it led 22 of the top 50 ``worst_files`` and 14 of the top 50
+ ``high_leverage_files``; after, it leads none of either. Its magnitude is
+ real and still counted in ``total_deduction``; it just stops being the
+ answer to "why this file".
+ """
+ from repowise.server.mcp_server import get_health
+
+ row = (await get_health(targets=["src/wide.py"]))["metrics"][0]
+ assert row["primary_biomarker"] == "nested_complexity"
+ assert row["primary_reason"] == "run nests 4 levels deep"
+ # The gradient is still the larger deduction and is still summed in.
+ assert row["total_deduction"] == pytest.approx(3.9)
+ dash = await get_health()
+ worst = next(m for m in dash["worst_files"] if m["file_path"] == "src/wide.py")
+ assert worst["primary_biomarker"] == "nested_complexity"
+
+
+async def test_a_gradient_only_file_still_leads_with_the_gradient(setup_mcp, session, populated_db):
+ """Preferring discrete must not blank the headline when there is nothing else."""
+ from repowise.core.persistence.crud import save_health_findings, save_health_metrics
+ from repowise.server.mcp_server import get_health
+
+ await save_health_metrics(
+ session,
+ populated_db,
+ [{"file_path": "src/only.py", "score": 6.0, "max_ccn": 2, "max_nesting": 1, "nloc": 80}],
+ )
+ await save_health_findings(
+ session,
+ populated_db,
+ [
+ {
+ "file_path": "src/only.py",
+ "biomarker_type": "coverage_gradient",
+ "severity": "medium",
+ "function_name": None,
+ "line_start": None,
+ "line_end": None,
+ "details": {},
+ "health_impact": 2.0,
+ "reason": "50% of lines uncovered",
+ }
+ ],
+ )
+ row = (await get_health(targets=["src/only.py"]))["metrics"][0]
+ assert row["primary_biomarker"] == "coverage_gradient"
+
+
+async def test_kpis_report_how_much_of_the_headline_is_non_code(setup_mcp, session, populated_db):
+ """Markdown and JSON rows score a mechanical 10.0 and lift the average.
+
+ No biomarker walks a non-code file, so its 10.0 means "nothing looked at
+ this" — the same fabricated-10.0 problem the perf pillar already surfaces
+ rather than hides. Measured on the live index: 233 of 3,314 rows are
+ non-code, 221 of them score exactly 10.0, and they lift ``average_health``
+ from 7.31 to 7.47, so a repo can raise its score by adding documentation.
+ Surfaced rather than subtracted — ``average_health`` is what the badge, the
+ snapshots and the web UI read, and redefining it here alone would make this
+ tool disagree with all of them.
+ """
+ from repowise.core.persistence.crud import save_health_metrics
+ from repowise.server.mcp_server import get_health
+
+ await save_health_metrics(
+ session,
+ populated_db,
+ [
+ {"file_path": "src/auth/service.py", "score": 4.0, "nloc": 100, "max_ccn": 9},
+ # No graph node → no language → not in LANGUAGE_MAPS → non-code.
+ {"file_path": "docs/CHANGELOG.md", "score": 10.0, "nloc": 100, "max_ccn": 0},
+ ],
+ )
+ kpis = (await get_health())["kpis"]
+ assert kpis["file_count"] == 2
+ assert kpis["non_code_files"] == 1
+ assert kpis["average_health"] == 7.0
+ assert kpis["average_health_code_only"] == 4.0
+
+
+async def test_non_code_split_is_gated_on_the_language_read(setup_mcp, health_data):
+ """The split rides the language map ``kpis`` already reads — it adds no query.
+
+ So it appears only where that read happens: dashboard mode with ``kpis``
+ surviving the projection. ``only=["directive"]`` stays the cheapest useful
+ call, and targeted mode (which serves no ``kpis`` block at all) is unchanged.
+ """
+ from repowise.server.mcp_server import get_health
+
+ assert "kpis" not in await get_health(targets=["src/auth/service.py"])
+ assert "kpis" not in await get_health(only=["directive"])
+ assert "non_code_files" in (await get_health())["kpis"]
+
+
+async def test_response_is_trimmed_under_the_host_result_cap(setup_mcp, health_data, monkeypatch):
+ """Five ranked lists at the default limit compose past the host's cap.
+
+ Past ``MAX_MCP_OUTPUT_TOKENS`` the host *rejects* the whole result with an
+ isError — the agent loses the answer entirely — so per-list caps that are
+ each reasonable are not enough; something has to bound the sum. Measured on
+ the live index at ``limit=50, include=['refactoring']``: 60,299 chars before
+ the guard, trimmed to fit after, with every cut named.
+ """
+ from repowise.server.mcp_server import get_health
+
+ baseline = len(json.dumps(await get_health(), default=str))
+ monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", "900") # 900 * 0.6 * 4 = 2160 chars
+ result = await get_health()
+ assert len(json.dumps(result, default=str)) <= 2160 < baseline
+ dropped = result["_meta"]["truncated_to_fit"]
+ assert dropped, "the guard must say what it cut"
+ assert set(dropped) <= {
+ "refactoring_plans",
+ "high_leverage_files",
+ "worst_files",
+ "test_findings",
+ "top_findings",
+ "findings",
+ "churn_complexity",
+ "modules",
+ }
+ assert "truncated_recovery" in result["_meta"]
+
+
+async def test_a_response_that_fits_is_not_trimmed(setup_mcp, health_data):
+ """No trim, no marker — the guard must be invisible on every normal call."""
+ from repowise.server.mcp_server import get_health
+
+ meta = (await get_health(include=["refactoring"]))["_meta"]
+ assert "truncated_to_fit" not in meta
+ assert "truncated_recovery" not in meta
+
+
+async def test_trimming_never_eats_the_directive_or_the_totals(
+ setup_mcp, health_data, monkeypatch
+):
+ """The blocks that let a caller recover must survive the cut that caused it."""
+ from repowise.server.mcp_server import get_health
+
+ # Small enough that the guard exhausts every trimmable list and stops.
+ monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", "400")
+ result = await get_health()
+ assert all(result[k] == [] for k in ("worst_files", "top_findings", "high_leverage_files"))
+ assert result["directive"]["fix_first"]
+ # Totals describe what was there before the trim, so the loss stays visible.
+ assert result["worst_files_total"] == 2
+ assert result["mode"] == "dashboard"
+
+
+async def test_meta_reports_the_commit_health_was_scored_at(setup_mcp, session, populated_db):
+ """``indexed_commit`` describes the index; health is a separate pass.
+
+ A response could show a current index beside scores computed several commits
+ earlier and look entirely fresh. ``health_analyzed_at`` said *when*; nothing
+ said *which commit*.
+ """
+ from repowise.core.persistence.crud import save_health_metrics
+ from repowise.server.mcp_server import get_health
+
+ await save_health_metrics(
+ session,
+ populated_db,
+ [{"file_path": "src/auth/service.py", "score": 4.0, "nloc": 100, "max_ccn": 9}],
+ analyzed_commit="c" * 40,
+ )
+ meta = (await get_health())["_meta"]
+ assert meta["health_analyzed_commit"] == "c" * 12
+ # One pass, one commit — no need to warn about a mixed table.
+ assert "health_analyzed_commits_distinct" not in meta
+
+
+async def test_meta_admits_when_the_table_holds_two_scoring_passes(
+ setup_mcp, session, populated_db
+):
+ """The incremental path rewrites only changed files, so the table can be mixed.
+
+ Reporting one SHA for all of it would be a claim the read cannot support —
+ which is why the column is per row rather than per repo.
+ """
+ from repowise.core.persistence.crud import save_health_metrics, upsert_health_metrics
+ from repowise.server.mcp_server import get_health
+
+ await save_health_metrics(
+ session,
+ populated_db,
+ [
+ {"file_path": "src/auth/service.py", "score": 4.0, "nloc": 100, "max_ccn": 9},
+ {"file_path": "src/db/models.py", "score": 9.0, "nloc": 50, "max_ccn": 2},
+ ],
+ analyzed_commit="a" * 40,
+ )
+ await upsert_health_metrics(
+ session,
+ populated_db,
+ [{"file_path": "src/auth/service.py", "score": 3.0, "nloc": 100, "max_ccn": 9}],
+ analyzed_commit="b" * 40,
+ )
+ meta = (await get_health())["_meta"]
+ assert meta["health_analyzed_commit"] == "b" * 12 # the newest pass
+ assert meta["health_analyzed_commits_distinct"] == 2
+
+
+async def test_an_unstamped_upsert_does_not_erase_an_existing_commit(
+ setup_mcp, session, populated_db
+):
+ """A caller that does not track the sha must not wipe one that does."""
+ from repowise.core.persistence.crud import save_health_metrics, upsert_health_metrics
+ from repowise.server.mcp_server import get_health
+
+ await save_health_metrics(
+ session,
+ populated_db,
+ [{"file_path": "src/auth/service.py", "score": 4.0, "nloc": 100, "max_ccn": 9}],
+ analyzed_commit="a" * 40,
+ )
+ await upsert_health_metrics(
+ session,
+ populated_db,
+ [{"file_path": "src/auth/service.py", "score": 3.0, "nloc": 100, "max_ccn": 9}],
+ )
+ assert (await get_health())["_meta"]["health_analyzed_commit"] == "a" * 12
+
+
+async def test_meta_omits_the_commit_when_no_row_records_one(setup_mcp, health_data):
+ """NULL reads as "not recorded", never as "current"."""
+ from repowise.server.mcp_server import get_health
+
+ meta = (await get_health())["_meta"]
+ assert "health_analyzed_commit" not in meta
+ assert isinstance(meta["health_analyzed_at"], str)
+
+
+def test_only_docstring_does_not_overclaim_the_aliases():
+ """The docstring listed the ``include`` names as ``only`` aliases. Three are.
+
+ ``performance`` / ``defect`` / ``maintainability`` are dimension filters with
+ no top-level key, so they land in ``unknown_only_keys`` — a caller typing one
+ out of the docstring gets an empty projection and no explanation.
+ """
+ from repowise.server.mcp_server.tool_health import _ONLY_ALIASES, get_health
+
+ doc = get_health.__doc__ or ""
+ only_section = doc.split("only:", 1)[1].split("repo:", 1)[0]
+ assert set(_ONLY_ALIASES) == {"biomarkers", "accuracy", "refactoring"}
+ for name in _ONLY_ALIASES:
+ assert name in only_section
+ # And it says plainly that the dimension names are not aliases.
+ for name in ("performance", "defect", "maintainability"):
+ assert name in only_section
+ assert "do not" in only_section
+
+
+async def test_trimming_takes_from_the_longest_list_first(setup_mcp, health_data, monkeypatch):
+ """The cut has to land on whichever block is actually responsible.
+
+ Trimming a fixed victim would hold the payload down just as well and be
+ wrong about *why* it was over: on this fixture ``top_findings`` (4 rows) is
+ twice ``worst_files`` (2) and four times ``high_leverage_files`` (1), so a
+ small overflow must come out of ``top_findings`` and leave the one-row list
+ whole. (Found by mutation testing — the first version of this guard passed
+ every test with a fixed trim order.)
+ """
+ from repowise.server.mcp_server import get_health
+
+ baseline = await get_health()
+ size = len(json.dumps(baseline, default=str))
+ assert len(baseline["top_findings"]) == 4
+ # Budget = current size minus roughly one finding, plus the marker headroom
+ # the guard reserves, so exactly a row or two has to go.
+ per_row = len(json.dumps(baseline["top_findings"], default=str)) // 4
+ monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", str(int((size - per_row + 400) / 4 / 0.6)))
+ result = await get_health()
+ dropped = result["_meta"]["truncated_to_fit"]
+ assert set(dropped) == {"top_findings"}
+ assert len(result["high_leverage_files"]) == 1
+ assert len(result["worst_files"]) == 2
+
+
+async def test_guard_trims_the_uncapped_targeted_lists(setup_mcp, health_data, monkeypatch):
+ """The three lists that can actually run away are ``limit``-free.
+
+ Found in adversarial review, and it is the defect the guard was most likely
+ to have: the first ``_TRIMMABLE_LISTS`` held only the eight *capped*
+ dashboard blocks — the ones least able to overflow — while ``metrics``,
+ ``trends`` and ``coverage.files`` were invisible to it. Those three are
+ built per target with no cap (a ``module:`` target expands to every file in
+ the module) and targeted ``coverage.files`` carries the per-line
+ ``covered_lines`` arrays dashboard mode declines to read. A guard that
+ misses them is worse than none: it trims a small capped list to empty, still
+ overflows, and stamps ``truncated_to_fit`` claiming it handled it.
+ """
+ from repowise.server.mcp_server import get_health
+
+ targets = ["src/auth/service.py", "src/db/models.py"]
+ baseline = await get_health(targets=targets)
+ assert len(baseline["metrics"]) == 2
+ assert baseline["metrics_total"] == 2
+
+ monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", "400")
+ result = await get_health(targets=targets)
+ assert result["_meta"]["truncated_to_fit"].get("metrics"), (
+ "metrics is uncapped by limit, so the size guard is the only thing "
+ "bounding it — it must be reachable"
+ )
+ assert len(result["metrics"]) < 2
+ # The total still describes what was there, so the trim stays visible.
+ assert result["metrics_total"] == 2
+
+
+async def test_guard_reaches_a_list_nested_one_level_down(setup_mcp, health_data, monkeypatch):
+ """``coverage.files`` is not a top-level key; a flat scan never finds it."""
+ from repowise.server.mcp_server import get_health
+
+ monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", "400")
+ result = await get_health(include=["coverage"])
+ # Whatever else it cut, it must not have stopped at the top level while a
+ # nested list still held rows.
+ assert result["_meta"]["truncated_to_fit"]
+ from repowise.server.mcp_server.tool_health import _TRIMMABLE_LISTS, _resolve_list
+
+ assert "coverage.files" in _TRIMMABLE_LISTS
+ assert "trends" in _TRIMMABLE_LISTS
+ assert _resolve_list({"coverage": {"files": [1, 2]}}, "coverage.files") == [1, 2]
+ assert _resolve_list({"coverage": {"files": []}}, "coverage.files") is None
+ assert _resolve_list({}, "coverage.files") is None
+ assert _resolve_list({"coverage": None}, "coverage.files") is None
diff --git a/tests/unit/server/mcp/test_meta_freshness.py b/tests/unit/server/mcp/test_meta_freshness.py
index 71f4dd9d7..5d0ebe648 100644
--- a/tests/unit/server/mcp/test_meta_freshness.py
+++ b/tests/unit/server/mcp/test_meta_freshness.py
@@ -78,6 +78,66 @@ def test_empty_targets_means_nothing_served_and_never_warns(tmp_path, monkeypatc
assert out.get("index_behind") is True
+def test_no_targets_with_zero_changed_files_does_not_warn(tmp_path, monkeypatch):
+ """HEAD moved but the trees are identical — nothing anywhere can be stale.
+
+ Regression (N4): a repo-level response took the "no targets" branch before
+ ever asking git *what* changed, so an empty commit (or a merge that changed
+ nothing) produced ``stale_warning`` on a repo that was completely current.
+ A warning that fires when zero files changed is the loudest possible way to
+ be wrong, and it trains an agent to stop reading the field.
+ """
+ monkeypatch.setattr(_meta, "_read_live_head", lambda p: _LIVE)
+ _prime(tmp_path, frozenset())
+ out = _meta.freshness_from_repo(_repo(tmp_path), targets=None)
+ assert "stale_warning" not in out
+ assert out.get("index_behind") is True
+ assert out.get("live_head") == _LIVE[:12]
+
+
+def test_no_targets_with_real_changes_still_warns(tmp_path, monkeypatch):
+ """The zero-change carve-out must not silence a genuinely behind index."""
+ monkeypatch.setattr(_meta, "_read_live_head", lambda p: _LIVE)
+ _prime(tmp_path, frozenset({"src/a.py"}))
+ out = _meta.freshness_from_repo(_repo(tmp_path), targets=None)
+ assert "stale_warning" in out
+ assert "index_behind" not in out
+
+
+def test_empty_commit_over_real_git_is_not_stale(tmp_path):
+ """End to end against git, since the carve-out turns on a real empty diff."""
+
+ def git(*args):
+ subprocess.run(
+ ["git", "-C", str(tmp_path), *args], check=True, capture_output=True, text=True
+ )
+
+ def sha():
+ return subprocess.run(
+ ["git", "-C", str(tmp_path), "rev-parse", "HEAD"],
+ check=True,
+ capture_output=True,
+ text=True,
+ ).stdout.strip()
+
+ git("init", "-q")
+ git("config", "user.email", "[email protected]")
+ git("config", "user.name", "t")
+ (tmp_path / "a.py").write_text("x = 1\n", encoding="utf-8")
+ git("add", ".")
+ git("commit", "-qm", "one")
+ indexed = sha()
+ git("commit", "-q", "--allow-empty", "-m", "empty")
+ live = sha()
+
+ assert live != indexed
+ assert _meta._changed_files_between(str(tmp_path), indexed, live) == frozenset()
+ repo = types.SimpleNamespace(updated_at=None, local_path=str(tmp_path), head_commit=indexed)
+ out = _meta.freshness_from_repo(repo, targets=None)
+ assert "stale_warning" not in out
+ assert out.get("index_behind") is True
+
+
def test_git_diff_failure_falls_back_to_repo_level_warning(tmp_path, monkeypatch):
monkeypatch.setattr(_meta, "_read_live_head", lambda p: _LIVE)
_prime(tmp_path, None) # git couldn't answer (rebased-away SHA, timeout)