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): treat tree-sitter query and history-tier files as what they are (#3723)
Swati Ahujae167bc570312
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex cf72f1cd8..65df2eac6 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -215,6 +215,7 @@ Per file:| owners, reviewers | Primary owner (`primary_owner`) and the owner clause in `risk_summary` are unconditional; detailed owner metrics (`owner_pct`, `owner_line_pct`, `recent_owner`, `recent_owner_pct`, `bus_factor`, `contributor_count`) are opt-in under `include=["owners"]`; recommended reviewers stay in PR mode || test gaps, `security_signals` | Test coverage gaps and security findings for the file || `resolved`, `unresolved_reason` | A target naming no indexed file: `unsupported_target_kind` (a `module:` id), `directory`, `not_indexed`, `no_such_path`. Counts are omitted, never zeroed |+| `signal_tier`, `signal_tier_reason` | `"history"` on a file indexed for commit history only (docs, config, query and other non-code files): the card carries commit counts, `last_commit_at`, `trend`, owner and `security_signals`, and omits hotspot, co-change, dependents and classification rather than zeroing them |Opt-in blocks: `owners` adds `owner_pct`, `owner_line_pct`, `recent_owner`, `recent_owner_pct`, `bus_factor` and `contributor_count`. `tests` adds the PR directive's typed `test_recommendations`, and `blast` adds `pr_blast_radius`, the PR dossier behind the directive (transitive files, co-change warnings, test gaps, the structural score; reviewers stay in the directive). `graph` adds typed `dependents` (direct versus transitive), `consumers` (typed contract consumers only), `cross_repo_links`, `impact_surface` and `direct_risks`, with `relationship_analysis` distinguishing an empty analysis from an unavailable or partial one. `churn` adds `change_magnitude`, `risk_type` and `change_pattern`. `scales` adds the unit, range and calibration of every scalar; it is identical on every call, so ask once. A multi-target call also carries `global_hotspots`.@@ -259,7 +260,7 @@ Every float is rounded to 4 significant digits. Direct rows' `structural_score``include=["diagnostics"]` adds `score` (the raw 0 to 10 number), `fallback_band`, `risk_authority`, `score_measures`, `score_unit`, `baseline_sample_size`, `features` and `drivers`, plus `health_delta.analyzer` (analyzer and rules fingerprint), `health_delta.base` and `health_delta.head` (the two resolved revisions) and `health_delta.limits`. `include=["scales"]` adds each field's unit, range and calibration.-**health_delta.** Both revisions are analysed from their own content, and a finding at head is reported only when the diff explains it. `scope` counts changed, eligible, analysed, skipped and failed files; `status` is `available`, `partial` or `unavailable`, and `partial` is never a clean bill. Documentation and configuration files (Markdown, JSON, YAML, TOML and the other doc or config extensions) are skipped with reason `not_code` and never make a run `partial`; a change made only of them reads `clear_in_analyzed_scope` with a headline saying health analysis does not cover them. HTML, schema and other files with no health dialect still make a run `partial`. `introduced`, `worsened` and `resolved` are totals; `top_findings` holds the three most actionable, with `findings_total`. Each finding names `dimension`, `biomarker`, `severity`, `path`, `symbol`, head-side `lines`, a `reason`, and an `attribution` (`basis` of `added_lines`, `changed_symbol`, `changed_call_edge`, `new_file`, `file_change`, `context_change` or `unknown`, with a `confidence`). Identity ignores line numbers, so moved code introduces nothing. `inspect` gives the `finding_id` call that expands one; ids are bound to the two revisions. A finding that matches a stored one carries `health_reference` for `get_health(finding_id=...)`. Performance findings carry `opportunity_id` and are ordered by opportunity rank.+**health_delta.** Both revisions are analysed from their own content, and a finding at head is reported only when the diff explains it. `scope` counts changed, eligible, analysed, skipped and failed files; `status` is `available`, `partial` or `unavailable`, and `partial` is never a clean bill. Documentation and configuration files (Markdown, JSON, YAML, TOML and the other doc or config extensions) are skipped with reason `not_code` and never make a run `partial`; a change made only of them reads `clear_in_analyzed_scope` with a headline saying health analysis does not cover them. Tree-sitter query files (`.scm` under a `queries` directory) are skipped with reason `not_analyzable_data`, which also never makes a run `partial`; a change made only of them reads `clear_in_analyzed_scope` with its own headline, since they can still change behaviour. HTML, schema and other files with no health dialect still make a run `partial`. `introduced`, `worsened` and `resolved` are totals; `top_findings` holds the three most actionable, with `findings_total`. Each finding names `dimension`, `biomarker`, `severity`, `path`, `symbol`, head-side `lines`, a `reason`, and an `attribution` (`basis` of `added_lines`, `changed_symbol`, `changed_call_edge`, `new_file`, `file_change`, `context_change` or `unknown`, with a `confidence`). Identity ignores line numbers, so moved code introduces nothing. `inspect` gives the `finding_id` call that expands one; ids are bound to the two revisions. A finding that matches a stored one carries `health_reference` for `get_health(finding_id=...)`. Performance findings carry `opportunity_id` and are ordered by opportunity rank.**impacted_tests.** The same selection `repowise impacted-tests` makes over the whole change (every touched path, whatever the score's filters). `status` is `selected` or `run_all` (or `no_index`, `unknown`, `config_invalid`, `timeout`, `busy`, `no_source_line_changes` when nothing was selected, each with `run_all` true; `timeout` means the selection took over 30 seconds and `busy` that one for this repository is still running, and `repowise impacted-tests` gives the answer); `run_all` true means no subset can be vouched for, with up to three `reasons` (`reasons_total` counts them all). `tests_to_run` (capped at ten, `total` and `truncated`) is in `repowise impacted-tests`' [run order](CLI_REFERENCE.md#repowise-impacted-tests-revspec), the `always_run_total` tests that run with every subset last; `why` gives each listed file's reason. With `run_all` the list is what to run first. `tests_to_run_kind` is `test_id` when a coverage node id is listed, else `test_file`. `basis` is `measured` when coverage decided a changed file, `inferred` when only the graph or a rule did, `none` when nothing named a test; `basis_by_file` names the evidence per changed file (`coverage`, `changed-test`, `call-graph`, `import-graph`, `conftest`, `full-run`, `no-tests-needed`, ...). With a coverage map, `map_present` is true and `line_coverage` buckets the scored files' changed lines, matched on the side of the diff the map was measured at (by file when it was measured at neither): `untested_changes`, `stale_test_candidates` (covered lines whose test file is absent from the diff), `covered`, `no_coverage_data`. Build the measured map with `coverage run --contexts=test` and `repowise coverage add`.diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd.py b/packages/cli/src/repowise/cli/commands/risk_cmd.pyindex f651bb954..19c7aa286 100644--- a/packages/cli/src/repowise/cli/commands/risk_cmd.py+++ b/packages/cli/src/repowise/cli/commands/risk_cmd.py@@ -234,13 +234,22 @@ def _render_card(name: str, card: dict) -> None:console.print(f" [dim]unresolved: {reason}[/dim]")returntrend = card.get("trend") or "unknown"- console.print(- f" [dim]hotspot {float(card.get('hotspot_score') or 0.0):.0%} ({trend}) · "- f"{card.get('dependents_count', 0)} direct dependents · "- f"{card.get('risk_type', 'unknown')} · owned "- f"{_ta.owner_share(card.get('owner_pct'))} by "- f"{escape(str(card.get('primary_owner') or 'unknown'))}[/dim]"- )+ if card.get("signal_tier") == "history":+ # Nothing measured a hotspot, dependents or classification for this file.+ last = str(card.get("last_commit_at") or "unknown")[:10]+ console.print(+ f" [dim]history only · {card.get('commit_count_total', 0)} commits ({trend}) · "+ f"last {escape(last)} · owned {_ta.owner_share(card.get('owner_pct'))} by "+ f"{escape(str(card.get('primary_owner') or 'unknown'))}[/dim]"+ )+ else:+ console.print(+ f" [dim]hotspot {float(card.get('hotspot_score') or 0.0):.0%} ({trend}) · "+ f"{card.get('dependents_count', 0)} direct dependents · "+ f"{card.get('risk_type', 'unknown')} · owned "+ f"{_ta.owner_share(card.get('owner_pct'))} by "+ f"{escape(str(card.get('primary_owner') or 'unknown'))}[/dim]"+ )# Kept in the projection, so each owes a line here: a key kept in the# payload that no renderer prints is the second silent failure mode of a# trim, and the one a projection test cannot see.diff --git a/packages/core/src/repowise/core/analysis/change_health/models.py b/packages/core/src/repowise/core/analysis/change_health/models.pyindex e709c81a0..2de2b8cbf 100644--- a/packages/core/src/repowise/core/analysis/change_health/models.py+++ b/packages/core/src/repowise/core/analysis/change_health/models.py@@ -46,10 +46,18 @@ SEVERITY_RANK: dict[str, int] = {"low": 0, "medium": 1, "high": 2, "critical": 3#: Documentation or configuration: skipped, but no code went unexamined.NOT_CODE = "not_code"+#: Tree-sitter queries and similar data: no detector reads them, yet they can+#: change behaviour, so they are named apart from docs and config.+NOT_ANALYZABLE_DATA = "not_analyzable_data"++#: Skip reasons that leave no code unexamined.+NO_CODE_GAP = frozenset({NOT_CODE, NOT_ANALYZABLE_DATA})+#: Why a changed file produced no comparison. Kept per file so a partial run#: can never render as a clean one.SkipReason = Literal["not_code",+ "not_analyzable_data","unsupported_language","generated","binary",@@ -171,7 +179,7 @@ class ChangeHealthDelta:resolved_total: int = 0unchanged_total: int = 0uncertain_total: int = 0- #: ``{path: reason}``. Any reason but ``not_code`` means the run was partial.+ #: ``{path: reason}``. Any reason outside ``NO_CODE_GAP`` means the run was partial.skipped: dict[str, str] = field(default_factory=dict)timing_ms: float = 0.0cache_hit: bool = False@@ -188,7 +196,7 @@ class ChangeHealthDelta:@propertydef code_skipped(self) -> dict[str, str]:"""Skipped files that may hold code, so their absence leaves a gap."""- return {p: r for p, r in self.skipped.items() if r != NOT_CODE}+ return {p: r for p, r in self.skipped.items() if r not in NO_CODE_GAP}@propertydef is_clean(self) -> bool:diff --git a/packages/core/src/repowise/core/analysis/change_health/service.py b/packages/core/src/repowise/core/analysis/change_health/service.pyindex 114ef58fb..cebaf3d9a 100644--- a/packages/core/src/repowise/core/analysis/change_health/service.py+++ b/packages/core/src/repowise/core/analysis/change_health/service.py@@ -12,6 +12,7 @@ import threadingimport timefrom collections import OrderedDictfrom dataclasses import dataclass+from pathlib import PurePosixPathfrom ...support_paths import is_doc_or_config_pathfrom ...test_paths import is_test_related_path@@ -24,6 +25,8 @@ from .attribution import FindingAttributor, changed_symbols_forfrom .identity import change_finding_id, finding_key, severity_rankfrom .matcher import FindingMatcher, MatchedFindingfrom .models import (+ NO_CODE_GAP,+ NOT_ANALYZABLE_DATA,NOT_CODE,AnalysisFingerprint,ChangeFinding,@@ -47,6 +50,12 @@ MAX_CHANGED_FILES = 300#: dialect (HTML, schemas, shell) may carry logic, so it stays a gap._NOT_CODE_LANGUAGES = frozenset({"json", "yaml", "toml", "markdown"})+#: Tree-sitter query files: patterns no health detector reads. ``.scm`` is also+#: Scheme source, so only the tree-sitter layout (a ``queries`` directory)+#: counts; any other ``.scm`` stays a gap.+_QUERY_SUFFIX = ".scm"+_QUERY_DIR = "queries"+#: Comparisons kept in the process cache._CACHE_CAPACITY = 32@@ -218,19 +227,10 @@ class ChangeHealthDeltaService:basis = "both_sides_analyzed"if not eligible:- if not changes:- explanation = "This change touches no files."- elif all(r == NOT_CODE for r in skipped.values()):- explanation = (- "Only documentation or configuration files changed; "- "health analysis does not cover them."- )- else:- explanation = "No changed file is health-analyzable, so nothing was compared."delta = ChangeHealthDelta(# Nothing was compared either way, so neither case is a clean bill.status="unavailable",- explanation=explanation,+ explanation=_nothing_compared(changes, skipped),base=base_id,head=head_id,comparison_basis=basis,@@ -392,6 +392,20 @@ def _filter(changes: list[FileChange], request: DeltaRequest) -> list[FileChange)+def _nothing_compared(changes: list[FileChange], skipped: dict[str, str]) -> str:+ """Why no changed file reached the analyzer, for the explanation."""+ if not changes:+ return "This change touches no files."+ if all(r == NOT_CODE for r in skipped.values()):+ return (+ "Only documentation or configuration files changed; "+ "health analysis does not cover them."+ )+ if all(r in NO_CODE_GAP for r in skipped.values()):+ return "Only query or other data files changed; health analysis does not cover them."+ return "No changed file is health-analyzable, so nothing was compared."++def _skip_reason(change: FileChange) -> str:"""Why a changed path never reached the analyzer."""if change.head_path is None:@@ -400,6 +414,9 @@ def _skip_reason(change: FileChange) -> str:if language in _NOT_CODE_LANGUAGES or is_doc_or_config_path(change.head_path):return NOT_CODEif language is None:+ path = PurePosixPath(change.head_path)+ if path.suffix.lower() == _QUERY_SUFFIX and _QUERY_DIR in path.parts[:-1]:+ return NOT_ANALYZABLE_DATAreturn "unsupported_language"return "not_health_analyzable"@@ -413,7 +430,7 @@ def _status_for(f"{'file' if scope.changed == 1 else 'files'} could be analysed.")# Docs, config and data hold no code, so skipping them leaves nothing unexamined.- code_skipped = sum(1 for r in skipped.values() if r != NOT_CODE)+ code_skipped = sum(1 for r in skipped.values() if r not in NO_CODE_GAP)if code_skipped or scope.failed:return ("partial",diff --git a/packages/core/src/repowise/core/analysis/decisions/rationale_comments.py b/packages/core/src/repowise/core/analysis/decisions/rationale_comments.pyindex 4326d0466..aa95bddaf 100644--- a/packages/core/src/repowise/core/analysis/decisions/rationale_comments.py+++ b/packages/core/src/repowise/core/analysis/decisions/rationale_comments.py@@ -183,6 +183,8 @@ LINE_PREFIXES: dict[str, tuple[str, ...]] = {"lua": ("--",),"hs": ("--",),"elm": ("--",),+ # Tree-sitter query files (and Scheme). Longest prefix first: ";; x" is common.+ "scm": (";;", ";"),}# Extensions that use C-style /* ... */ block comments.@@ -312,7 +314,7 @@ def _strip_comment_open(stripped: str, prefixes: tuple[str, ...]) -> str | None:# A line that is only a divider rule (``# -------`` / ``// =====`` / ``***``).# These delimit comment runs and must never be glued into the rationale text.-_SEPARATOR_CHARS = frozenset("-=*~_#/+.<> ")+_SEPARATOR_CHARS = frozenset("-=*~_#/+.<>; ")def _is_separator(body: str) -> bool:diff --git a/packages/core/src/repowise/core/analysis/review_directive.py b/packages/core/src/repowise/core/analysis/review_directive.pyindex ed4399272..6b3200e68 100644--- a/packages/core/src/repowise/core/analysis/review_directive.py+++ b/packages/core/src/repowise/core/analysis/review_directive.py@@ -15,7 +15,7 @@ import hashlibfrom dataclasses import dataclassfrom typing import Literal-from .change_health.models import ChangeHealthDelta+from .change_health.models import NOT_ANALYZABLE_DATA, ChangeHealthDeltafrom .health.scoring import ADVISORY_DIMENSION#: How much of a lane's evidence was actually computed.@@ -120,14 +120,21 @@ def _plural(word: str, count: int) -> str:return word if count == 1 else f"{word}s"-def _verdict(delta: ChangeHealthDelta) -> tuple[ReviewStatus, str, EvidenceState]:- if delta.status == "unavailable" and delta.skipped and not delta.code_skipped:+def _no_code_headline(delta: ChangeHealthDelta) -> str:+ if NOT_ANALYZABLE_DATA in delta.skipped.values():return (- "clear_in_analyzed_scope",- "No code changed: only documentation or configuration files; "- "health analysis does not cover them.",- "available",+ "No code changed: only query or other data files, which health analysis "+ "does not cover. They can still change behaviour, so test selection still applies.")+ return (+ "No code changed: only documentation or configuration files; "+ "health analysis does not cover them."+ )+++def _verdict(delta: ChangeHealthDelta) -> tuple[ReviewStatus, str, EvidenceState]:+ if delta.status == "unavailable" and delta.skipped and not delta.code_skipped:+ return "clear_in_analyzed_scope", _no_code_headline(delta), "available"if delta.status in _NOT_COMPARED:return "unknown", f"Change health could not be compared: {delta.explanation}", "unavailable"if delta.status in _UNTRUSTWORTHY:diff --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 6bc583134..86c7e01ba 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@@ -434,6 +434,47 @@ async def _unresolved_reason(return {"unresolved_reason": "no_such_path", **hint}+def _history_tier_card(target: str, meta: Any, security_signals: list[dict]) -> dict:+ """The card for a file indexed at the history tier (``meta.history_only``).++ A non-code file keeps commit counts, windows and authorship, but no churn+ percentile, hotspot flag, co-change partners or fix rollup, so the scored+ card would print zeros nothing measured. This one carries only what was.+ """+ commits = meta.commit_count_total or 0+ last = meta.last_commit_at.isoformat() if meta.last_commit_at else None+ owner = meta.primary_owner_name or "unknown"+ pct = meta.primary_owner_commit_pct or 0.0+ return {+ "target": target,+ "signal_tier": "history",+ "signal_tier_reason": (+ "not a parsed code file: only commit history is indexed, so hotspot, "+ "co-change and risk classification do not apply"+ ),+ "commit_count_total": commits,+ "commit_count_90d": meta.commit_count_90d or 0,+ "last_commit_at": last,+ "trend": _compute_trend(meta),+ "primary_owner": owner,+ "owner_pct": pct,+ "contributor_count": meta.contributor_count or 0,+ "security_signals": security_signals,+ # Workspace enrichment adds its rows here; co-change covers code files only.+ "relationship_analysis": {+ "co_change": {+ "status": "unavailable",+ "scope": "git_history",+ "reason": "history-tier file",+ }+ },+ "risk_summary": (+ f"{target}: history only, {commits} commits, last {last[:10] if last else 'unknown'}, "+ f"{_owner_clause(owner, pct, None)}"+ ),+ }++async def _assess_one_target(session: AsyncSession,repository: Repository,@@ -588,6 +629,10 @@ async def _assess_one_target(),}+ if getattr(meta, "history_only", False) is True:+ security = await _get_security_signals(session, repo_id, lookup_path)+ return _history_tier_card(target, meta, security)+if meta is None:result_data["hotspot_score"] = 0.0result_data["is_hotspot"] = Falsediff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.pyindex e7cbe87b8..509deaba6 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py@@ -629,8 +629,8 @@ def _build_pr_directive(# response carries an expandable [repowise#<ref>] marker for it.for r in response["targets"].values():# The counts below would be the structural zeros get_risk stopped- # emitting for a card that resolved nothing.- if r.get("resolved") is False:+ # emitting for a card that resolved nothing or holds history only.+ if r.get("resolved") is False or r.get("signal_tier") == "history":continuepartners = r.get("co_change_partners") or []if len(partners) > 3:diff --git a/tests/unit/analysis/test_decision_rationale_comments.py b/tests/unit/analysis/test_decision_rationale_comments.pyindex 7f7751528..7f7474677 100644--- a/tests/unit/analysis/test_decision_rationale_comments.py+++ b/tests/unit/analysis/test_decision_rationale_comments.py@@ -62,6 +62,18 @@ def test_extract_comment_blocks_handles_c_style_and_returns_empty_for_unknown():assert extract_comment_blocks("plain prose because yes", "txt") == []+def test_tree_sitter_query_comments_are_mined():+ scm = (+ ";;;;;;;;;;;;;;;;\n"+ ";; The receiver stays uncaptured because a qualified super call\n"+ "; binds to the parent class, not the field.\n"+ "(method_invocation name: (identifier) @call.target) @call.site\n"+ )+ blocks = extract_comment_blocks(scm, "scm")+ assert blocks[0].text.startswith("The receiver stays uncaptured")+ assert harvest_file_rationale(scm, "scm")++# ---------------------------------------------------------------------------# Guardrails# ---------------------------------------------------------------------------diff --git a/tests/unit/analysis/test_review_directive.py b/tests/unit/analysis/test_review_directive.pyindex 4a918b640..330abe856 100644--- a/tests/unit/analysis/test_review_directive.py+++ b/tests/unit/analysis/test_review_directive.py@@ -137,6 +137,16 @@ def test_an_unsupported_code_file_still_leaves_the_verdict_unknown():assert [a.targets for a in directive.actions] == [("lib.ex",)]+def test_a_query_only_change_is_clear_with_its_own_headline():+ delta = _delta(status="unavailable", explanation="Only query files changed")+ delta.skipped = {"queries/java.scm": "not_analyzable_data", "README.md": "not_code"}+ directive = review_directive(delta)+ assert directive.status == "clear_in_analyzed_scope"+ assert "query" in directive.headline+ assert "documentation or configuration" not in directive.headline+ assert not directive.actions++# ---------------------------------------------------------------------------# Actions carry targets, not rendered strings# ---------------------------------------------------------------------------diff --git a/tests/unit/change_health/test_comparison.py b/tests/unit/change_health/test_comparison.pyindex 7064febdb..e162472c2 100644--- a/tests/unit/change_health/test_comparison.py+++ b/tests/unit/change_health/test_comparison.py@@ -598,3 +598,39 @@ def test_the_analyzer_fingerprint_is_reported_on_both_sides(make_repo):assert delta.fingerprint.analyzer_version > 0assert delta.fingerprint.performance_model_version > 0assert delta.comparison_basis == "both_sides_analyzed"+++def test_a_query_file_change_is_data_not_a_gap(make_repo):+ repo = make_repo()+ repo.commit("seed", {"queries/java.scm": "(identifier) @name\n"})+ repo.commit("edit", {"queries/java.scm": "(type_identifier) @name\n"})++ delta = compare(repo)++ assert delta.status == "unavailable"+ assert delta.skipped == {"queries/java.scm": "not_analyzable_data"}+ assert delta.code_skipped == {}+ assert "query" in delta.explanation+ assert not delta.is_clean+++def test_a_query_file_beside_code_does_not_make_the_run_partial(make_repo):+ repo = make_repo()+ repo.commit("seed", {"app.py": "x = 1\n", "queries/java.scm": "(identifier) @a\n"})+ repo.commit("edit", {"app.py": "x = 2\n", "queries/java.scm": "(identifier) @b\n"})++ delta = compare(repo)++ assert delta.status == "available"+ assert delta.code_skipped == {}+++def test_a_scheme_file_outside_queries_is_still_a_gap(make_repo):+ repo = make_repo()+ repo.commit("seed", {"src/main.scm": "(define (f x) x)\n"})+ repo.commit("edit", {"src/main.scm": "(define (f x) (+ x 1))\n"})++ delta = compare(repo)++ assert delta.skipped == {"src/main.scm": "unsupported_language"}+ assert delta.code_skipped == {"src/main.scm": "unsupported_language"}diff --git a/tests/unit/cli/test_risk_cmd_contract.py b/tests/unit/cli/test_risk_cmd_contract.pyindex ef8b5b872..1d96996d5 100644--- a/tests/unit/cli/test_risk_cmd_contract.py+++ b/tests/unit/cli/test_risk_cmd_contract.py@@ -204,6 +204,32 @@ def test_the_projection_survives_a_payload_with_no_targets_key() -> None:assert project_risk({})["targets"] == {}+def test_a_history_tier_card_prints_its_history_not_hotspot_zeros() -> None:+ from unittest.mock import patch++ from rich.console import Console++ from repowise.cli.commands import risk_cmd++ card = {+ "signal_tier": "history",+ "commit_count_total": 11,+ "last_commit_at": "2026-03-01T00:00:00",+ "trend": "stable",+ "primary_owner": "Carol",+ "owner_pct": 0.5,+ }+ projected = project_risk({"targets": {"queries/java.scm": card}})["targets"]["queries/java.scm"]+ assert projected["signal_tier"] == "history" and projected["commit_count_total"] == 11+ rec = Console(record=True, width=300)+ with patch.object(risk_cmd, "console", rec):+ risk_cmd._render_card("queries/java.scm", projected)+ out = rec.export_text()+ assert "history only · 11 commits (stable) · last 2026-03-01" in out+ assert "Carol" in out+ assert "hotspot" not in out and "direct dependents" not in out++# ---------------------------------------------------------------------------# Errors a caller scripts against# ---------------------------------------------------------------------------diff --git a/tests/unit/server/mcp/test_risk.py b/tests/unit/server/mcp/test_risk.pyindex c9e69e12d..6eb023dd5 100644--- a/tests/unit/server/mcp/test_risk.py+++ b/tests/unit/server/mcp/test_risk.py@@ -1159,3 +1159,48 @@ async def test_get_risk_pr_mode_puts_docs_and_config_cards_last(setup_mcp):files = ["CHANGES.rst", "setup.cfg", "src/auth/service.py"]result = await get_risk(files, changed_files=files)assert next(iter(result["targets"])) == "src/auth/service.py"++[email protected]("path", ["queries/java.scm", "docs/guide.md"])+async def test_get_risk_history_tier_file_omits_unmeasured_signals(setup_mcp, session, path):+ """A history-only row carries commits and owner, never zeros posing as measurements."""+ from datetime import UTC, datetime++ from repowise.core.persistence.models import GitMetadata+ from repowise.server.mcp_server import get_risk++ session.add(+ GitMetadata(+ id=f"gm-history-{path}",+ repository_id=setup_mcp,+ file_path=path,+ history_only=True,+ commit_count_total=11,+ commit_count_90d=4,+ commit_count_30d=1,+ last_commit_at=datetime(2026, 3, 1, tzinfo=UTC),+ primary_owner_name="Carol",+ primary_owner_commit_pct=0.5,+ top_authors_json=json.dumps([{"name": "Carol", "count": 6}]),+ )+ )+ await session.flush()++ for result in (+ await get_risk([path], include=["graph", "churn"]),+ await get_risk([path], changed_files=[path]),+ ):+ card = result["targets"][path]+ assert card["signal_tier"] == "history"+ assert card["commit_count_total"] == 11+ assert card["last_commit_at"].startswith("2026-03-01")+ assert card["primary_owner"] == "Carol"+ for key in ("hotspot_score", "is_hotspot", "co_change_partners", "risk_type"):+ assert key not in card+ assert "co_change_partners_emitted" not in card+ assert "hotspot" not in card["risk_summary"]+ # Detailed owner metrics stay behind include=["owners"], as on a scored card.+ assert "owner_pct" not in card and "contributor_count" not in card+ owners = (await get_risk([path], include=["owners"]))["targets"][path]+ assert owners["owner_pct"] == 0.5