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(mcp,claude-md): response-quality sweep across MCP tools and generated CLAUDE.md (#413)

Raghav Chamadiya1e4241d25eed
diff --git a/packages/cli/src/repowise/cli/rewrite_hook.py b/packages/cli/src/repowise/cli/rewrite_hook.py
index 1a7767d69..bc547dfd0 100644
--- a/packages/cli/src/repowise/cli/rewrite_hook.py
+++ b/packages/cli/src/repowise/cli/rewrite_hook.py
@@ -50,11 +50,13 @@ from repowise.cli.agent_adapters.base import RewriteResult
_WRAPPER_RE = re.compile(
r"^(?:"
r"uv run|uvx|npx|pnpm exec|pnpm dlx|yarn dlx|poetry run|pipenv run|hatch run|"
- r"python3? -m|py -m"
+ r"python3? -m|py -m|"
+ r"cmd(?:\.exe)? /c"
r")\s+",
re.IGNORECASE,
)
_ENV_ASSIGN_RE = re.compile(r"^\w+=\S+\s+")
+_WHOLE_QUOTED_RE = re.compile(r'^"([^"]*)"$')
_EXE_PATH_RE = re.compile(r'^(?:"[^"]*[\\/]|\S*[\\/])(?P<exe>[\w.-]+?)(?:\.exe)?(?:")?(?=\s|$)')
@@ -64,6 +66,9 @@ def _normalize(command: str) -> str:
previous = cmd
cmd = _ENV_ASSIGN_RE.sub("", cmd)
cmd = _WRAPPER_RE.sub("", cmd)
+ quoted = _WHOLE_QUOTED_RE.match(cmd)
+ if quoted:
+ cmd = quoted.group(1).strip()
if cmd == previous:
break
cmd = _EXE_PATH_RE.sub(lambda m: m.group("exe"), cmd)
diff --git a/packages/core/src/repowise/core/distill/filters/file_listing.py b/packages/core/src/repowise/core/distill/filters/file_listing.py
index 49bc34ff5..14e9ab05c 100644
--- a/packages/core/src/repowise/core/distill/filters/file_listing.py
+++ b/packages/core/src/repowise/core/distill/filters/file_listing.py
@@ -15,8 +15,11 @@ from repowise.core.distill.registry import filter_registry
_COMMAND_RE = re.compile(r"^(ls\b|dir\b|tree\b|find\b|fd\b|get-childitem\b|gci\b|git ls-files\b)")
-# A bare path: no spaces (or escaped ones), with directory separators or an extension.
-_PATH_LINE_RE = re.compile(r"^[\w.@~-]+(?:[\\/][\w.@\[\]-]+)*[\\/]?$")
+# A bare path: no spaces (or escaped ones), with directory separators or an
+# extension. The optional drive prefix covers absolute Windows paths
+# (``C:\Users\...`` from ``dir /s /b``), which the sniff used to reject
+# wholesale because of the colon.
+_PATH_LINE_RE = re.compile(r"^(?:[A-Za-z]:[\\/])?[\w.@~-]+(?:[\\/][\w.@\[\]-]+)*[\\/]?$")
# ls -l style: permission bits then columns ending in the name.
_LS_LONG_RE = re.compile(r"^[-dlbcps][-rwxsStT]{9}[\s+@]")
diff --git a/packages/core/src/repowise/core/distill/router.py b/packages/core/src/repowise/core/distill/router.py
index 1a41419df..f0d85213a 100644
--- a/packages/core/src/repowise/core/distill/router.py
+++ b/packages/core/src/repowise/core/distill/router.py
@@ -17,7 +17,8 @@ from repowise.core.distill.registry import filter_registry
_WRAPPER_RE = re.compile(
r"^(?:"
r"uv run|uvx|npx|pnpm exec|pnpm dlx|yarn dlx|poetry run|pipenv run|hatch run|"
- r"python3? -m|py -m"
+ r"python3? -m|py -m|"
+ r"cmd(?:\.exe)? /c"
r")\s+",
re.IGNORECASE,
)
@@ -25,6 +26,10 @@ _WRAPPER_RE = re.compile(
# Leading POSIX-style env assignments: FOO=bar BAZ=1 cmd ...
_ENV_ASSIGN_RE = re.compile(r"^\w+=\S+\s+")
+# A command that is one whole quoted string — the typical remainder after
+# stripping a ``cmd /c "dir /s /b ..."`` wrapper.
+_WHOLE_QUOTED_RE = re.compile(r'^"([^"]*)"$')
+
# Path prefix on the executable: .venv\Scripts\pytest.exe → pytest
_EXE_PATH_RE = re.compile(r'^(?:"[^"]*[\\/]|\S*[\\/])(?P<exe>[\w.-]+?)(?:\.exe)?(?:")?(?=\s|$)')
@@ -36,6 +41,9 @@ def normalize_command(command: str) -> str:
previous = cmd
cmd = _ENV_ASSIGN_RE.sub("", cmd)
cmd = _WRAPPER_RE.sub("", cmd)
+ quoted = _WHOLE_QUOTED_RE.match(cmd)
+ if quoted:
+ cmd = quoted.group(1).strip()
if cmd == previous:
break
cmd = _EXE_PATH_RE.sub(lambda m: m.group("exe"), cmd)
diff --git a/packages/core/src/repowise/core/generation/editor_files/fetcher.py b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
index d546dea1b..bfd9d37eb 100644
--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py
+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
@@ -127,7 +127,7 @@ class EditorFileDataFetcher:
modules: list[KeyModule] = []
for page, _pagerank, symbol_count in rows:
purpose = _extract_sentences(page.content or "", max_sentences=1)
- purpose = purpose[:80].rstrip(".") if purpose else ""
+ purpose = _truncate_at_word(purpose, 80).rstrip(".") if purpose else ""
modules.append(
KeyModule(
name=page.target_path,
@@ -311,33 +311,54 @@ class EditorFileDataFetcher:
import json
db_layers = await crud.get_kg_layers(self._session, self._repo_id)
- db_tour = await crud.get_kg_tour_steps(self._session, self._repo_id)
layers = [
KGLayerSummary(
name=l.name,
file_count=len(json.loads(l.node_ids_json) if l.node_ids_json else []),
- description=(l.description or "")[:80],
+ description=_truncate_at_word(l.description or "", 80),
)
for l in db_layers
]
- tour = []
- for s in db_tour:
- node_ids = json.loads(s.node_ids_json) if s.node_ids_json else []
- primary = ""
- for nid in node_ids:
- fp = nid.removeprefix("file:")
- if fp != nid or not nid.startswith("file:"):
- primary = fp
- break
- tour.append(
- KGTourStepSummary(
- order=s.step_order,
- title=s.title,
- primary_file=primary,
+ # Guided tour: the overview page's metadata_json carries the
+ # authoritative tour (order/title/target_path) — the same source
+ # the MCP get_overview tool renders. The KG tour-step rows often
+ # persist empty node_ids_json, which used to leave every CLAUDE.md
+ # tour step path-less ("3. **index.ts**" with no way to tell which
+ # of the five index.ts re-export hubs it meant).
+ tour: list[KGTourStepSummary] = []
+ pages = await crud.list_pages(
+ self._session,
+ self._repo_id,
+ page_type="repo_overview",
+ limit=1,
+ )
+ if pages:
+ try:
+ ov_meta = json.loads(pages[0].metadata_json or "{}")
+ except (json.JSONDecodeError, TypeError):
+ ov_meta = {}
+ for s in ov_meta.get("guided_tour") or []:
+ tour.append(
+ KGTourStepSummary(
+ order=s.get("order") or len(tour) + 1,
+ title=s.get("title") or "",
+ primary_file=s.get("target_path") or "",
+ )
+ )
+ if not tour:
+ db_tour = await crud.get_kg_tour_steps(self._session, self._repo_id)
+ for s in db_tour:
+ node_ids = json.loads(s.node_ids_json) if s.node_ids_json else []
+ primary = node_ids[0].removeprefix("file:") if node_ids else ""
+ tour.append(
+ KGTourStepSummary(
+ order=s.step_order,
+ title=s.title,
+ primary_file=primary,
+ )
)
- )
return layers, tour
@@ -376,18 +397,39 @@ def _get_head_short_sha(repo_path: Path) -> str:
def _extract_sentences(text: str, max_sentences: int) -> str:
- """Return up to *max_sentences* sentences from the start of *text*.
+ """Return up to *max_sentences* prose sentences from the start of *text*.
- Strips markdown headers/code fences so only prose remains.
+ Strips markdown headers/code fences AND list/table lines so only prose
+ remains. List items rarely end with sentence punctuation, so keeping
+ them used to jam bullets onto the tail of the last real sentence
+ ("...rendered in a web UI. - **Languages**") and leave orphaned
+ fragments like "1. **Inputs**" in the rendered CLAUDE.md.
"""
# Remove markdown headers and code fences
text = re.sub(r"^#{1,6}\s+.*$", "", text, flags=re.MULTILINE)
text = re.sub(r"```.*?```", "", text, flags=re.DOTALL)
+ # Drop list items, table rows, and blockquotes — prose only.
+ # Both "1." and "1)" enumeration styles count as list items.
+ text = re.sub(r"^\s*(?:[-*+]\s|\d+[.)]\s|\||>).*$", "", text, flags=re.MULTILINE)
text = re.sub(r"`([^`]+)`", r"\1", text) # strip backticks, keep text
text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text) # links → text
- text = text.strip()
+ text = re.sub(r"\n{2,}", "\n", text).strip()
# Split on sentence boundaries
sentences = re.split(r"(?<=[.!?])\s+", text)
sentences = [s.strip() for s in sentences if s.strip() and len(s.strip()) > 10]
return " ".join(sentences[:max_sentences])
+
+
+def _truncate_at_word(text: str, limit: int) -> str:
+ """Truncate *text* to at most *limit* chars without splitting a word.
+
+ Hard ``[:80]`` slices cut mid-word ("classificat", "repowi") which reads
+ as a rendering bug in every generated table. Cutting at the last word
+ boundary and appending an ellipsis keeps the same budget honestly.
+ """
+ text = text.strip()
+ if len(text) <= limit:
+ return text
+ cut = text[:limit].rsplit(" ", 1)[0].rstrip(".,;:")
+ return f"{cut}…"
diff --git a/packages/core/src/repowise/core/generation/editor_files/tech_stack.py b/packages/core/src/repowise/core/generation/editor_files/tech_stack.py
index 8db5baa8a..3af5eee47 100644
--- a/packages/core/src/repowise/core/generation/editor_files/tech_stack.py
+++ b/packages/core/src/repowise/core/generation/editor_files/tech_stack.py
@@ -68,10 +68,15 @@ _DOTNET_MAX_PROJECTS = 200
# Directory names to prune from the scan. These never host real
# project source and bloat the walk on Windows where `bin/obj`
-# contains thousands of intermediate files per project.
+# contains thousands of intermediate files per project. Test fixtures
+# and vendored sample repos are pruned too: a Python/TS repo that keeps
+# .NET solutions under tests/fixtures/ or test-repos/ must not be
+# labelled a C# codebase by its own test data.
_DOTNET_PRUNE = frozenset({
"bin", "obj", ".vs", "node_modules", ".git", "packages",
".idea", "artifacts", ".build", "TestResults",
+ "tests", "test", "fixtures", "test-repos", "testdata", "samples",
+ "local-stash",
})
@@ -99,6 +104,11 @@ def _find_dotnet_projects(repo_path: Path) -> list[Path]:
if entry.is_dir():
if entry.name in _DOTNET_PRUNE or entry.name.startswith("."):
continue
+ # A nested git repo is a separate project (vendored
+ # benchmark checkout, sibling clone) — its project files
+ # must not define THIS repo's tech stack.
+ if (entry / ".git").exists():
+ continue
_walk(entry, depth + 1)
elif entry.is_file() and entry.suffix == ".csproj":
found.append(entry)
@@ -160,7 +170,26 @@ def detect_tech_stack(repo_path: Path) -> list[TechStackItem]:
add(display, raw or None, cat)
# TypeScript can be added independently — many monorepos only use
# TS via tsconfig.json without depending on a Node.js runtime.
- if "typescript" in all_deps or (repo_path / "tsconfig.json").exists():
+ # Monorepos frequently keep tsconfig.json only inside workspace
+ # packages (packages/*/tsconfig.json), so look two levels deep.
+ def _is_project_dir(p: Path) -> bool:
+ rel_parts = p.relative_to(repo_path).parts[:-1]
+ if any(part == "node_modules" or part.startswith(".") for part in rel_parts):
+ return False
+ # Skip nested git repos (sibling clones, vendored checkouts).
+ probe = repo_path
+ for part in rel_parts:
+ probe = probe / part
+ if (probe / ".git").exists():
+ return False
+ return True
+
+ has_tsconfig = (
+ (repo_path / "tsconfig.json").exists()
+ or any(_is_project_dir(p) for p in repo_path.glob("*/tsconfig.json"))
+ or any(_is_project_dir(p) for p in repo_path.glob("*/*/tsconfig.json"))
+ )
+ if "typescript" in all_deps or has_tsconfig:
ts_ver = all_deps.get("typescript", "").lstrip("^~>=") or None
add("TypeScript", ts_ver, "language")
@@ -227,7 +256,15 @@ def detect_tech_stack(repo_path: Path) -> list[TechStackItem]:
# still register. A shallow glob misses every real-world .NET
# monorepo layout — eShop, Aspire samples, PowerToys, Roslyn etc.
csproj_files = _find_dotnet_projects(repo_path)
- sln_files = list(repo_path.glob("*.sln")) + list(repo_path.glob("*/*.sln"))
+ sln_files = [
+ sln
+ for sln in list(repo_path.glob("*.sln")) + list(repo_path.glob("*/*.sln"))
+ if sln.parent == repo_path
+ or (
+ sln.parent.name not in _DOTNET_PRUNE
+ and not (sln.parent / ".git").exists()
+ )
+ ]
has_directory_build = (repo_path / "Directory.Build.props").exists() or (
repo_path / "Directory.Packages.props"
).exists()
diff --git a/packages/core/src/repowise/core/generation/templates/claude_md.j2 b/packages/core/src/repowise/core/generation/templates/claude_md.j2
index 4086316ec..7bbac88d2 100644
--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2
@@ -13,11 +13,20 @@ Last indexed: {{ data.indexed_at }}{% if data.indexed_commit %} (commit {{ data.
{% endif %}
{% if data.key_modules %}
### Key Modules
+{% set module_owners = data.key_modules | selectattr("owner") | list %}
+{% if module_owners %}
| Module | Purpose | Owner |
|--------|---------|-------|
{% for mod in data.key_modules %}
| `{{ mod.name }}` | {{ mod.purpose or "—" }} | {{ mod.owner or "—" }} |
{% endfor %}
+{% else %}
+| Module | Purpose |
+|--------|---------|
+{% for mod in data.key_modules %}
+| `{{ mod.name }}` | {{ mod.purpose or "—" }} |
+{% endfor %}
+{% endif %}
{% endif %}
{% if data.entry_points %}
### Entry Points
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 2f3d00e29..894935991 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
@@ -90,12 +90,15 @@ async def get_context(
return _unsupported_repo_all("get_context")
ctx = await _resolve_repo_context(repo)
- # Default to docs + freshness when include is omitted. Freshness is
- # critical for the agent to detect stale index data. The other blocks
- # (ownership/last_change/decisions) are 200-500 bytes each and bloat
- # every subsequent agent turn via cache replay. Callers that want them
- # must pass include explicitly.
- include_set = set(include) if include else {"docs", "freshness"}
+ # docs + freshness are ALWAYS returned (the tool contract says
+ # "defaults are always returned"); ``include`` only adds blocks on top.
+ # Freshness is critical for the agent to detect stale index data. The
+ # other blocks (ownership/last_change/decisions) are 200-500 bytes each
+ # and bloat every subsequent agent turn via cache replay. Callers that
+ # want them must pass include explicitly. Building the set this way
+ # also fixes include=["skeleton"] silently dropping the file summary
+ # and freshness card that every other call shape carries.
+ include_set = {"docs", "freshness"} | (set(include) if include else set())
exclude_spec = _get_exclude_spec(ctx.path)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
index c290fdfc6..861ebbe68 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
@@ -77,6 +77,16 @@ def _synthesize_structural_summary(file_path: str, classes: list[str], functions
return f"{name}: " + "; ".join(parts) + "."
+def _clean_signature(signature: str | None) -> str:
+ """Collapse a stored signature onto one line.
+
+ Signatures indexed from CRLF files carry literal ``\\r\\n`` plus the
+ original indentation — pure token waste in a triage card. Whitespace
+ runs collapse to single spaces; the text is unchanged otherwise.
+ """
+ return " ".join((signature or "").split())
+
+
async def _resolve_one_target(
session: AsyncSession,
repository: Repository,
@@ -333,7 +343,14 @@ async def _resolve_one_target(
symbols = res.scalars().all()
classes = [s.name for s in symbols if s.kind == "class"]
functions = [s.name for s in symbols if s.kind in ("function", "method")]
- if compact:
+ if include and "skeleton" in include:
+ # The skeleton block already renders every signature with
+ # line bounds — repeating the symbol list in docs would
+ # roughly double the response for zero information. Keep
+ # the cheap title/summary card only.
+ if not docs.get("summary"):
+ docs["summary"] = _synthesize_structural_summary(target, classes, functions)
+ elif compact:
# Compact mode: name+kind+signature+line+symbol_id only. Drops
# docstrings, line ranges, structure, and imported_by — those
# live behind compact=False or include= flags. The symbol_id
@@ -351,7 +368,7 @@ async def _resolve_one_target(
{
"name": s.name,
"kind": s.kind,
- "signature": s.signature,
+ "signature": _clean_signature(s.signature),
"line": s.start_line,
"symbol_id": s.symbol_id,
}
@@ -370,7 +387,7 @@ async def _resolve_one_target(
{
"name": s.name,
"kind": s.kind,
- "signature": s.signature,
+ "signature": _clean_signature(s.signature),
"start_line": s.start_line,
"end_line": s.end_line,
"docstring": (s.docstring or "")[:400],
@@ -440,7 +457,10 @@ async def _resolve_one_target(
[
{
"path": f.target_path,
- "description": f.title,
+ # Page titles are "File: <path>" — pure redundancy
+ # next to the path field. Use the indexed one-line
+ # summary when there is one.
+ "description": (f.summary or "").strip()[:160],
"confidence_score": f.confidence,
}
for f in file_pages
@@ -454,7 +474,7 @@ async def _resolve_one_target(
docs["name"] = sym.name
docs["qualified_name"] = sym.qualified_name
docs["kind"] = sym.kind
- docs["signature"] = sym.signature
+ docs["signature"] = _clean_signature(sym.signature)
docs["file_path"] = sym.file_path
docs["docstring"] = sym.docstring or ""
# File page summary (full content gated behind include=["full_doc"])
diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview.py b/packages/server/src/repowise/server/mcp_server/tool_overview.py
index 4af10dd85..1ed2919ee 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
+import re
from collections import Counter, defaultdict
from typing import Any
@@ -46,6 +47,28 @@ from repowise.server.mcp_server._helpers import (
)
from repowise.server.mcp_server._meta import build_meta as _build_meta
+# Leading markdown-header boilerplate on module page content ("## Overview").
+_MD_HEADER_RE = re.compile(r"^\s*#{1,6}\s+.*$", re.MULTILINE)
+
+
+def _truncate_at_word(text: str, limit: int) -> str:
+ """Truncate at a word boundary with an ellipsis — never mid-word.
+
+ Hard slices ("request/response ha") read as rendering bugs to the
+ caller; same budget, honest cut.
+ """
+ text = text.strip()
+ if len(text) <= limit:
+ return text
+ return text[:limit].rsplit(" ", 1)[0].rstrip(".,;:") + "…"
+
+
+def _module_description(content: str, limit: int = 200) -> str:
+ """First prose of a module page, minus the "## Overview" boilerplate."""
+ prose = _MD_HEADER_RE.sub("", content or "").strip()
+ return _truncate_at_word(prose, limit)
+
+
# ---------------------------------------------------------------------------
# repo="all" — workspace-level summary
# ---------------------------------------------------------------------------
@@ -435,7 +458,7 @@ async def get_overview(repo: str | None = None) -> dict:
architecture["layers"] = [
{
"name": layer.name,
- "description": (layer.description or "")[:120],
+ "description": _truncate_at_word(layer.description or "", 120),
"file_count": len(
json.loads(layer.node_ids_json) if layer.node_ids_json else []
),
@@ -480,11 +503,14 @@ async def get_overview(repo: str | None = None) -> dict:
# Older indexes persisted titles like "Repository Overview: repo" because
# repo_name was not passed through to generate_repo_overview. Substitute
# the actual repo name back in so the response is useful without reindex.
+ # Exact match only: a prefix replace would corrupt any repo whose name
+ # starts with "repo" ("Repository Overview: repowise" → "...repowisewise").
if overview_page:
persisted_title = overview_page.title or ""
- title = persisted_title.replace(
- "Repository Overview: repo", f"Repository Overview: {repository.name}"
- )
+ if persisted_title.strip() == "Repository Overview: repo":
+ title = f"Repository Overview: {repository.name}"
+ else:
+ title = persisted_title
else:
title = repository.name
# Code-health KPIs — three headline numbers for the architecture
@@ -591,11 +617,7 @@ async def get_overview(repo: str | None = None) -> dict:
{
"name": p.title,
"path": p.target_path,
- "description": (
- p.content[:200].rsplit(" ", 1)[0] + "..."
- if len(p.content) > 200
- else p.content
- ),
+ "description": _module_description(p.content),
}
for p in module_pages
],
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk.py
index e42591acd..bda0c0a8e 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk.py
@@ -716,8 +716,21 @@ async def get_risk(
[p for p in (_as_path(e) for e in trimmed_blast.get("cochange_warnings", [])) if p],
exclude_spec,
)[:3]
+ # Scope to the PR: the directive answers "what should I do about
+ # THIS diff", so only changed files belong here. Repo-wide test
+ # gaps stay available in pr_blast_radius.test_gaps for deeper
+ # review — surfacing them in the directive made unrelated files
+ # ("alembic/env.py has no tests") read as failings of the PR.
+ # Read from the untrimmed analyzer payload: the trimmed list is
+ # capped at 10 repo-wide entries and may have already dropped the
+ # changed files we're looking for.
+ changed_set = set(changed_files)
missing_tests = filter_path_list(
- [p for p in (_as_path(e) for e in trimmed_blast.get("test_gaps", [])) if p],
+ [
+ p
+ for p in (_as_path(e) for e in pr_blast_radius.get("test_gaps", []))
+ if p and p in changed_set
+ ],
exclude_spec,
)[:3]
diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.py
index d37136790..370e5ba54 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_search.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py
@@ -58,9 +58,18 @@ _CONFIG_PATH_TOKENS = (
def _classify_hit_kind(target_path: str, page_type: str) -> str:
- """Bucket a hit into implementation / test / config / doc."""
+ """Bucket a hit into implementation / test / config / doc.
+
+ Pages without a file behind them (decision records, repo overviews,
+ onboarding pages — all have empty ``target_path``) are docs: letting
+ them fall through to the path heuristics classified every decision
+ record as "implementation", so ``kind="implementation"`` returned
+ decision pages instead of filtering them out.
+ """
tp = (target_path or "").lower()
- if page_type == "module_page" or page_type == "symbol_spotlight" or tp.endswith(".md"):
+ if page_type in ("module_page", "symbol_spotlight") or tp.endswith(".md"):
+ return "doc"
+ if not tp or page_type not in ("file_page",):
return "doc"
if any(tok in tp for tok in _TEST_PATH_TOKENS):
return "test"
@@ -220,7 +229,10 @@ async def search_codebase(
# Try semantic search, fall back to FTS. Track which backend supplied the
# hits so the response can surface it per-result — silent fallback hides
# a quality cliff that the agent should weigh into its trust budget.
- fetch_limit = limit * 3 if page_type else limit
+ # Over-fetch whenever a post-filter (page_type or kind) will trim hits;
+ # without the head-room a kind filter applied to an already-truncated
+ # list returned fewer than ``limit`` results — frequently zero.
+ fetch_limit = limit * 3 if (page_type or kind) else limit
results = []
search_method = "embedding"
with contextlib.suppress(TimeoutError, Exception):
@@ -250,9 +262,7 @@ async def search_codebase(
}
)
- output = output[:limit]
-
- # Batch-lookup page target paths for git freshness boost
+ # Batch-lookup page target paths for the kind filter + git freshness boost
if output:
page_ids = [item["page_id"] for item in output]
async with get_session(ctx.session_factory) as session:
@@ -260,12 +270,9 @@ async def search_codebase(
select(Page.id, Page.target_path).where(Page.id.in_(page_ids))
)
page_info = {row[0]: row[1] for row in res.all()}
- # Attach target_path to each item so the kind filter (path-prefix
- # heuristic) and downstream get_context callers can act on it.
- for item in output:
- item["target_path"] = page_info.get(item["page_id"], "")
- # Build git freshness map for result file paths
+ # Build git freshness map for result file paths — once for the
+ # whole batch, not per item.
target_paths = [tp for tp in page_info.values() if tp]
git_map: dict[str, GitMetadata] = {}
if target_paths:
@@ -274,6 +281,11 @@ async def search_codebase(
)
git_map = {g.file_path: g for g in git_res.scalars().all()}
+ # Attach target_path to each item so the kind filter (path-prefix
+ # heuristic) and downstream get_context callers can act on it.
+ for item in output:
+ item["target_path"] = page_info.get(item["page_id"], "")
+
output = filter_dicts_by_key(output, "target_path", _get_exclude_spec(ctx.path))
for item in output:
@@ -294,6 +306,16 @@ async def search_codebase(
# Re-sort by boosted relevance
output.sort(key=lambda x: x.get("relevance_score", 0), reverse=True)
+ # Kind filter runs on the over-fetched list BEFORE the limit cut so the
+ # caller still gets up to ``limit`` results of the requested kind.
+ if kind:
+ output = [
+ item for item in output
+ if _classify_hit_kind(item.get("target_path", ""), item.get("page_type", "")) == kind
+ ]
+
+ output = output[:limit]
+
# Derive confidence_score from relative position in the result set.
if output:
max_score = max((item.get("relevance_score") or 0) for item in output)
@@ -301,12 +323,6 @@ async def search_codebase(
raw = item.get("relevance_score") or 0
item["confidence_score"] = round(raw / max_score, 2) if max_score > 0 else 0.0
- if kind:
- output = [
- item for item in output
- if _classify_hit_kind(item.get("target_path", ""), item.get("page_type", "")) == kind
- ]
-
response: dict = {"results": output, "_meta": _build_meta(repository=repository)}
if grep_hint:
response["grep_hint"] = grep_hint
diff --git a/tests/unit/cli/test_ui_package.py b/tests/unit/cli/test_ui_package.py
index 8523aaf90..a5274a60c 100644
--- a/tests/unit/cli/test_ui_package.py
+++ b/tests/unit/cli/test_ui_package.py
@@ -98,7 +98,7 @@ def test_advanced_config_default_keys_no_fast(monkeypatch: pytest.MonkeyPatch) -
"exclude": (),
"commit_limit": 500,
"follow_renames": False,
- "concurrency": 5,
+ "concurrency": 10,
"reasoning": "auto",
"embedder": "mock",
"test_run": False,
@@ -113,4 +113,4 @@ def test_advanced_config_allow_fast_small_repo(monkeypatch: pytest.MonkeyPatch)
assert result["run_mode"] == "standard"
assert result["tier1_top_n"] is None
assert result["commit_limit"] == 1000 # <500 files -> deeper history default
- assert result["concurrency"] == 8 # <200 files -> higher concurrency default
+ assert result["concurrency"] == 12 # <200 files -> higher concurrency default
diff --git a/tests/unit/distill/test_rewrite_hook.py b/tests/unit/distill/test_rewrite_hook.py
index 81d88f1a3..a06bb4192 100644
--- a/tests/unit/distill/test_rewrite_hook.py
+++ b/tests/unit/distill/test_rewrite_hook.py
@@ -158,6 +158,8 @@ class TestClassify:
"npx jest --ci",
"git status",
"LS_COLORS=1 ls -la",
+ 'cmd /c "dir /s /b packages"',
+ "cmd.exe /c dir /s",
],
)
def test_normalize_mirrors_core_router(self, command: str) -> None:
diff --git a/tests/unit/distill/test_router.py b/tests/unit/distill/test_router.py
index 66eed8c5e..8c5259677 100644
--- a/tests/unit/distill/test_router.py
+++ b/tests/unit/distill/test_router.py
@@ -20,6 +20,9 @@ from repowise.core.distill.router import normalize_command, select_filter
("/usr/bin/git diff", "git diff"),
("FOO=bar npm test", "npm test"),
("npx vitest run", "vitest run"),
+ ('cmd /c "dir /s /b packages"', "dir /s /b packages"),
+ ("cmd.exe /c dir /s", "dir /s"),
+ ("CMD /C tree src", "tree src"),
],
)
def test_normalize_command(raw: str, expected: str) -> None:
@@ -56,6 +59,7 @@ def test_normalize_command(raw: str, expected: str) -> None:
("find . -name *.py", "file_listing"),
("ls -la", "file_listing"),
("tree packages", "file_listing"),
+ ('cmd /c "dir /s /b packages"', "file_listing"),
("tail -200 app.log", "logs"),
("docker logs api", "logs"),
("kubectl logs pod-1", "logs"),
diff --git a/tests/unit/generation/test_editor_fetcher_helpers.py b/tests/unit/generation/test_editor_fetcher_helpers.py
new file mode 100644
index 000000000..35972b911
--- /dev/null
+++ b/tests/unit/generation/test_editor_fetcher_helpers.py
@@ -0,0 +1,77 @@
+"""Unit tests for the pure helpers in editor_files.fetcher.
+
+These guard the CLAUDE.md rendering quality: prose-only sentence
+extraction (no jammed list bullets) and word-boundary truncation
+(no mid-word chops in generated tables).
+"""
+
+from __future__ import annotations
+
+from repowise.core.generation.editor_files.fetcher import (
+ _extract_sentences,
+ _truncate_at_word,
+)
+
+
+class TestExtractSentences:
+ def test_plain_prose(self) -> None:
+ text = "First sentence here. Second sentence here. Third one follows."
+ assert _extract_sentences(text, max_sentences=2) == (
+ "First sentence here. Second sentence here."
+ )
+
+ def test_strips_headers_and_fences(self) -> None:
+ text = "## Overview\n\nThe module does X.\n\n```py\ncode\n```\nIt also does Y."
+ out = _extract_sentences(text, max_sentences=4)
+ assert "## Overview" not in out
+ assert "code" not in out
+ assert "The module does X." in out
+
+ def test_list_items_do_not_jam_onto_prose(self) -> None:
+ # Regression: bullets after a sentence used to be glued onto it
+ # ("...web UI. - **Languages**") because they carry no sentence
+ # punctuation of their own.
+ text = (
+ "The engine outputs a wiki rendered in a web UI.\n\n"
+ "- **Languages**\n"
+ " - Python\n"
+ "1. **Inputs**\n"
+ " - A target repository workspace.\n"
+ " 1) extending the language registry/specs, and\n"
+ " 2) implementing a resolver.\n"
+ "| col | col |\n"
+ "> quoted\n"
+ "Documentation is served through an API."
+ )
+ out = _extract_sentences(text, max_sentences=4)
+ assert "- **Languages**" not in out
+ assert "1. **Inputs**" not in out
+ assert "1) extending" not in out
+ assert "| col" not in out
+ assert "quoted" not in out
+ assert "rendered in a web UI." in out
+ assert "served through an API." in out
+
+ def test_empty_input(self) -> None:
+ assert _extract_sentences("", max_sentences=3) == ""
+
+
+class TestTruncateAtWord:
+ def test_short_text_unchanged(self) -> None:
+ assert _truncate_at_word("short text", 80) == "short text"
+
+ def test_never_cuts_mid_word(self) -> None:
+ text = (
+ "The ingestion/languages module is the language ingestion "
+ "subsystem's classification and resolution layer"
+ )
+ out = _truncate_at_word(text, 80)
+ assert len(out) <= 81 # limit + ellipsis
+ assert out.endswith("…")
+ # Every emitted word must be a complete word of the input.
+ for word in out.rstrip("…").split():
+ assert word in text
+
+ def test_exact_limit_unchanged(self) -> None:
+ text = "x" * 80
+ assert _truncate_at_word(text, 80) == text
diff --git a/tests/unit/generation/test_kg_claude_md_onboarding.py b/tests/unit/generation/test_kg_claude_md_onboarding.py
index e3601913f..45aee99a8 100644
--- a/tests/unit/generation/test_kg_claude_md_onboarding.py
+++ b/tests/unit/generation/test_kg_claude_md_onboarding.py
@@ -106,6 +106,42 @@ class TestClaudeMdKGSection:
assert "**Entry Point**" in rendered
assert "`src/main.py`" in rendered
+ def test_key_modules_owner_column_dropped_when_no_owners(self, jinja_env):
+ from repowise.core.generation.editor_files.data import KeyModule
+
+ tmpl = jinja_env.get_template("claude_md.j2")
+ data = EditorFileData(
+ repo_name="test",
+ indexed_at="2026-05-25",
+ indexed_commit="abc123",
+ architecture_summary="",
+ key_modules=[
+ KeyModule(name="src/api", purpose="API layer", file_count=4, owner=None),
+ KeyModule(name="src/core", purpose="Core logic", file_count=9, owner=None),
+ ],
+ )
+ rendered = tmpl.render(data=data)
+ assert "| Module | Purpose |" in rendered
+ assert "Owner" not in rendered
+
+ def test_key_modules_owner_column_kept_when_any_owner(self, jinja_env):
+ from repowise.core.generation.editor_files.data import KeyModule
+
+ tmpl = jinja_env.get_template("claude_md.j2")
+ data = EditorFileData(
+ repo_name="test",
+ indexed_at="2026-05-25",
+ indexed_commit="abc123",
+ architecture_summary="",
+ key_modules=[
+ KeyModule(name="src/api", purpose="API layer", file_count=4, owner="Alice"),
+ KeyModule(name="src/core", purpose="Core logic", file_count=9, owner=None),
+ ],
+ )
+ rendered = tmpl.render(data=data)
+ assert "| Module | Purpose | Owner |" in rendered
+ assert "Alice" in rendered
+
def test_no_tour_section_without_data(self, jinja_env):
tmpl = jinja_env.get_template("claude_md.j2")
data = EditorFileData(
diff --git a/tests/unit/generation/test_tech_stack.py b/tests/unit/generation/test_tech_stack.py
index 364438ddc..ec43ae6cb 100644
--- a/tests/unit/generation/test_tech_stack.py
+++ b/tests/unit/generation/test_tech_stack.py
@@ -64,6 +64,77 @@ def test_detects_typescript_from_tsconfig(tmp_path):
assert "TypeScript" in names
+def test_detects_typescript_from_workspace_package_tsconfig(tmp_path):
+ # Monorepos often keep tsconfig.json only inside workspace packages.
+ (tmp_path / "package.json").write_text(
+ json.dumps({"name": "app", "dependencies": {}}), encoding="utf-8"
+ )
+ pkg_dir = tmp_path / "packages" / "ui"
+ pkg_dir.mkdir(parents=True)
+ (pkg_dir / "tsconfig.json").write_text("{}", encoding="utf-8")
+ items = detect_tech_stack(tmp_path)
+ names = [i.name for i in items]
+ assert "TypeScript" in names
+
+
+def test_node_modules_tsconfig_is_not_typescript_evidence(tmp_path):
+ (tmp_path / "package.json").write_text(
+ json.dumps({"name": "app", "dependencies": {}}), encoding="utf-8"
+ )
+ dep_dir = tmp_path / "node_modules" / "some-dep"
+ dep_dir.mkdir(parents=True)
+ (dep_dir / "tsconfig.json").write_text("{}", encoding="utf-8")
+ items = detect_tech_stack(tmp_path)
+ names = [i.name for i in items]
+ assert "TypeScript" not in names
+
+
+def test_fixture_csproj_does_not_make_repo_csharp(tmp_path):
+ # A Python repo with .NET solutions under tests/fixtures and vendored
+ # sample repos must not be labelled a C# codebase by its own test data.
+ (tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n", encoding="utf-8")
+ for parent in ("tests/fixtures/dotnet_solution/src/Api", "test-repos/eShop/src/Api"):
+ d = tmp_path / parent
+ d.mkdir(parents=True)
+ (d / "Api.csproj").write_text("<Project></Project>", encoding="utf-8")
+ (tmp_path / "test-repos" / "eShop" / "eShop.sln").write_text("", encoding="utf-8")
+ items = detect_tech_stack(tmp_path)
+ names = [i.name for i in items]
+ assert "C#" not in names
+ assert ".NET" not in names
+ assert "Python" in names
+
+
+def test_nested_git_repo_csproj_is_not_stack_evidence(tmp_path):
+ # Vendored checkouts (benchmark repos, sibling clones) are separate git
+ # repos — their project files must not define this repo's tech stack.
+ (tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n", encoding="utf-8")
+ nested = tmp_path / "bench-repos" / "nethermind"
+ (nested / ".git").mkdir(parents=True)
+ proj = nested / "tools" / "Evm"
+ proj.mkdir(parents=True)
+ (proj / "Evm.csproj").write_text("<Project></Project>", encoding="utf-8")
+ (nested / "Nethermind.sln").write_text("", encoding="utf-8")
+ items = detect_tech_stack(tmp_path)
+ names = [i.name for i in items]
+ assert "C#" not in names
+ assert ".NET" not in names
+
+
+def test_real_dotnet_repo_still_detected(tmp_path):
+ d = tmp_path / "src" / "Web"
+ d.mkdir(parents=True)
+ (d / "Web.csproj").write_text(
+ "<Project><PropertyGroup><TargetFramework>net9.0</TargetFramework>"
+ "</PropertyGroup></Project>",
+ encoding="utf-8",
+ )
+ items = detect_tech_stack(tmp_path)
+ names = [i.name for i in items]
+ assert "C#" in names
+ assert ".NET" in names
+
+
def test_detects_rust_from_cargo_toml(tmp_path):
(tmp_path / "Cargo.toml").write_text(
'[package]\nname = "myapp"\nversion = "0.1.0"\n', encoding="utf-8"
diff --git a/tests/unit/server/mcp/test_context.py b/tests/unit/server/mcp/test_context.py
index 4d6f10ad0..54694f636 100644
--- a/tests/unit/server/mcp/test_context.py
+++ b/tests/unit/server/mcp/test_context.py
@@ -203,11 +203,28 @@ async def test_get_context_include_filter(setup_mcp):
result = await get_context(["src/auth/service.py"], include=["docs"])
t = result["targets"]["src/auth/service.py"]
+ # docs + freshness are the always-on defaults (the tool contract says
+ # "defaults are always returned"); include only ADDS blocks.
assert "docs" in t
+ assert "freshness" in t
assert "ownership" not in t
assert "last_change" not in t
assert "decisions" not in t
- assert "freshness" not in t
+
+
+async def test_get_context_skeleton_keeps_default_card(setup_mcp):
+ """include=["skeleton"] must not silently drop the summary/freshness card."""
+ from repowise.server.mcp_server import get_context
+
+ result = await get_context(["src/auth/service.py"], include=["skeleton"])
+ t = result["targets"]["src/auth/service.py"]
+ assert "freshness" in t
+ assert "docs" in t
+ assert t["docs"].get("summary")
+ # ...but the symbol list is suppressed: the skeleton already carries
+ # every signature, so repeating it in docs would double the response.
+ assert "symbols" not in t["docs"]
@pytest.mark.asyncio
diff --git a/tests/unit/server/mcp/test_overview_helpers.py b/tests/unit/server/mcp/test_overview_helpers.py
new file mode 100644
index 000000000..b5ab6dc80
--- /dev/null
+++ b/tests/unit/server/mcp/test_overview_helpers.py
@@ -0,0 +1,41 @@
+"""Unit tests for get_overview's pure rendering helpers."""
+
+from __future__ import annotations
+
+from repowise.server.mcp_server.tool_overview import (
+ _module_description,
+ _truncate_at_word,
+)
+
+
+class TestTruncateAtWord:
+ def test_short_unchanged(self):
+ assert _truncate_at_word("short", 120) == "short"
+
+ def test_cuts_at_word_boundary_with_ellipsis(self):
+ text = (
+ "Implements the server-side application logic for MCP tooling, "
+ "including budget/risk/meta helpers and request/response handling"
+ )
+ out = _truncate_at_word(text, 120)
+ assert out.endswith("…")
+ # No mid-word fragment: every word emitted exists in the source.
+ for word in out.rstrip("…").split():
+ assert word in text
+
+
+class TestModuleDescription:
+ def test_strips_overview_boilerplate(self):
+ content = "## Overview\n\nThe `core/distill` module is the distillation subsystem."
+ out = _module_description(content)
+ assert not out.startswith("##")
+ assert out.startswith("The `core/distill` module")
+
+ def test_truncates_long_prose_at_word(self):
+ content = "## Overview\n\n" + ("word " * 100)
+ out = _module_description(content, limit=50)
+ assert len(out) <= 51
+ assert out.endswith("…")
+
+ def test_empty_content(self):
+ assert _module_description("") == ""
diff --git a/tests/unit/server/mcp/test_search.py b/tests/unit/server/mcp/test_search.py
index f1d9c69cd..9fbc562fa 100644
--- a/tests/unit/server/mcp/test_search.py
+++ b/tests/unit/server/mcp/test_search.py
@@ -29,3 +29,34 @@ async def test_search_codebase(setup_mcp):
result = await search_codebase("authentication service")
assert "results" in result
assert len(result["results"]) >= 1
+
+
+class TestClassifyHitKind:
+ """The ``kind`` filter's path heuristic."""
+
+ def test_decision_record_is_doc(self):
+ # Regression: decision records carry an empty target_path and used
+ # to fall through the path heuristics into "implementation", so
+ # kind="implementation" returned decision pages instead of code.
+ from repowise.server.mcp_server.tool_search import _classify_hit_kind
+
+ assert _classify_hit_kind("", "decision_record") == "doc"
+
+ def test_overview_and_onboarding_are_doc(self):
+ from repowise.server.mcp_server.tool_search import _classify_hit_kind
+
+ assert _classify_hit_kind("", "repo_overview") == "doc"
+ assert _classify_hit_kind("onboarding/guided_tour", "onboarding") == "doc"
+
+ def test_file_page_paths_classify_by_role(self):
+ from repowise.server.mcp_server.tool_search import _classify_hit_kind
+
+ assert _classify_hit_kind("src/auth/service.py", "file_page") == "implementation"
+ assert _classify_hit_kind("tests/unit/test_auth.py", "file_page") == "test"
+ assert _classify_hit_kind("pyproject.toml", "file_page") == "config"
+ assert _classify_hit_kind("docs/guide.md", "file_page") == "doc"
+
+ def test_module_page_is_doc(self):
+ from repowise.server.mcp_server.tool_search import _classify_hit_kind
+
+ assert _classify_hit_kind("src/auth", "module_page") == "doc"