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): get_context on a directory reads the files under it (#4372)

Raghav Chamadiyaa7b5186f77c4
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 0b5dc31ea..307647a0c 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -163,6 +163,7 @@ A triage card per file, module or symbol: summary, symbols with signatures, hots
Target kinds:
- `path::Symbol`: a miss falls back to the file's card.
+- A directory: a module card from the indexed files under it, with or without a module page (none is `index_status: "directory_without_module_page"`, with up to 15 `docs.files`). Git history is stored per file, so `ownership` counts the files each person is primary owner of (`owners_by_files`), `last_change` gives the newest commit's date and file (and its author when a stored author matches), and `hotspot_files` counts hotspot files; no commit share, contributor count or bus factor is claimed.
- `component:<name>`: declared context and rolled-up facts, from [`.repowise/components.yaml`](../reference/CONFIG.md#repowisecomponentsyaml) or derived.
- `change:<id>` (`change:pr-123` or a commit sha): one [Change Record](../reference/CLI_REFERENCE.md#repowise-changes).
- `package:<name>` (`package:requests`, `package:npm:lodash`): where a package is imported ([PACKAGE_USAGE.md](../reference/PACKAGE_USAGE.md)).
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index 4f3459d02..74d17920a 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -184,6 +184,7 @@ Per target, under `targets`:
| title, summary, symbols | Docs summary and symbols with signatures and lines |
| `symbols_truncated`, `symbols_total` | Compact card: `{shown, total, hint}` and the full count |
| `hotspot` | Churn flag |
+| `hotspot_files` | Directory card: hotspot files under it, absent at zero |
| `fix_history` | Files with counted bug fixes: `fix_count` over `window` (6 months), age, `bug_magnet`. A cue to call `get_risk` |
| `episodes` | Count of dated records; `get_why` serves them |
| decisions | Titles; with `include=["decisions"]` the lanes `decisions`, `candidates` (max 3), `history` (max 2) |
@@ -205,7 +206,7 @@ Top level: `targets`, `_meta`, `ignored_arguments`, `suspects` when asked, and `
| `include` | Adds |
|-----------|------|
| `full_doc` | `content_md`, plus `digest_md` (questions answered, concept index, public API, git signals); dropped first over budget |
-| `ownership` | Primary owner, bus factor, contributor count |
+| `ownership` | Primary owner, bus factor, contributor count; on a directory, `owners_by_files` (top 3, `owners_total` beyond) and `basis` |
| `last_change`, `community` | Newest change; community |
| `callers`, `callees` | Call-graph neighbours |
| `references` | Symbol edit set; see [references](#references) |
diff --git a/packages/server/src/repowise/server/mcp_server/_directory.py b/packages/server/src/repowise/server/mcp_server/_directory.py
new file mode 100644
index 000000000..90e3c1935
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/_directory.py
@@ -0,0 +1,118 @@
+"""A directory target read from the indexed files under it.
+
+Git metadata is stored per file, so a directory has no row of its own: every
+directory answer (get_why's origin, get_context's module card) is built from
+its files' rows. Per-file commit counts are never summed, since a commit that
+touches two files would count twice.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.persistence.models import GitMetadata
+from repowise.server.mcp_server._helpers import (
+ LIKE_ESCAPE,
+ _build_origin_story,
+ _link_decisions_to_commits,
+ escape_like,
+ is_excluded,
+)
+
+#: Newest stored commits a directory origin lists, across its files; the same
+#: five the origin cap in tool_why/caps.py serves, so none is built to be dropped.
+_DIRECTORY_KEY_COMMITS = 5
+
+
+def _dir_prefix(path: str) -> str:
+ """*path* as a directory prefix of indexed file paths; ``""`` for the root."""
+ clean = path.replace("\\", "/").removeprefix("./").strip("/")
+ return "" if clean in ("", ".") else clean + "/"
+
+
+def _rows_under(path: str, all_git_meta: list, exclude_spec: Any) -> list:
+ """The git rows of the non-excluded files under *path* as a directory."""
+ prefix = _dir_prefix(path)
+ return [
+ m
+ for m in all_git_meta
+ if m.file_path.startswith(prefix) and not is_excluded(m.file_path, exclude_spec)
+ ]
+
+
+async def _git_rows_under(
+ session: AsyncSession, repository_id: Any, path: str, exclude_spec: Any, *columns: Any
+) -> list:
+ """*columns* (``file_path`` first) of the non-excluded files under *path*."""
+ res = await session.execute(
+ select(*columns).where(
+ GitMetadata.repository_id == repository_id,
+ GitMetadata.file_path.like(f"{escape_like(_dir_prefix(path))}%", escape=LIKE_ESCAPE),
+ )
+ )
+ # SQLite's LIKE ignores case; _rows_under's exact prefix decides.
+ return _rows_under(path, list(res.all()), exclude_spec)
+
+
+async def _indexed_under(
+ session: AsyncSession, repository_id: Any, path: str, exclude_spec: Any
+) -> bool:
+ """Whether a non-excluded indexed file lives under *path*, reading paths only."""
+ return bool(
+ await _git_rows_under(session, repository_id, path, exclude_spec, GitMetadata.file_path)
+ )
+
+
+def _date_or_unknown(pick: Any, stamps: list) -> str:
+ """``pick`` (min or max) of the known *stamps* as a date, else ``"unknown"``."""
+ known = [t for t in stamps if t]
+ return pick(known).strftime("%Y-%m-%d") if known else "unknown"
+
+
+def _newest_distinct_commits(file_metas: list) -> list[dict]:
+ """Every file's stored significant commits, one row per SHA, newest first."""
+ by_sha: dict[str, dict] = {}
+ for m in file_metas:
+ for c in json.loads(m.significant_commits_json or "[]"):
+ if c.get("sha"):
+ by_sha.setdefault(c["sha"], c)
+ return sorted(by_sha.values(), key=lambda c: c.get("date", ""), reverse=True)
+
+
+def _build_directory_origin(
+ dir_path: str,
+ file_metas: list,
+ governing_decisions: list[dict],
+) -> dict:
+ """The origin of a directory from its files' stored git metadata.
+
+ Git metadata is stored per file, so a directory has no commit total, owner
+ or age of its own: summing per-file counts would count a shared commit once
+ per file. Only what holds across files is served: the date span and the
+ stored significant commits, one row per SHA.
+ """
+ if not file_metas:
+ return _build_origin_story(dir_path, None, governing_decisions)
+ first_date = _date_or_unknown(min, [m.first_commit_at for m in file_metas])
+ last_date = _date_or_unknown(max, [m.last_commit_at for m in file_metas])
+ key_commits = _newest_distinct_commits(file_metas)[:_DIRECTORY_KEY_COMMITS]
+ return {
+ "available": True,
+ "scope": "directory",
+ "files_with_history": len(file_metas),
+ "first_commit": first_date,
+ "last_commit": last_date,
+ "key_commits": key_commits,
+ # Over the served commits only, so a large directory stays bounded.
+ "linked_decisions": _link_decisions_to_commits(governing_decisions, key_commits),
+ "summary": (
+ f"{dir_path} is a directory: {len(file_metas)} file(s) under it have "
+ f"git history, first commit {first_date}, last commit {last_date}. "
+ "History is stored per file, so there is no commit count or owner for "
+ "the directory itself; pass a file under it for that file's origin."
+ ),
+ }
diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.py
index 2442cdc34..f49c215f1 100644
--- a/packages/server/src/repowise/server/mcp_server/_helpers.py
+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py
@@ -442,62 +442,6 @@ def _build_origin_story(
}
-#: Newest stored commits a directory origin lists, across its files; the same
-#: five the origin cap in tool_why/caps.py serves, so none is built to be dropped.
-_DIRECTORY_KEY_COMMITS = 5
-
-
-def _date_or_unknown(pick: Any, stamps: list) -> str:
- """``pick`` (min or max) of the known *stamps* as a date, else ``"unknown"``."""
- known = [t for t in stamps if t]
- return pick(known).strftime("%Y-%m-%d") if known else "unknown"
-
-
-def _newest_distinct_commits(file_metas: list) -> list[dict]:
- """Every file's stored significant commits, one row per SHA, newest first."""
- by_sha: dict[str, dict] = {}
- for m in file_metas:
- for c in json.loads(m.significant_commits_json or "[]"):
- if c.get("sha"):
- by_sha.setdefault(c["sha"], c)
- return sorted(by_sha.values(), key=lambda c: c.get("date", ""), reverse=True)
-
-
-def _build_directory_origin(
- dir_path: str,
- file_metas: list,
- governing_decisions: list[dict],
-) -> dict:
- """The origin of a directory from its files' stored git metadata.
-
- Git metadata is stored per file, so a directory has no commit total, owner
- or age of its own: summing per-file counts would count a shared commit once
- per file. Only what holds across files is served: the date span and the
- stored significant commits, one row per SHA.
- """
- if not file_metas:
- return _build_origin_story(dir_path, None, governing_decisions)
- first_date = _date_or_unknown(min, [m.first_commit_at for m in file_metas])
- last_date = _date_or_unknown(max, [m.last_commit_at for m in file_metas])
- key_commits = _newest_distinct_commits(file_metas)[:_DIRECTORY_KEY_COMMITS]
- return {
- "available": True,
- "scope": "directory",
- "files_with_history": len(file_metas),
- "first_commit": first_date,
- "last_commit": last_date,
- "key_commits": key_commits,
- # Over the served commits only, so a large directory stays bounded.
- "linked_decisions": _link_decisions_to_commits(governing_decisions, key_commits),
- "summary": (
- f"{dir_path} is a directory: {len(file_metas)} file(s) under it have "
- f"git history, first commit {first_date}, last commit {last_date}. "
- "History is stored per file, so there is no commit count or owner for "
- "the directory itself; pass a file under it for that file's origin."
- ),
- }
-
-
def _sibling_coverage(
file_path: str,
governing: list[dict],
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/resolution.py b/packages/server/src/repowise/server/mcp_server/tool_context/resolution.py
index 353ff4f2c..d9343ab13 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/resolution.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/resolution.py
@@ -25,6 +25,7 @@ from repowise.core.persistence.models import (
WikiSymbol,
)
from repowise.server.mcp_server._budget import OmissionCollector
+from repowise.server.mcp_server._directory import _dir_prefix, _indexed_under
from repowise.server.mcp_server._helpers import (
LIKE_ESCAPE,
escape_like,
@@ -82,6 +83,8 @@ class ResolvedTarget:
graph_symbol: GraphNode | None = None
live_file_meta: GitMetadata | None = None
live_unindexed_file: bool = False
+ # A module's directory: its page's path, or the directory itself with no page.
+ dir_path: str | None = None
Resolution = ResolvedTarget | dict[str, Any]
@@ -215,14 +218,29 @@ async def _module_page_partial(q: TargetQuery) -> Page | None:
return candidates[0] if candidates else None
+async def _directory(q: TargetQuery) -> Resolution | None:
+ """A directory with no module page, known from the indexed files under it."""
+ prefix = _dir_prefix(q.target)
+ if "::" in q.target or not prefix:
+ return None
+ if await _indexed_under(q.session, q.repo_id, q.target, q.exclude_spec):
+ return ResolvedTarget("module", dir_path=prefix.rstrip("/"))
+ return None
+
+
async def _module_page(q: TargetQuery) -> Resolution | None:
- """A module page: exact, then without a trailing slash, then partial."""
+ """A module page: exact, then without a trailing slash; then the directory
+ itself when files are indexed under it, so a partial match cannot hand a
+ parent directory its child's card; then partial."""
page = await _module_page_at(q, q.target)
if page is None and q.clean_target != q.target:
page = await _module_page_at(q, q.clean_target)
if page is None:
+ directory = await _directory(q)
+ if directory is not None:
+ return directory
page = await _module_page_partial(q)
- return ResolvedTarget("module", page=page) if page else None
+ return ResolvedTarget("module", page=page, dir_path=page.target_path) if page else None
async def _symbol_rows(q: TargetQuery) -> Any:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/sections.py b/packages/server/src/repowise/server/mcp_server/tool_context/sections.py
index b5243aaff..6f0380e7d 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/sections.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/sections.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import contextlib
import json
+from collections import Counter
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from datetime import UTC, datetime
@@ -37,6 +38,7 @@ from repowise.core.persistence.models import (
)
from repowise.server.mcp_server._budget import cap_collection
from repowise.server.mcp_server._changes import file_changes, file_provenance, load_file_meta
+from repowise.server.mcp_server._directory import _git_rows_under
from repowise.server.mcp_server._edit_sites import reference_edit_set
from repowise.server.mcp_server._helpers import _decision_body
from repowise.server.mcp_server._meta import served_root, uncommitted_targets
@@ -63,6 +65,18 @@ from repowise.server.mcp_server.tool_risk.assessment import fix_annotation
_MAX_CANDIDATES = 3
_MAX_DECISION_HISTORY = 2
+#: Owners a directory card names, by how many of its files each owns.
+_MAX_DIRECTORY_OWNERS = 3
+
+#: The per-file git columns a directory card reads.
+_DIRECTORY_COLUMNS = (
+ GitMetadata.file_path,
+ GitMetadata.primary_owner_name,
+ GitMetadata.last_commit_at,
+ GitMetadata.is_hotspot,
+ GitMetadata.top_authors_json,
+)
+
@dataclass
class CardState:
@@ -71,6 +85,7 @@ class CardState:
query: TargetQuery
resolved: ResolvedTarget
data: dict[str, Any] = field(default_factory=dict)
+ _dir_rows: list[Any] | None = field(default=None, init=False, repr=False)
@property
def session(self) -> AsyncSession:
@@ -102,11 +117,26 @@ class CardState:
@property
def git_path(self) -> str | None:
- """The path git rows are keyed on: the module's directory for a module."""
- if self.resolved.target_type == "module" and self.page:
- return self.page.target_path
+ """The file git rows are keyed on; None for a module."""
return self.resolved.file_path
+ @property
+ def dir_path(self) -> str | None:
+ """A module's directory, whose git facts come from the files under it."""
+ return self.resolved.dir_path if self.resolved.target_type == "module" else None
+
+ async def dir_rows(self) -> list[Any]:
+ """The git rows of the files under ``dir_path``, read once per card."""
+ if self._dir_rows is None:
+ self._dir_rows = await _git_rows_under(
+ self.session,
+ self.repo_id,
+ self.dir_path or "",
+ self.query.exclude_spec,
+ *_DIRECTORY_COLUMNS,
+ )
+ return self._dir_rows
+
@property
def skeleton_plus(self) -> bool:
return self.wants("skeleton+")
@@ -126,6 +156,8 @@ def _identity_section(card: CardState) -> None:
data["type"] = resolved.target_type
if resolved.target_type == "file" and resolved.file_path:
data["path"] = path_identity(resolved.file_path)
+ if resolved.target_type == "module" and card.page is None:
+ data["index_status"] = "directory_without_module_page"
meta = resolved.live_file_meta
if meta is not None:
data["index_status"] = "live_file_without_wiki_page"
@@ -188,6 +220,9 @@ async def _triage_section(card: CardState) -> None:
* ``decision_records``: titles only, pointing to ``get_why``; inlining
rationale would bloat every cached response.
"""
+ if card.dir_path is not None:
+ await _directory_triage(card)
+ return
triage_path = card.git_path
if not triage_path:
return
@@ -217,6 +252,16 @@ async def _triage_section(card: CardState) -> None:
await _governing_decision_titles(card, triage_path)
+async def _directory_triage(card: CardState) -> None:
+ """A directory has no hotspot bit or fix history of its own; it names how
+ many files under it are hotspots, the cue to call get_risk on them."""
+ hotspots = sum(1 for r in await card.dir_rows() if r.is_hotspot)
+ if hotspots:
+ card.data["hotspot_files"] = hotspots
+ if card.wants("decisions"):
+ await _governing_decision_titles(card, card.dir_path or card.target)
+
+
async def _governing_decision_titles(card: CardState, triage_path: str) -> None:
target = card.target
governing: list[DecisionRecord] = []
@@ -253,6 +298,9 @@ async def _git_meta_row(card: CardState, git_path: str | None) -> GitMetadata |
async def _ownership_section(card: CardState) -> None:
if not card.default_on("ownership"):
return
+ if card.dir_path is not None:
+ card.data["ownership"] = _directory_ownership(await card.dir_rows())
+ return
ownership: dict[str, Any] = {}
meta = await _git_meta_row(card, card.git_path)
if meta:
@@ -279,6 +327,28 @@ async def _ownership_section(card: CardState) -> None:
card.data["ownership"] = ownership
+def _directory_ownership(rows: list[Any]) -> dict[str, Any]:
+ """Who owns the files under a directory, counted in files.
+
+ Each file stores only its own primary owner and shares, so a commit share,
+ contributor count or bus factor for the directory cannot be derived: an
+ author's commits on two files may be one commit.
+ """
+ counts = Counter(r.primary_owner_name for r in rows if r.primary_owner_name)
+ ranked = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
+ ownership: dict[str, Any] = {
+ "files_with_history": len(rows),
+ "owners_by_files": [
+ {"name": name, "files": n} for name, n in ranked[:_MAX_DIRECTORY_OWNERS]
+ ],
+ "basis": "files each person is primary owner of; history is per file, so no "
+ "directory commit share, contributor count or bus factor",
+ }
+ if len(ranked) > _MAX_DIRECTORY_OWNERS:
+ ownership["owners_total"] = len(ranked)
+ return ownership
+
+
def _agent_provenance(card: CardState, meta: GitMetadata, ownership: dict[str, Any]) -> None:
"""Agent provenance, only when agent-attributed commits exist and
attribution is on. The share is of commits with a known source, with its
@@ -303,6 +373,9 @@ def _agent_provenance(card: CardState, meta: GitMetadata, ownership: dict[str, A
async def _last_change_section(card: CardState) -> None:
if not card.default_on("last_change"):
return
+ if card.dir_path is not None:
+ card.data["last_change"] = await _directory_last_change(card)
+ return
last_change: dict[str, Any] = {}
meta = await _git_meta_row(card, card.git_path)
if meta:
@@ -318,6 +391,38 @@ async def _last_change_section(card: CardState) -> None:
card.data["last_change"] = last_change
+async def _directory_last_change(card: CardState) -> dict[str, Any]:
+ """The newest commit under a directory: its date and the file it touched.
+
+ ``author`` is the author whose own newest commit on that file is at that
+ moment, and is absent when no stored author matches.
+ """
+ dated = [r for r in await card.dir_rows() if r.last_commit_at]
+ if not dated:
+ return {"date": None, "days_ago": None}
+ newest = max(dated, key=lambda r: (_as_utc(r.last_commit_at), r.file_path))
+ last_change: dict[str, Any] = {
+ "date": newest.last_commit_at.isoformat(),
+ "path": newest.file_path,
+ "days_ago": await _days_since_last_change(
+ card.session, card.repo_id, newest.last_commit_at, card.query.as_of_ts
+ ),
+ }
+ author = _author_at(newest.top_authors_json, _as_utc(newest.last_commit_at))
+ if author:
+ last_change["author"] = author
+ return last_change
+
+
+def _author_at(top_authors_json: str | None, moment: datetime) -> str | None:
+ """The stored author whose newest commit on the file is at *moment*."""
+ with contextlib.suppress(TypeError, ValueError):
+ for a in json.loads(top_authors_json or "[]"):
+ if int(a.get("last_commit_ts") or -1) == int(moment.timestamp()):
+ return a.get("name")
+ return None
+
+
async def _changes_section(card: CardState) -> None:
"""Change Records and provenance (file targets, opt-in)."""
include = card.include
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 97742ed79..9c073ddd3 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
@@ -349,8 +349,28 @@ def _attach_file_preview(card: CardState, docs: dict[str, Any]) -> None:
docs["summary"] = _preview_summary(card.target, preview)
+async def _directory_docs(card: CardState, docs: dict[str, Any]) -> None:
+ """A directory with no module page: its files with git history, capped as symbols are."""
+ paths = sorted(r.file_path for r in await card.dir_rows())
+ docs["summary"] = (
+ f"{card.dir_path}: a directory with no module page; {len(paths)} file(s) "
+ "under it have git history."
+ )
+ cap_collection(
+ docs,
+ "files",
+ [{"path": p} for p in paths],
+ _SYMBOL_CAP,
+ card.query.collector,
+ label=f"{card.target} :: docs.files beyond cap={_SYMBOL_CAP}",
+ )
+
+
async def _module_docs(card: CardState, docs: dict[str, Any]) -> None:
page = card.page
+ if page is None:
+ await _directory_docs(card, docs)
+ return
exclude_spec = card.query.exclude_spec
docs["title"] = page.title
docs["summary"] = page.summary or ""
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.py b/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.py
index 67328d4d1..0deda6978 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.py
@@ -13,20 +13,22 @@ from repowise.core.analysis.decisions.lifecycle import is_governing
from repowise.core.analysis.decisions.scope import binds_to_paths
from repowise.core.persistence.crud.authority import decision_currencies
from repowise.core.persistence.database import get_session
-from repowise.core.persistence.models import DecisionRecord, GitMetadata
+from repowise.core.persistence.models import DecisionRecord
from repowise.core.precedent.currency import describe_decision_currency
from repowise.server.mcp_server._budget import OmissionCollector
from repowise.server.mcp_server._code_rationale import mine_rationale as _mine_rationale
+from repowise.server.mcp_server._directory import (
+ _build_directory_origin,
+ _indexed_under,
+ _rows_under,
+)
from repowise.server.mcp_server._episodes import episode_evidence
from repowise.server.mcp_server._helpers import (
- LIKE_ESCAPE,
- _build_directory_origin,
_build_origin_story,
_compute_alignment,
_get_exclude_spec,
_get_repo,
_resolve_repo_context,
- escape_like,
is_excluded,
)
from repowise.server.mcp_server._meta import build_meta as _build_meta
@@ -181,37 +183,6 @@ def _origin_for(
return _build_directory_origin(path.rstrip("/"), rows_under, governing)
-def _dir_prefix(path: str) -> str:
- """*path* as a directory prefix of indexed file paths; ``""`` for the root."""
- clean = path.replace("\\", "/").removeprefix("./").strip("/")
- return "" if clean in ("", ".") else clean + "/"
-
-
-def _rows_under(path: str, all_git_meta: list, exclude_spec: Any) -> list:
- """The git rows of the non-excluded files under *path* as a directory."""
- prefix = _dir_prefix(path)
- return [
- m
- for m in all_git_meta
- if m.file_path.startswith(prefix) and not is_excluded(m.file_path, exclude_spec)
- ]
-
-
-async def _indexed_under(
- session: Any, repository_id: Any, path: str, exclude_spec: Any
-) -> bool:
- """Whether a non-excluded indexed file lives under *path*, without loading rows."""
- res = await session.execute(
- select(GitMetadata.file_path).where(
- GitMetadata.repository_id == repository_id,
- GitMetadata.file_path.like(
- f"{escape_like(_dir_prefix(path))}%", escape=LIKE_ESCAPE
- ),
- )
- )
- return any(not is_excluded(fp, exclude_spec) for fp in res.scalars())
-
-
def _records_naming_path(all_decisions: list, path: str) -> list:
"""Records whose own scope names *path* as a file or a module."""
# A record whose file list is just its source commit's footprint does not
diff --git a/tests/unit/server/golden/mcp/get_context_module.json b/tests/unit/server/golden/mcp/get_context_module.json
index b07221169..bfe0cf1f0 100644
--- a/tests/unit/server/golden/mcp/get_context_module.json
+++ b/tests/unit/server/golden/mcp/get_context_module.json
@@ -18,7 +18,7 @@
}
]
},
- "hotspot": false,
+ "hotspot_files": 1,
"freshness": {
"confidence_score": 0.95,
"freshness_status": "fresh",
diff --git a/tests/unit/server/mcp/test_context_directory.py b/tests/unit/server/mcp/test_context_directory.py
new file mode 100644
index 000000000..ed737245f
--- /dev/null
+++ b/tests/unit/server/mcp/test_context_directory.py
@@ -0,0 +1,86 @@
+"""get_context on a directory: its git facts come from the files under it."""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime
+
+import pytest
+
+
+async def test_directory_without_a_module_page_resolves_from_its_files(setup_mcp):
+ from repowise.server.mcp_server import get_context
+
+ result = await get_context(["src/"], include=["ownership", "last_change"])
+ card = result["targets"]["src/"]
+ assert card["type"] == "module"
+ # src/auth and src/db have module pages; src itself does not, and gets its own card.
+ assert card["index_status"] == "directory_without_module_page"
+ assert [f["path"] for f in card["docs"]["files"]] == [
+ "src/auth/service.py",
+ "src/db/models.py",
+ ]
+ # One hotspot file under it; a directory has no hotspot bit of its own.
+ assert card["hotspot_files"] == 1
+ assert "hotspot" not in card
+ ownership = card["ownership"]
+ assert ownership["files_with_history"] == 2
+ assert ownership["owners_by_files"] == [
+ {"name": "Alice", "files": 1},
+ {"name": "Bob", "files": 1},
+ ]
+ # Per-file shares do not add up to a directory's, so none is claimed.
+ assert not {"primary_owner", "owner_pct", "contributor_count", "bus_factor"} & set(ownership)
+ last = card["last_change"]
+ assert last["date"].startswith("2026-03-15")
+ assert last["path"] == "src/auth/service.py"
+ assert last["days_ago"] == 0
+ # The fixture's authors carry no commit time, so no author is claimed.
+ assert "author" not in last
+
+
+async def test_module_page_ownership_comes_from_its_files(setup_mcp):
+ from repowise.server.mcp_server import get_context
+
+ card = (await get_context(["src/db"], include=["ownership", "last_change"]))["targets"][
+ "src/db"
+ ]
+ assert "index_status" not in card
+ assert "hotspot_files" not in card and "hotspot" not in card
+ assert card["ownership"]["owners_by_files"] == [{"name": "Bob", "files": 1}]
+ assert card["last_change"]["date"].startswith("2025-09-01")
+ assert card["last_change"]["path"] == "src/db/models.py"
+
+
+async def test_unknown_and_sibling_prefix_directories_stay_not_found(setup_mcp):
+ from repowise.server.mcp_server import get_context
+
+ targets = (await get_context(["src/nope", "src/au"]))["targets"]
+ for t in ("src/nope", "src/au"):
+ assert targets[t].get("type") != "module", (t, targets[t])
+
+
+async def test_directory_card_is_no_larger_than_a_file_card(setup_mcp):
+ from repowise.server.mcp_server import get_context
+
+ targets = (await get_context(["src/", "src/auth/service.py"]))["targets"]
+ assert len(json.dumps(targets["src/"])) <= len(json.dumps(targets["src/auth/service.py"]))
+
+
+def test_last_change_author_is_the_one_committing_at_that_moment():
+ from repowise.server.mcp_server.tool_context.sections import _author_at
+
+ moment = datetime(2026, 3, 15, tzinfo=UTC)
+ authors = json.dumps(
+ [
+ {"name": "Alice", "commit_count": 9, "last_commit_ts": int(moment.timestamp()) - 60},
+ {"name": "Bob", "commit_count": 1, "last_commit_ts": int(moment.timestamp())},
+ ]
+ )
+ assert _author_at(authors, moment) == "Bob"
+ assert _author_at("[]", moment) is None
+ assert _author_at("not json", moment) is None
diff --git a/tests/unit/server/mcp/test_why.py b/tests/unit/server/mcp/test_why.py
index 23a0e070b..9f238c91b 100644
--- a/tests/unit/server/mcp/test_why.py
+++ b/tests/unit/server/mcp/test_why.py
@@ -342,7 +342,7 @@ async def test_get_why_target_cards_roll_up_a_directory(setup_mcp):
def test_directory_origin_lists_a_shared_commit_once():
from types import SimpleNamespace
- from repowise.server.mcp_server._helpers import _build_directory_origin
+ from repowise.server.mcp_server._directory import _build_directory_origin
shared = '[{"sha": "s1", "date": "2026-01-02", "message": "m", "author": "a"}]'
metas = [
@@ -360,14 +360,14 @@ def test_directory_rows_skip_excluded_files_and_sibling_prefixes():
import pathspec
- from repowise.server.mcp_server.tool_why.path_mode import _rows_under
+ from repowise.server.mcp_server._directory import _rows_under
rows = [
SimpleNamespace(file_path=p)
for p in ("src/db/models.py", "src/dbx/other.py", "src/db/vendor/lib.py")
]
spec = pathspec.PathSpec.from_lines("gitwildmatch", ["vendor/"])
- for query in ("src/db", "src/db/", "./src/db", "src\db"):
+ for query in ("src/db", "src/db/", "./src/db", r"src\db"):
assert [m.file_path for m in _rows_under(query, rows, spec)] == ["src/db/models.py"]
assert len(_rows_under(".", rows, None)) == 3