Skip to content

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

feat(suspects): rank path targets by what they name and take a typed symptom over MCP (#4205)

Raghav Chamadiya2d5f8594dce7
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index d44a8e252..25c857a61 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -165,12 +165,13 @@ A triage card for files, modules or symbols: summary, symbols with signatures an
| `include` | list[string] | none | Any of `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `references`, `metrics`, `community`, `decisions`, `skeleton`, `health`, `doc_drift`, `symbols`, `changes`, `provenance`, `suspects` |
| `compact` | bool | `true` | `false` adds the structure block, imports and docstrings |
| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported (returns an error) |
+| `symptom` | string | none | Issue text, an error message or a pasted stack trace for `include=["suspects"]` to rank against, in place of the words in the target paths |
**Key return fields:** `targets` keyed by target, each with title, summary, symbols, `hotspot`, `fix_history` (files with counted bug fixes), `episodes`, decision titles, `file_preview` (for files with no symbols), `resolved_to` (a symbol miss falling back to its file); `dropped_targets` and `recovery` when the budget forced targets out; `_meta.complete` for whole files served.
A `component:<name>` target returns the component's declared context (owner, system, criticality, tags) and `facts` rolled up over its files: health, hotspots, bus factor, test reach and dead code, each with a `basis` (`measured`, `inferred` or `unavailable`). Components come from [`.repowise/components.yaml`](../reference/CONFIG.md#repowisecomponentsyaml) or are derived from the index. With `include=["ownership"]` a component card adds `ownership`: declared teams with their activity over the last 90 days, a count of individual owners, and findings (`critical_no_active_owner`, `declared_owner_inactive`, `critical_bus_factor_one`, `catalog_entry_no_code`). An owner with no identity in the indexed history is `unknown` and raises no finding, so `critical_no_active_owner` does not fire when every owner is unknown; individuals match only by exact git email or forge noreply login. No other `include` applies to component targets. Health and dead code leave out files in gated languages and say how many.
-A `change:<id>` target (`change:pr-123`, or a commit sha the change landed) returns the [Change Record](../reference/CLI_REFERENCE.md#repowise-changes): title, forge ref, `merged_at`, category, files and provenance with its coverage. On a file target, `changes` lists the newest Change Records that touched it, and `provenance` gives the file's commits by source (agent, human-attested, unknown) with coverage; the agent share is withheld below 30% coverage. With attribution off, `provenance` reads `{"unavailable": "attribution_off"}` and change rows carry none. `suspects` adds one top-level block: the changes merged in the last 14 days ranked against the targets as a symptom, at most 5 rows, each with the signals that fired and their evidence, plus the candidate count and window; an order to read changes in, never a cause.
+A `change:<id>` target (`change:pr-123`, or a commit sha the change landed) returns the [Change Record](../reference/CLI_REFERENCE.md#repowise-changes): title, forge ref, `merged_at`, category, files and provenance with its coverage. On a file target, `changes` lists the newest Change Records that touched it, and `provenance` gives the file's commits by source (agent, human-attested, unknown) with coverage; the agent share is withheld below 30% coverage. With attribution off, `provenance` reads `{"unavailable": "attribution_off"}` and change rows carry none. `suspects` adds one top-level block: the changes merged in the last 14 days ranked against the targets' files and the words in their paths, or the `symptom` text when one is given, at most 5 rows, each with the signals that fired and their evidence, plus the candidate count and window; an order to read changes in, never a cause.
A `package:<name>` target (`package:requests`, or `package:npm:lodash`) returns where that third-party package is imported: its manifest declarations, a summary, the components and declared owner teams, and up to 25 import sites with line, `mapping` (`declared` or `inferred`) and `reachability` (`reachable`, `unreachable`, `test` or `unknown`, with a basis). See [PACKAGE_USAGE.md](../reference/PACKAGE_USAGE.md).
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index b6a0fbd67..7d60eb6f6 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -599,6 +599,7 @@ call.
|------|-------------|
| `--include` | Opt-in block, repeatable: `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `metrics`, `community`, `decisions`, `health`, `skeleton`, `doc_drift`, `symbols` |
| `--no-compact` | Add structure, imports and docstrings to each card |
+| `--symptom` | Issue text, an error or a stack trace for `--include suspects` to rank against |
```bash
repowise context src/api/routes.py src/api/auth.py
diff --git a/packages/cli/src/repowise/cli/commands/context_cmd.py b/packages/cli/src/repowise/cli/commands/context_cmd.py
index 72528a81b..f6665326b 100644
--- a/packages/cli/src/repowise/cli/commands/context_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/context_cmd.py
@@ -186,11 +186,17 @@ def project(payload: dict, targets: tuple[str, ...]) -> dict:
default=False,
help="Add structure, imports and docstrings to each card.",
)
+ "--symptom",
+ default=None,
+ help="Issue text, an error or a stack trace for --include suspects to rank against.",
+)
@_ta.target_options
def context_command(
targets: tuple[str, ...],
include: tuple[str, ...],
no_compact: bool,
+ symptom: str | None,
path: str | None,
repo_alias: str | None,
no_workspace: bool,
@@ -220,6 +226,7 @@ def context_command(
targets=list(targets),
include=list(include) or None,
compact=not no_compact,
+ symptom=symptom,
)
payload = _ta.run(repo_path, _factory, "get_context")
diff --git a/packages/core/src/repowise/core/suspects/index.py b/packages/core/src/repowise/core/suspects/index.py
index 4e53489b5..fdedd1409 100644
--- a/packages/core/src/repowise/core/suspects/index.py
+++ b/packages/core/src/repowise/core/suspects/index.py
@@ -37,6 +37,11 @@ def _aware(value: datetime) -> datetime:
return value if value.tzinfo else value.replace(tzinfo=UTC)
+def repo_terms(repo_path: Path | str) -> frozenset[str]:
+ """The repo's own name as search words: they match every change."""
+ return frozenset(meaningful_terms(Path(repo_path).resolve().name.replace("-", " ")))
+
+
def _tracked_files(repo_path: Path) -> frozenset[str]:
return frozenset((_git(repo_path, "ls-files") or "").splitlines())
@@ -130,7 +135,7 @@ async def find_suspects(
named = prepared.files
ctx = SuspectContext(
repo_files=repo_files,
- repo_terms=frozenset(meaningful_terms(repo_path.resolve().name.replace("-", " "))),
+ repo_terms=repo_terms(repo_path),
imports=await _imports(session, repo_id) if named else {},
co_change=await get_co_change_partners(session, repo_id, list(named)) if named else {},
)
@@ -159,4 +164,4 @@ async def find_suspects(
}
-__all__ = ["DEFAULT_LIMIT", "DEFAULT_WINDOW_DAYS", "NOTE", "find_suspects"]
+__all__ = ["DEFAULT_LIMIT", "DEFAULT_WINDOW_DAYS", "NOTE", "find_suspects", "repo_terms"]
diff --git a/packages/core/src/repowise/core/suspects/signals.py b/packages/core/src/repowise/core/suspects/signals.py
index f1ab05465..4c63f3fbf 100644
--- a/packages/core/src/repowise/core/suspects/signals.py
+++ b/packages/core/src/repowise/core/suspects/signals.py
@@ -48,6 +48,32 @@ _EVIDENCE_STOPWORDS = frozenset(
)
+#: Path segments that name a project's layout, not what its code does: as text
+#: they match nearly every change.
+_LAYOUT_SEGMENTS = frozenset(
+ {
+ "cmd", "core", "dist", "index", "init", "__init__", "internal", "java", "kotlin",
+ "lib", "libs", "main", "packages", "pkg", "pkgs", "py", "python", "scala",
+ "source", "sources", "src", "test", "tests",
+ }
+)
+
+
+def path_terms(target: str, quiet: frozenset[str] = frozenset()) -> str:
+ """A file or ``file::Symbol`` target as symptom text.
+
+ Directory names, file stem and symbol, without the extension, layout
+ segments or *quiet* words. A filler stem (``index.ts``) stays when nothing
+ else is left.
+ """
+ path, _, member = target.partition("::")
+ *dirs, name = path.replace("\\", "/").strip("/").split("/")
+ stem = name.rsplit(".", 1)[0] if "." in name.lstrip(".") else name
+ drop = _LAYOUT_SEGMENTS | quiet
+ words = [w for w in [*dirs, stem] if w and w.lower() not in drop] or [stem]
+ return " ".join([*words, member] if member else words)
+
+
def path_mentions(text: str) -> list[str]:
"""Path-like tokens in free text, in order, deduped."""
return list(dict.fromkeys(m.group(0).lstrip("/\\") for m in _PATH_TOKEN.finditer(text)))
@@ -238,4 +264,5 @@ __all__ = [
"TextSignal",
"TraceSignal",
"path_mentions",
+ "path_terms",
]
diff --git a/packages/server/src/repowise/server/chat_suspects.py b/packages/server/src/repowise/server/chat_suspects.py
index e2c7630eb..37447d753 100644
--- a/packages/server/src/repowise/server/chat_suspects.py
+++ b/packages/server/src/repowise/server/chat_suspects.py
@@ -1,8 +1,8 @@
"""The chat-only ``find_suspects`` tool: changes before a symptom, in reading order.
-MCP has no free-text symptom input (get_context's ``include=["suspects"]``
-takes its targets as the symptom), so chat gets this tool for an incident
-described in words, the input the suspects measurement scored. It reads the
+Chat gets its own tool for an incident described in words, the input the
+suspects measurement scored, rather than routing it through get_context's
+``include=["suspects"]`` and its ``symptom`` argument. It reads the
same index through the in-process tool state, so it is offered only on the
local backend, and only when the session may run ``get_context``, which reads
the same data under the same scope.
diff --git a/packages/server/src/repowise/server/mcp_server/_changes.py b/packages/server/src/repowise/server/mcp_server/_changes.py
index 463d228a9..0202fb6de 100644
--- a/packages/server/src/repowise/server/mcp_server/_changes.py
+++ b/packages/server/src/repowise/server/mcp_server/_changes.py
@@ -301,22 +301,30 @@ async def overview_changes(session: Any, repository: Any) -> dict[str, Any]:
SUSPECTS_CAP = 5
-async def suspects_block(session: Any, repository: Any, targets: list[str]) -> dict[str, Any]:
+async def suspects_block(
+ session: Any, repository: Any, targets: list[str], symptom: str | None = None
+) -> dict[str, Any]:
"""Changes merged in the last 14 days ranked against the targets as a symptom.
- File and symbol targets name the symptom's files; every target's text
- feeds the text signal. A ``change:`` or ``component:`` target is not part
- of the symptom.
+ File and symbol targets name the symptom's files. A typed *symptom* (issue
+ text, an error, a stack trace) is the text query as given; without one,
+ the targets' :func:`path_terms` are. A ``change:`` or ``component:``
+ target is not part of the symptom.
"""
from repowise.core.suspects import Symptom
- from repowise.core.suspects.index import find_suspects
+ from repowise.core.suspects.index import find_suspects, repo_terms
+ from repowise.core.suspects.signals import path_terms
symptom_targets = [t for t in targets if not is_change_target(t) and not t.startswith("component:")]
files = tuple(dict.fromkeys(t.split("::", 1)[0] for t in symptom_targets))
+ if not (symptom and symptom.strip()):
+ quiet = repo_terms(repository.local_path)
+ symptom = " ".join(path_terms(t, quiet) for t in symptom_targets)
+ # ``prepare`` reads a stack trace out of the text when no trace is given.
return await find_suspects(
session,
repository.id,
repository.local_path,
- Symptom(text=" ".join(symptom_targets), files=files),
+ Symptom(text=symptom, files=files),
limit=SUSPECTS_CAP,
)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/context.py b/packages/server/src/repowise/server/mcp_server/tool_context/context.py
index 97d3d89fd..bb3705f27 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/context.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/context.py
@@ -133,23 +133,23 @@ async def get_context(
include: list[str] | None = None,
compact: bool = True,
repo: str | None = None,
+ symptom: str | None = None,
) -> dict:
"""Triage card for files / modules / symbols — relationships, not source bytes.
- Returns title, summary, signatures with line numbers, hotspot bit, and
+ Returns title, summary, signatures with lines, hotspot bit and
decision_record titles. A symbol row without symbol_id is path::name.
- fix_history appears only on files with counted bug fixes (count, age,
- bug_magnet); hotspot is churn. Either one is a cue to
- call get_risk. episodes counts the dated records bound to a target
- (absent at zero); get_why serves the bodies. A symbol target is counted as its file, and a
- module aggregates everything beneath it.
- Batch targets in one call. No source bytes by default: pass
- include=["skeleton"] for the whole file body-elided and line-verified in
+ fix_history (count, age, bug_magnet) appears only on files with counted
+ bug fixes; hotspot is churn. Either is a cue to call get_risk. episodes
+ counts the dated records bound to a target (absent at zero); get_why serves
+ the bodies. A symbol target counts as its file; a module aggregates all
+ beneath it. Batch targets in one call. No source bytes by default:
+ include=["skeleton"] gives the whole file body-elided and line-verified in
ONE call, or Read it. Do not call get_symbol per signature.
For a rename or update-all-callers task, include=["references"] is the
- whole edit set when complete is true.
+ whole edit set when complete.
- Default responses fit 24,000 serialized chars; nonempty ``include`` uses
+ Defaults fit 24,000 serialized chars; nonempty ``include`` uses
32,000. Reductions carry counts and ``_meta.omitted`` recovery refs;
``_meta.recovery_unavailable`` names a storage failure.
Include-gated blocks are projections, not omissions.
@@ -159,11 +159,11 @@ async def get_context(
"change:<id>" (pr-123 or a sha), "package:<name>".
include: opt-in blocks: full_doc | ownership | last_change | callers
| callees | references | metrics | community | decisions | skeleton
- | skeleton+ | health | doc_drift (docs naming this file)
- | symbols (all, not the top 15) | changes | provenance
- | suspects.
+ | skeleton+ | health | doc_drift (docs naming it) | symbols
+ (all, not top 15) | changes | provenance | suspects.
compact: False adds structure+imports+docstrings.
repo: usually omitted.
+ symptom: issue text, error or stack trace suspects ranks on.
"""
if repo == "all":
return _unsupported_repo_all("get_context")
@@ -171,12 +171,18 @@ async def get_context(
if needs_routing(routes):
return await run_grouped(
routes,
- lambda alias, local: get_context(local, include=include, compact=compact, repo=alias),
+ lambda alias, local: get_context(
+ local, include=include, compact=compact, repo=alias, symptom=symptom
+ ),
)
ctx = await _resolve_repo_context(repo)
collector = OmissionCollector("get_context", repo_root=ctx.path)
ignored: list[dict[str, Any]] = []
include_set = _include_set(include, ignored)
+ if symptom and "suspects" not in include_set:
+ ignored.append(
+ {"argument": "symptom", "values": [symptom[:80]], "valid": ['include=["suspects"]']}
+ )
exclude_spec = _get_exclude_spec(ctx.path)
import time as _time
@@ -197,7 +203,9 @@ async def get_context(
collector=collector,
)
suspects = (
- await suspects_block(session, repository, targets) if "suspects" in include_set else None
+ await suspects_block(session, repository, targets, symptom)
+ if "suspects" in include_set
+ else None
)
results = _per_target_results(targets, raw_results)
diff --git a/tests/unit/server/mcp/test_changes_mcp.py b/tests/unit/server/mcp/test_changes_mcp.py
index 88c50cbc3..bb4dcbf80 100644
--- a/tests/unit/server/mcp/test_changes_mcp.py
+++ b/tests/unit/server/mcp/test_changes_mcp.py
@@ -206,6 +206,26 @@ async def test_suspects_rank_recent_changes_against_the_targets(setup_mcp, sessi
assert (top["id"], top["rank"]) == ("pr-2", 1)
assert "text" in top["signals"] and "recency" in top["signals"]
assert "not a cause" in block["note"]
+ for row in block["suspects"]:
+ assert not {"term py", "term src"} & set(row["signals"].get("text", {}).get("evidence", []))
+
+
+async def test_a_typed_symptom_is_the_suspects_text_query(setup_mcp, session):
+ import time_machine
+
+ from repowise.server.mcp_server import get_context
+
+ await _seed(session)
+ with time_machine.travel(datetime(2026, 3, 16, tzinfo=UTC), tick=False):
+ result = await get_context(
+ targets=["src/db/models.py"], include=["suspects"], symptom="token refresh fails"
+ )
+ ignored = await get_context(targets=["src/db/models.py"], symptom="token refresh fails")
+ top = result["suspects"]["suspects"][0]
+ assert top["id"] == "pr-2"
+ assert "term refresh" in top["signals"]["text"]["evidence"]
+ assert any(a["argument"] == "symptom" for a in ignored["ignored_arguments"])
@pytest.mark.asyncio
diff --git a/tests/unit/test_suspects.py b/tests/unit/test_suspects.py
index b20a56762..564dff906 100644
--- a/tests/unit/test_suspects.py
+++ b/tests/unit/test_suspects.py
@@ -7,6 +7,7 @@ from datetime import UTC, datetime, timedelta
import pytest
from repowise.core.co_change import CoChangePartner
+from repowise.core.fts_query import meaningful_terms
from repowise.core.suspects import (
Candidate,
Hit,
@@ -16,7 +17,7 @@ from repowise.core.suspects import (
suspect_signals,
)
from repowise.core.suspects.git_text import hunk_symbols
-from repowise.core.suspects.signals import path_mentions
+from repowise.core.suspects.signals import path_mentions, path_terms
NOW = datetime(2026, 1, 10, tzinfo=UTC)
QUERY = "django/db/models/query.py"
@@ -291,3 +292,15 @@ async def test_candidates_use_the_default_commit_limit(suspects_index, config):
out = await find_suspects(session, repo_id, path, Symptom(at=NOW))
assert out["candidates"] == 3
assert out["candidates_capped"] is False
+
+
+def test_path_target_text_drops_extension_and_layout_segments():
+ text = path_terms(
+ "packages/core/src/repowise/core/ingestion/call_resolver.py", frozenset({"repowise"})
+ )
+ assert set(meaningful_terms(text)) == {"call_resolver", "ingestion"}
+
+
+def test_path_target_text_keeps_the_symbol_and_a_filler_stem_left_alone():
+ assert path_terms("src/billing/invoice.ts::totalDue") == "billing invoice totalDue"
+ assert path_terms("src/index.ts") == "index"