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(context): rank and cap the symbol card, and preview docs by counts (#3010)

Raghav Chamadiya07e9f1646218
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index b37cd53ef..806f096fc 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -162,12 +162,14 @@ A triage card for files, modules or symbols: summary, symbols with signatures an
| Parameter | Type | Default | Meaning |
|-----------|------|---------|---------|
| `targets` | list[string] | required | File paths, module paths, or `"path::Symbol"` ids |
-| `include` | list[string] | none | Any of `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `metrics`, `community`, `decisions`, `skeleton`, `health`, `doc_drift` |
+| `include` | list[string] | none | Any of `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `metrics`, `community`, `decisions`, `skeleton`, `health`, `doc_drift`, `symbols` |
| `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) |
**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 file's compact symbol list holds its top 15 symbols: types (classes, interfaces, structs, traits, enums, type aliases, impls, modules) first, then functions and methods, then the rest, each group by centrality. `symbols_truncated` gives the total, and `include=["symbols"]` lists them all. When the response budget trims the list further, it keeps symbols by kind and name match, not centrality. A row without `symbol_id` is `path::name`; methods and overload variants carry theirs, so pass a row's id to `get_symbol` when it has one.
+
`skeleton` renders a file with bodies elided: every signature, the imports, and the bodies of its most central symbols, with line ranges on every elision. `doc_drift` lists the documents that name the file and whether they carry drift. An empty `callers` or `callees` list comes with a `*_basis` saying how much of that language's calls the graph resolved; read it before concluding nothing calls a symbol.
```
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index a7d18f918..7b7d96dc4 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -581,7 +581,7 @@ call.
| Flag | Description |
|------|-------------|
-| `--include` | Opt-in block, repeatable: `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `metrics`, `community`, `decisions`, `health`, `skeleton`, `doc_drift` |
+| `--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 |
```bash
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index 6feab1eaf..b65f2162a 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -134,17 +134,17 @@ Per target, under `targets`:
| Field | Meaning |
|-------|---------|
-| title, summary, symbols | Docs summary and the symbols defined, with signatures and line numbers |
+| title, summary, symbols | Docs summary and the symbols defined, with signatures and line numbers. Compact cards list the top 15 (types, then functions and methods, then the rest, by centrality) with `symbols_truncated` `{shown, total, hint}` and `symbols_total`; a budget trim below that keeps symbols by kind and name match, not centrality; `include=["symbols"]` lists all. A row without `symbol_id` is `path::name` |
| `hotspot` | Churn flag |
| `fix_history` | Only on files with counted bug fixes: count, age, `bug_magnet`. A cue to call `get_risk` |
| `episodes` | Count of dated records bound to the target; `get_why` serves their bodies |
| decisions | Titles by default. With `include=["decisions"]`, three lanes: `decisions` (accepted, governing), `candidates` (proposed, at most 3), `history` (accepted then withdrawn, at most 2) |
-| `file_preview` | For a file with no indexed symbols: line and character counts, plus the heading spine for markdown or the first lines otherwise |
+| `file_preview` | For a file with no indexed symbols: `lines`, `chars`, and for a markdown or reST document `heading_count` with the first three `headings`; otherwise the first three non-empty lines as `head` |
| `resolved_to`, `note` | A `path::Name` target whose symbol did not resolve answers with the file's card instead |
| `cross_repo` | Workspace mode: `co_changes_with` partners in other repos and contract `consumers` / `providers` |
| `*_basis` | Beside an empty `callers`, `callees` or `used_by`: the language, how many call edges the index resolved for it, and the share that are guesses. An empty list means no resolved edge, not proof of none |
-Opt-in blocks: `full_doc`, `ownership` (primary owner, bus factor, contributor count), `last_change`, `callers`, `callees`, `metrics` (PageRank, betweenness, percentiles), `community`, `skeleton`, `health`, `doc_drift`.
+Opt-in blocks: `full_doc`, `ownership` (primary owner, bus factor, contributor count), `last_change`, `callers`, `callees`, `metrics` (PageRank, betweenness, percentiles), `community`, `skeleton`, `health`, `doc_drift`, `symbols` (every symbol of a file).
**Skeleton.** Sliced from the index's stored symbol bounds, with no parsing at query time: every signature, the import preamble, and the bodies of the top symbols ranked by centrality, hotspot and query match. Elision markers carry 1-indexed line ranges, so you can read any part back.
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-context.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-context.md
index 940c37923..d634979a6 100644
--- a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-context.md
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-context.md
@@ -35,7 +35,8 @@ repowise context src/api/routes.py --include skeleton
`--include skeleton` adds the body-elided, line-verified file shape. For the
exact function body, prefer `/prompts:repowise-symbol` (or `get_symbol`) with a
-`symbol_id` from the card.
+`symbol_id` from the card; a symbol row without one is addressed as
+`path::name`.
Shared targeting flags (`--path`, `--repo`, `--no-workspace`) work the same as
the other tool-adapter commands.
diff --git a/packages/cli/src/repowise/cli/commands/context_cmd.py b/packages/cli/src/repowise/cli/commands/context_cmd.py
index 50c8a5874..37b40c771 100644
--- a/packages/cli/src/repowise/cli/commands/context_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/context_cmd.py
@@ -20,6 +20,7 @@ _INCLUDE_BLOCKS = (
"health",
"skeleton",
"doc_drift",
+ "symbols",
)
#: Card keys the projection replaces or drops. Everything else passes through.
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 c129fb533..7b2c059e4 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
@@ -26,6 +26,7 @@ Optional ``include`` parameter widens the response:
- include=["skeleton"] → body-elided file rendering (signatures + top-PageRank bodies)
- include=["health"] → code-health scores and biomarkers for the target
- include=["doc_drift"] → documents that name this file, and their drift
+ - include=["symbols"] → every symbol in a file card, not the ranked top 15
An unrecognised key is dropped and named in ``ignored_arguments`` rather than
silently ignored: an unknown key otherwise produces exactly the response the
@@ -82,6 +83,7 @@ _INCLUDE_BLOCKS = frozenset(
"skeleton",
"health",
"doc_drift",
+ "symbols",
}
)
@@ -128,8 +130,9 @@ async def get_context(
"""Triage card for files / modules / symbols — relationships, not source bytes.
Returns title, summary, signatures with line numbers, hotspot bit, and
- decision_record titles. fix_history appears only on files with counted bug
- fixes (count, age, bug_magnet); hotspot is churn. Either one is a cue to
+ 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 — what
happened here and why — and appears only when there is at least one;
get_why serves the bodies. A symbol target is counted as its file, and a
@@ -147,7 +150,9 @@ async def get_context(
targets: file paths, module paths, or "path::Symbol" ids.
include: opt-in blocks: full_doc | ownership | last_change | callers
| callees | metrics | community | decisions | skeleton | health
- | doc_drift (documents naming this file).
+ | doc_drift (documents naming this file) | symbols (all of a
+ file's symbols; the default lists the top 15, classes and
+ functions first).
An unrecognised key is named in ignored_arguments.
compact: default True; False adds structure+imports+docstrings.
repo: usually omitted.
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 3a321a4c8..cf951790b 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
@@ -82,6 +82,60 @@ _MAX_DECISION_HISTORY = 2
#: 32,766 after, and which applies depends on the libsqlite3 linked at runtime.
_RANK_LOOKUP_CHUNK = 500
+#: Rows the compact symbol list carries unless ``include=["symbols"]``. The
+#: head of a file is mostly constants and type vars; ranked, 15 rows cover a
+#: file's types and functions in most real files.
+_SYMBOL_CAP = 15
+
+# Card rank by ``SymbolKind``: the types a file defines, then its callables,
+# then values. Wider than the budgeter's ``symbol_priority`` table, which
+# ranks ``type_alias``, ``impl`` and ``module`` with variables.
+_TYPE_KINDS = frozenset(
+ {"class", "interface", "struct", "trait", "enum", "type", "type_alias", "impl", "module"}
+)
+_CALLABLE_KINDS = frozenset({"function", "method", "macro", "decorator"})
+
+
+def _kind_rank(kind: str | None) -> int:
+ kind = (kind or "").lower()
+ return 0 if kind in _TYPE_KINDS else 1 if kind in _CALLABLE_KINDS else 2
+
+
+async def _compact_symbol_rows(
+ session: AsyncSession, repo_id: str, file_path: str, symbols: Any
+) -> list[dict[str, Any]]:
+ """Compact rows ranked by kind, then PageRank, then start line.
+
+ ``symbol_id`` is omitted when it is exactly ``path::name``, which the
+ reader can rebuild; methods and overload variants keep theirs, because a
+ bare ``path::name`` does not resolve them uniquely.
+ """
+ res = await session.execute(
+ select(GraphNode.node_id, GraphNode.pagerank).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.file_path == file_path,
+ )
+ )
+ rank = {node_id: float(pr or 0.0) for node_id, pr in res.all()}
+ path = path_identity(file_path)
+ scored = []
+ for s in symbols:
+ row: dict[str, Any] = {
+ "name": s.name,
+ "kind": s.kind,
+ "signature": _clean_signature(s.signature),
+ "line": s.start_line,
+ }
+ sid = symbol_identity(s.symbol_id)
+ if sid != f"{path}::{s.name}":
+ row["symbol_id"] = sid
+ scored.append(
+ ((_kind_rank(s.kind), -rank.get(s.symbol_id, 0.0), s.start_line or 0), row)
+ )
+ scored.sort(key=lambda pair: pair[0])
+ return [row for _, row in scored]
+
+
# The default file card is the symbol list; the skeleton is opt-in via
# ``include=["skeleton"]``. An auto-upgraded card was mostly source text, which
# a direct Read serves more cheaply, so measure card sizes before restoring one.
@@ -120,40 +174,124 @@ def _preview_summary(file_path: str, preview: dict[str, Any]) -> str:
lines = preview.get("lines", 0)
if not lines:
return f"{name}: empty file"
- headings = preview.get("headings")
- if headings:
- return f"{name}: {lines}-line document, {len(headings)} headings, no indexed symbols."
+ heading_count = preview.get("heading_count")
+ if heading_count:
+ return f"{name}: {lines}-line document, {heading_count} headings, no indexed symbols."
return f"{name}: {lines} lines, no indexed symbols."
-# Bounds on the preview a symbol-less file (README, YAML, SQL) gets, cheap
-# enough to stay on by default.
-_PREVIEW_MAX_LINES = 15
+# Bounds on the preview a symbol-less file (README, YAML, SQL) gets: counts
+# plus a few verbatim lines, cheap enough to stay on by default.
+_PREVIEW_MAX_LINES = 3
_PREVIEW_MAX_LINE_CHARS = 120
# Beyond this the file is big enough that a preview would misrepresent it; the
# counts and the "go Read it" note are the honest reply.
_PREVIEW_MAX_BYTES = 2_000_000
-_MARKDOWN_EXTS = (".md", ".markdown", ".mdx", ".rst")
+_MARKDOWN_EXTS = (".md", ".markdown", ".mdx")
+_RST_EXTS = (".rst",)
+_MD_HEADING = re.compile(r" {0,3}#{1,6}(\s|$)")
+_MD_FENCE = re.compile(r" {0,3}(`{3,}|~{3,})")
+_RST_ADORNMENT = re.compile(r"([!-/:-@\[-`{-~])\1+")
+# Lines that open with a comment marker: licence banners and the like.
+_COMMENT_PREFIXES = ("#", "//", "--", "/*", "*", "<!--")
+
+
+def _markdown_headings(lines: list[str]) -> list[str]:
+ """ATX headings outside front matter, fenced code and HTML comments."""
+ headings: list[str] = []
+ start = 0
+ if lines and lines[0].strip() == "---":
+ close = next((i for i in range(1, len(lines)) if lines[i].strip() in ("---", "...")), None)
+ if close is not None:
+ start = close + 1
+ fence = ""
+ in_comment = False
+ for ln in lines[start:]:
+ if in_comment:
+ in_comment = "-->" not in ln
+ continue
+ if fence:
+ # Only a bare run of the opening character, at least as long, closes.
+ bare = ln.strip()
+ if bare and set(bare) == {fence[0]} and len(bare) >= len(fence):
+ fence = ""
+ continue
+ m = _MD_FENCE.match(ln)
+ if m:
+ fence = m.group(1)
+ continue
+ opened = ln.find("<!--")
+ if opened != -1 and "-->" not in ln[opened + 4 :]:
+ in_comment = True
+ continue
+ if _MD_HEADING.match(ln):
+ headings.append(ln.strip())
+ return headings
+
+
+def _rst_table_lines(lines: list[str]) -> set[int]:
+ """Line indexes inside simple tables: a blank-free block with 3+ ``=`` borders."""
+ inside: set[int] = set()
+ i = 0
+ while i < len(lines):
+ if not lines[i].strip():
+ i += 1
+ continue
+ j = i
+ while j < len(lines) and lines[j].strip():
+ j += 1
+ borders = sum(1 for k in range(i, j) if set(lines[k].strip()) <= {"=", " "})
+ if borders >= 3 and set(lines[i].strip()) <= {"=", " "}:
+ inside.update(range(i, j))
+ i = j
+ return inside
+
+
+def _rst_headings(lines: list[str]) -> list[str]:
+ """Section titles: an unindented line underlined by punctuation at least as long.
+
+ Indented lines (literal and directive bodies) are never titles, so a
+ ``# comment`` inside a ``code-block`` is not one either, and neither is a
+ row of a simple table framed by ``=`` borders.
+ """
+ tables = _rst_table_lines(lines)
+ headings: list[str] = []
+ for i in range(len(lines) - 1):
+ title, under = lines[i].rstrip(), lines[i + 1].rstrip()
+ if (
+ i not in tables
+ and title
+ and not title[0].isspace()
+ and not _RST_ADORNMENT.fullmatch(title)
+ and _RST_ADORNMENT.fullmatch(under)
+ and len(under) >= len(title)
+ ):
+ headings.append(title)
+ return headings
def _outline_lines(text: str, file_path: str) -> tuple[str, list[str]]:
- """Pick the most informative ~15 lines of a symbol-less file.
+ """Return a document's headings, or the head lines of anything else.
- Markdown-ish files get their heading spine, which is a genuine table of
- contents. Everything else gets its first non-blank, non-comment lines,
- which for config and data files is where the keys live. Returns the kind of
- excerpt chosen so the caller can label it truthfully.
+ Returns the kind of excerpt chosen so the caller can label it truthfully.
+ A heading-less document falls through to head lines rather than reporting
+ an empty outline. Head lines skip comment banners unless that is all
+ the file has.
"""
lines = text.splitlines()
- if file_path.lower().endswith(_MARKDOWN_EXTS):
- headings = [ln.strip() for ln in lines if ln.lstrip().startswith("#")]
- # An .rst or heading-less .md falls through to the head-lines form
- # rather than reporting an empty outline.
- if headings:
- return "headings", headings[:_PREVIEW_MAX_LINES]
+ lower = file_path.lower()
+ if lower.endswith(_MARKDOWN_EXTS):
+ headings = _markdown_headings(lines)
+ elif lower.endswith(_RST_EXTS):
+ headings = _rst_headings(lines)
+ else:
+ headings = []
+ if headings:
+ return "headings", headings
head = [ln.rstrip() for ln in lines if ln.strip()]
- return "head", head[:_PREVIEW_MAX_LINES]
+ content = [ln for ln in head if not ln.lstrip().startswith(_COMMENT_PREFIXES)]
+ return "head", content or head
def _file_preview(repo_root: Any, file_path: str) -> dict[str, Any] | None:
@@ -177,12 +315,12 @@ def _file_preview(repo_root: Any, file_path: str) -> dict[str, Any] | None:
return preview
kind, excerpt = _outline_lines(text, file_path)
+ if kind == "headings":
+ preview["heading_count"] = len(excerpt)
if excerpt:
- preview[kind] = [ln[:_PREVIEW_MAX_LINE_CHARS] for ln in excerpt]
+ preview[kind] = [ln[:_PREVIEW_MAX_LINE_CHARS] for ln in excerpt[:_PREVIEW_MAX_LINES]]
preview["note"] = (
- "This file has no indexed symbols, so there is no structural card for "
- "it. The fields above are counts and verbatim excerpts. Read the file "
- "for its full content."
+ "No indexed symbols; counts and a short excerpt only. Read the file for its content."
)
return preview
@@ -448,12 +586,13 @@ async def _resolve_one_target(
if target_type is None and "::" in target:
file_part = target.split("::", 1)[0]
if file_part and file_part != target and not is_excluded(file_part, exclude_spec):
- # file_part contains no "::", so this recursion is depth-1.
+ # file_part contains no "::", so this recursion is depth-1. The
+ # caller is hunting for a name, so the symbol list is uncapped.
card = await _resolve_one_target(
session,
repository,
file_part,
- include,
+ None if include is None else include | {"symbols"},
compact,
exclude_spec=exclude_spec,
repo_root=repo_root,
@@ -557,6 +696,7 @@ async def _resolve_one_target(
}
want_skeleton = bool(include and "skeleton" in include)
+ want_all_symbols = bool(include and "symbols" in include)
# --- Docs ---
# "full_doc" implies "docs" — entering the docs block whenever either is requested.
@@ -573,10 +713,12 @@ async def _resolve_one_target(
docs["human_notes"] = page.human_notes
# Symbols in this file
res = await session.execute(
- select(WikiSymbol).where(
+ select(WikiSymbol)
+ .where(
WikiSymbol.repository_id == repo_id,
WikiSymbol.file_path == target,
)
+ .order_by(WikiSymbol.start_line, WikiSymbol.symbol_id)
)
symbols = res.scalars().all()
classes = [s.name for s in symbols if s.kind == "class"]
@@ -587,26 +729,17 @@ async def _resolve_one_target(
if not docs.get("summary"):
docs["summary"] = _synthesize_structural_summary(target, classes, functions)
elif compact:
- # Compact: name, kind, signature, line and symbol_id only. The
- # cap stops a dense generated file blowing the budget; symbols
- # are in start_line order, so the head is the useful slice.
- symbol_cap = 40
- visible = list(symbols)[:symbol_cap]
- docs["symbols"] = [
- {
- "name": s.name,
- "kind": s.kind,
- "signature": _clean_signature(s.signature),
- "line": s.start_line,
- "symbol_id": symbol_identity(s.symbol_id),
- }
- for s in visible
- ]
- if len(symbols) > symbol_cap:
+ docs["symbols"] = await _compact_symbol_rows(
+ session, repo_id, target, symbols
+ )
+ if not want_all_symbols and len(symbols) > _SYMBOL_CAP:
+ docs["symbols"] = docs["symbols"][:_SYMBOL_CAP]
+ # The budgeter's own total, so a later trim cannot report 15.
+ docs["symbols_total"] = len(symbols)
docs["symbols_truncated"] = {
- "shown": symbol_cap,
+ "shown": _SYMBOL_CAP,
"total": len(symbols),
- "hint": "Call with compact=False or include=['full_doc'] for the full list.",
+ "hint": "Pass include=['symbols'] for the full list.",
}
if not docs.get("summary"):
docs["summary"] = _synthesize_structural_summary(target, classes, functions)
diff --git a/plugins/claude-code/commands/context.md b/plugins/claude-code/commands/context.md
index 46af46ee9..f4943cb4c 100644
--- a/plugins/claude-code/commands/context.md
+++ b/plugins/claude-code/commands/context.md
@@ -36,7 +36,8 @@ repowise context src/api/routes.py --include skeleton
`--include skeleton` adds the body-elided, line-verified file shape. For the
exact function body, prefer `/repowise:symbol` (or `get_symbol`) with a
-`symbol_id` from the card.
+`symbol_id` from the card; a symbol row without one is addressed as
+`path::name`.
Shared targeting flags (`--path`, `--repo`, `--no-workspace`) work the same as
the other tool-adapter commands.
diff --git a/plugins/claude-code/skills/codebase-exploration/SKILL.md b/plugins/claude-code/skills/codebase-exploration/SKILL.md
index ed0d14748..961b00161 100644
--- a/plugins/claude-code/skills/codebase-exploration/SKILL.md
+++ b/plugins/claude-code/skills/codebase-exploration/SKILL.md
@@ -22,7 +22,7 @@ plain file reads don't, usually in one round-trip instead of many.
| First orientation in an unfamiliar repo | `get_overview()` — architecture summary, key modules, entry points, git health, knowledge map. Skip it once you have the map. |
| A direct answer to "how/where/why does X work" | `get_answer(question="…")` — synthesised answer with citations + a `retrieval_quality` signal. Collapses the search → read → reason loop. |
| Find a symbol, file, or fuzzy concept | `search_codebase(query="…")` — hybrid search. `mode="auto"` routes an identifier to indexed symbol hits (`symbol_id`/line bounds → pipe into `get_symbol`), a path to file pages (→ `get_context`), and prose to semantic wiki search (each hit reports `search_method`: `embedding` vs `bm25`). Force a branch with `mode=symbol\|path\|concept\|hybrid`; narrow symbols with `symbol_kind`. |
-| A triage card for specific files/symbols | `get_context(targets=[…])` — title, summary, signatures, hotspot bit, top callers, decision titles, symbol_ids. Batch many targets in one call. |
+| A triage card for specific files/symbols | `get_context(targets=[…])` — title, summary, signatures, hotspot bit, top callers, decision titles, symbol_ids (a row without one is `path::name`). Batch many targets in one call. |
| The actual source of one symbol | `get_symbol("path/to/file.py::Name")` — exact bytes with line bounds. Cheaper than Read + offset math. Use a `symbol_id` from `get_context`. |
## Recommended flow
diff --git a/plugins/codex/skills/codebase-exploration/SKILL.md b/plugins/codex/skills/codebase-exploration/SKILL.md
index 38020b78c..b32139603 100644
--- a/plugins/codex/skills/codebase-exploration/SKILL.md
+++ b/plugins/codex/skills/codebase-exploration/SKILL.md
@@ -17,7 +17,7 @@ plain file reads don't, usually in one round-trip instead of many.
| First orientation in an unfamiliar repo | `get_overview()` — architecture summary, key modules, entry points, git health, knowledge map. Skip it once you have the map. |
| A direct answer to "how/where/why does X work" | `get_answer(question="…")` — synthesised answer with citations + a `retrieval_quality` signal. Collapses the search → read → reason loop. |
| Find a symbol, file, or fuzzy concept | `search_codebase(query="…")` — hybrid search. `mode="auto"` routes an identifier to indexed symbol hits (`symbol_id`/line bounds → pipe into `get_symbol`), a path to file pages (→ `get_context`), and prose to semantic wiki search (each hit reports `search_method`: `embedding` vs `bm25`). Force a branch with `mode=symbol\|path\|concept\|hybrid`; narrow symbols with `symbol_kind`. |
-| A triage card for specific files/symbols | `get_context(targets=[…])` — title, summary, signatures, hotspot bit, top callers, decision titles, symbol_ids. Batch many targets in one call. |
+| A triage card for specific files/symbols | `get_context(targets=[…])` — title, summary, signatures, hotspot bit, top callers, decision titles, symbol_ids (a row without one is `path::name`). Batch many targets in one call. |
| The actual source of one symbol | `get_symbol("path/to/file.py::Name")` — exact bytes with line bounds. Cheaper than Read + offset math. Use a `symbol_id` from `get_context`. |
## Recommended flow
diff --git a/plugins/shared/commands/context.md b/plugins/shared/commands/context.md
index fe64c2e9b..642264288 100644
--- a/plugins/shared/commands/context.md
+++ b/plugins/shared/commands/context.md
@@ -37,7 +37,8 @@ repowise context src/api/routes.py --include skeleton
`--include skeleton` adds the body-elided, line-verified file shape. For the
exact function body, prefer `{{cmd:symbol}}` (or `get_symbol`) with a
-`symbol_id` from the card.
+`symbol_id` from the card; a symbol row without one is addressed as
+`path::name`.
Shared targeting flags (`--path`, `--repo`, `--no-workspace`) work the same as
the other tool-adapter commands.
diff --git a/plugins/shared/skills/codebase-exploration.md b/plugins/shared/skills/codebase-exploration.md
index c93cda767..ac24979f0 100644
--- a/plugins/shared/skills/codebase-exploration.md
+++ b/plugins/shared/skills/codebase-exploration.md
@@ -30,7 +30,7 @@ plain file reads don't, usually in one round-trip instead of many.
| First orientation in an unfamiliar repo | `get_overview()` — architecture summary, key modules, entry points, git health, knowledge map. Skip it once you have the map. |
| A direct answer to "how/where/why does X work" | `get_answer(question="…")` — synthesised answer with citations + a `retrieval_quality` signal. Collapses the search → read → reason loop. |
| Find a symbol, file, or fuzzy concept | `search_codebase(query="…")` — hybrid search. `mode="auto"` routes an identifier to indexed symbol hits (`symbol_id`/line bounds → pipe into `get_symbol`), a path to file pages (→ `get_context`), and prose to semantic wiki search (each hit reports `search_method`: `embedding` vs `bm25`). Force a branch with `mode=symbol\|path\|concept\|hybrid`; narrow symbols with `symbol_kind`. |
-| A triage card for specific files/symbols | `get_context(targets=[…])` — title, summary, signatures, hotspot bit, top callers, decision titles, symbol_ids. Batch many targets in one call. |
+| A triage card for specific files/symbols | `get_context(targets=[…])` — title, summary, signatures, hotspot bit, top callers, decision titles, symbol_ids (a row without one is `path::name`). Batch many targets in one call. |
| The actual source of one symbol | `get_symbol("path/to/file.py::Name")` — exact bytes with line bounds. Cheaper than Read + offset math. Use a `symbol_id` from `get_context`. |
## Recommended flow
diff --git a/tests/unit/server/mcp/test_context_file_preview.py b/tests/unit/server/mcp/test_context_file_preview.py
index a78728485..0ea54b9cd 100644
--- a/tests/unit/server/mcp/test_context_file_preview.py
+++ b/tests/unit/server/mcp/test_context_file_preview.py
@@ -77,6 +77,82 @@ def test_markdown_preview_returns_the_heading_spine(tmp_path) -> None:
assert preview["chars"] > 0
+def test_preview_is_counts_plus_three_lines(tmp_path) -> None:
+ """The heading count is whole; only three headings ride along verbatim."""
+ body = "".join(f"## H{i}\n\ntext\n\n" for i in range(10))
+ (tmp_path / "long.md").write_text(body, encoding="utf-8")
+ preview = _file_preview(tmp_path, "long.md")
+ assert preview["heading_count"] == 10
+ assert preview["headings"] == ["## H0", "## H1", "## H2"]
+ (tmp_path / "long.txt").write_text("".join(f"l{i}\n" for i in range(10)), encoding="utf-8")
+ assert _file_preview(tmp_path, "long.txt")["head"] == ["l0", "l1", "l2"]
+
+
+def test_comments_in_a_fenced_block_are_not_markdown_headings(tmp_path) -> None:
+ """A ``#`` line inside a code fence is a shell or Python comment."""
+ (tmp_path / "f.md").write_text(
+ "# Title\n\n```bash\n# install it\npip install x\n```\n\n"
+ "~~~\n# also code\n~~~\n\n## Usage\n#hashtag is not a heading\n",
+ encoding="utf-8",
+ )
+ preview = _file_preview(tmp_path, "f.md")
+ assert preview["headings"] == ["# Title", "## Usage"]
+ assert preview["heading_count"] == 2
+
+
+def test_rst_headings_come_from_adornment_not_hash_lines(tmp_path) -> None:
+ """In reST a section title is underlined; ``#`` lines are code or list items."""
+ (tmp_path / "g.rst").write_text(
+ "=====\nGuide\n=====\n\nIntro.\n\nInstall\n-------\n\n"
+ ".. code-block:: python\n\n # a comment\n x = 1\n\n"
+ "#. first item\n#. second item\n\nToo short\n---\n\nUsage\n~~~~~\n",
+ encoding="utf-8",
+ )
+ preview = _file_preview(tmp_path, "g.rst")
+ assert preview["headings"] == ["Guide", "Install", "Usage"]
+ assert preview["heading_count"] == 3
+
+
+def test_a_fence_closes_only_on_a_bare_marker(tmp_path) -> None:
+ """```python inside an open fence is code, not the fence's end."""
+ (tmp_path / "n.md").write_text(
+ "# Top\n\n```\n```python\n# still code\n```\n\n## After\n",
+ encoding="utf-8",
+ )
+ assert _file_preview(tmp_path, "n.md")["headings"] == ["# Top", "## After"]
+
+
+def test_front_matter_and_html_comments_hold_no_headings(tmp_path) -> None:
+ (tmp_path / "fm.md").write_text(
+ "---\ntitle: x\n# yaml comment\n---\n\n<!--\n# commented out\n-->\n"
+ "<!-- # inline --> \n# Real\n",
+ encoding="utf-8",
+ )
+ preview = _file_preview(tmp_path, "fm.md")
+ assert preview["headings"] == ["# Real"]
+ assert preview["heading_count"] == 1
+
+
+def test_rst_simple_table_rows_are_not_titles(tmp_path) -> None:
+ (tmp_path / "t.rst").write_text(
+ "Guide\n=====\n\n=====\nName\n=====\nfoo\nbar\n=====\n\nUsage\n-----\n",
+ encoding="utf-8",
+ )
+ assert _file_preview(tmp_path, "t.rst")["headings"] == ["Guide", "Usage"]
+
+
+def test_head_lines_skip_a_comment_banner(tmp_path) -> None:
+ """A licence banner says nothing about the file; its keys do."""
+ (tmp_path / "b.yaml").write_text(
+ "# Copyright 2026 Example\n# Licensed under the Apache License\n#\n"
+ "name: svc\nport: 8080\nreplicas: 2\nimage: x\n",
+ encoding="utf-8",
+ )
+ assert _file_preview(tmp_path, "b.yaml")["head"] == ["name: svc", "port: 8080", "replicas: 2"]
+ (tmp_path / "only.sh").write_text("# just a comment\n", encoding="utf-8")
+ assert _file_preview(tmp_path, "only.sh")["head"] == ["# just a comment"]
+
+
def test_non_markdown_preview_returns_head_lines(tmp_path) -> None:
"""Config and data files keep their keys at the top, so head lines carry them."""
(tmp_path / "c.yaml").write_text("\n\nname: svc\nport: 8080\n", encoding="utf-8")
@@ -145,6 +221,7 @@ async def test_symbolless_file_card_carries_a_preview(
)
preview = card["docs"]["file_preview"]
assert preview["headings"] == ["# Guide", "## Install", "## Usage"]
+ assert preview["heading_count"] == 3
assert preview["lines"] == 11
assert "Read the file" in preview["note"]
# The stub summary contradicted the preview sitting beside it.
diff --git a/tests/unit/server/mcp/test_context_symbol_card.py b/tests/unit/server/mcp/test_context_symbol_card.py
new file mode 100644
index 000000000..e847533ee
--- /dev/null
+++ b/tests/unit/server/mcp/test_context_symbol_card.py
@@ -0,0 +1,129 @@
+"""The compact file card lists a file's most useful symbols, not its first ones.
+
+A file's head is mostly constants and type vars, so a start-line slice spent
+the card on them. The card now ranks by kind, then PageRank, caps the list,
+names how to get the rest, and drops a ``symbol_id`` only when it is exactly
+``path::name``.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.persistence.models import GraphNode, Repository, WikiSymbol
+from repowise.server.mcp_server.tool_context.targets import _SYMBOL_CAP, _resolve_one_target
+
+_FILE = "src/dense.py"
+_DEFAULT = {"docs", "freshness"}
+
+
+async def repository(session, populated_db) -> Repository:
+ return await session.get(Repository, populated_db)
+
+
+async def dense_file(session, populated_db) -> None:
+ """18 module variables first, then 3 classes, 4 functions, 2 variants, a type alias."""
+ rid = populated_db
+ session.add(
+ GraphNode(
+ id="gn-dense", repository_id=rid, node_id=_FILE, node_type="file", language="python"
+ )
+ )
+ rows: list[tuple[str, str, str]] = [(f"VAR_{i}", "variable", f"VAR_{i}") for i in range(18)]
+ rows += [(f"Klass{i}", "class", f"Klass{i}") for i in range(3)]
+ rows += [(f"fn_{i}", "function", f"fn_{i}") for i in range(4)]
+ rows += [("run", "method", "Klass0::run"), ("fn_0", "function", "fn_0#2")]
+ rows += [("Alias", "type_alias", "Alias")]
+ for line, (name, kind, tail) in enumerate(rows, start=1):
+ sid = f"{_FILE}::{tail}"
+ session.add(
+ WikiSymbol(
+ id=f"dense-{line}",
+ repository_id=rid,
+ file_path=_FILE,
+ symbol_id=sid,
+ name=name,
+ qualified_name=name,
+ kind=kind,
+ signature=name,
+ start_line=line,
+ end_line=line,
+ visibility="public",
+ is_async=False,
+ complexity_estimate=1,
+ )
+ )
+ # fn_3 is the most central function, so it leads the functions.
+ session.add(
+ GraphNode(
+ id="gn-fn3",
+ repository_id=rid,
+ node_id=f"{_FILE}::fn_3",
+ node_type="symbol",
+ file_path=_FILE,
+ pagerank=0.5,
+ )
+ )
+ await session.flush()
+
+
+async def _card(session, repository, target, include=_DEFAULT) -> dict:
+ return await _resolve_one_target(session, repository, target, include, True, exclude_spec=None)
+
+
+async def test_default_card_is_capped_and_ranked(session, repository, dense_file) -> None:
+ docs = (await _card(session, repository, _FILE))["docs"]
+ symbols = docs["symbols"]
+ assert len(symbols) == _SYMBOL_CAP == 15
+ assert docs["symbols_truncated"]["shown"] == 15
+ assert docs["symbols_truncated"]["total"] == 28
+ assert docs["symbols_total"] == 28
+ assert "include=['symbols']" in docs["symbols_truncated"]["hint"]
+ kinds = [s["kind"] for s in symbols]
+ # A type alias is a type, not a value, though the budgeter's table misses it.
+ assert kinds[:4] == ["class"] * 3 + ["type_alias"]
+ assert set(kinds[4:10]) == {"function", "method"}
+ assert kinds[10:] == ["variable"] * 5
+ # Centrality orders within a kind, start line breaks ties.
+ assert [s["name"] for s in symbols[4:6]] == ["fn_3", "fn_0"]
+ assert [s["name"] for s in symbols[10:12]] == ["VAR_0", "VAR_1"]
+
+
+async def test_budget_trim_of_a_capped_card_keeps_the_true_total(
+ session, repository, dense_file
+) -> None:
+ """The budgeter's ``symbols_total`` must count the file, not the 15-row cut."""
+ from repowise.server.mcp_server._budget.budgeter import truncate_to_budget
+
+ card = await _card(session, repository, _FILE)
+ result = truncate_to_budget({"targets": {_FILE: card}}, 1200, record_counts=True)
+ docs = result["targets"][_FILE]["docs"]
+ assert len(docs["symbols"]) < _SYMBOL_CAP
+ assert docs["symbols_emitted"] == len(docs["symbols"])
+ assert docs["symbols_total"] == 28
+
+
+async def test_include_symbols_returns_every_symbol(session, repository, dense_file) -> None:
+ docs = (await _card(session, repository, _FILE, _DEFAULT | {"symbols"}))["docs"]
+ assert len(docs["symbols"]) == 28
+ assert "symbols_truncated" not in docs
+
+
+async def test_symbol_id_dropped_only_when_derivable(session, repository, dense_file) -> None:
+ docs = (await _card(session, repository, _FILE, _DEFAULT | {"symbols"}))["docs"]
+ by_id = {s.get("symbol_id"): s for s in docs["symbols"] if "symbol_id" in s}
+ # A method and an overload variant cannot be rebuilt from path::name.
+ assert set(by_id) == {f"{_FILE}::Klass0::run", f"{_FILE}::fn_0#2"}
+ plain = [s for s in docs["symbols"] if "symbol_id" not in s]
+ assert len(plain) == 26
+
+
+async def test_unresolved_symbol_degrade_lists_every_symbol(
+ session, repository, dense_file
+) -> None:
+ """The caller is hunting for a name, so the fallback card is uncapped."""
+ card = await _card(session, repository, f"{_FILE}::Missing")
+ assert card["resolved_to"] == _FILE
+ assert len(card["docs"]["symbols"]) == 28