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(mcp): get_why on a directory reports its files' git history (#4356)

Raghav Chamadiya26dbb9c9d6f2
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index a532cdbd5..0b5dc31ea 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -284,6 +284,8 @@ Why code is shaped as it is: decision records, falling back to git archaeology a
Modes: a question searches decisions; a path (or `targets` alone) returns `decisions`, `candidates`, `history`, its origin story and `alignment`; `id` resolves one record; no arguments returns the dashboard (stale decisions, conflicts, ungoverned hotspots).
+A directory's origin story (`scope: "directory"`) is built from the files under it: how many have history, the first and last commit dates, and their stored key commits, each listed once. Git history is stored per file, so it carries no commit count or owner for the directory.
+
**Returns** `decisions` (binding), `candidates` (hints, not rules), `history`, `answer_basis` ([fields](../reference/MCP_RESPONSE_FIELDS.md#get_why)).
```
diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.py
index 6db248582..2442cdc34 100644
--- a/packages/server/src/repowise/server/mcp_server/_helpers.py
+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py
@@ -390,7 +390,7 @@ def _build_origin_story(
if git_meta is None:
return {
"available": False,
- "summary": f"No git history available for {file_path}.",
+ "summary": f"No git history is indexed for {file_path}.",
}
authors = json.loads(git_meta.top_authors_json) if git_meta.top_authors_json else []
@@ -442,6 +442,62 @@ 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_why/path_mode.py b/packages/server/src/repowise/server/mcp_server/tool_why/path_mode.py
index 58de627c6..67328d4d1 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,17 +13,20 @@ 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
+from repowise.core.persistence.models import DecisionRecord, GitMetadata
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._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
@@ -57,7 +60,8 @@ async def _why_path(query: str, repo: str | None) -> dict:
"""Mode 2: query is a path — governing decisions, origin story, alignment."""
ctx = await _resolve_repo_context(repo)
collector = OmissionCollector("get_why", repo_root=ctx.path)
- if is_excluded(query, _get_exclude_spec(ctx.path)):
+ exclude_spec = _get_exclude_spec(ctx.path)
+ if is_excluded(query, exclude_spec):
return {"query": query, "error": f"'{query}' is excluded by exclude_patterns."}
async with get_session(ctx.session_factory) as session:
repository = await _get_repo(session)
@@ -73,7 +77,10 @@ async def _why_path(query: str, repo: str | None) -> dict:
matched = _records_naming_path(all_decisions, query)
# A typo or a stale path: nothing to excavate, so say so before the
# archaeology fallback mines unrelated commits for it.
- if git_meta is None and not matched and not _maybe_on_disk(ctx.path, query):
+ known = git_meta is not None or bool(matched) or _maybe_on_disk(ctx.path, query)
+ if not known and not await _indexed_under(
+ session, repository.id, query, exclude_spec
+ ):
return {
"mode": "path",
"path": query,
@@ -81,7 +88,7 @@ async def _why_path(query: str, repo: str | None) -> dict:
"nor in the indexed git history.",
}
- # Pre-load all git metadata for cross-file search (used by fallback)
+ # Every file's rows: a directory's history, and the fallback's cross-file search.
all_git_meta = await _all_git_metadata(session, repository.id)
# A record with no acceptance row is a candidate whatever its status.
@@ -97,8 +104,11 @@ async def _why_path(query: str, repo: str | None) -> dict:
await _stamp_still_true(governing, matched, ctx.path)
# Every lane: the origin story is evidence, not instruction.
- origin_story = _build_origin_story(
- query, git_meta, governing + candidates + retired
+ origin_story = _origin_for(
+ query,
+ git_meta,
+ _rows_under(query, all_git_meta, exclude_spec),
+ governing + candidates + retired,
)
result_data: dict[str, Any] = {
@@ -162,6 +172,46 @@ def _maybe_on_disk(repo_path: str | Path | None, path: str) -> bool:
return candidate.exists()
+def _origin_for(
+ path: str, git_meta: Any | None, rows_under: list, governing: list[dict]
+) -> dict:
+ """A file's origin story, or a directory's from the files under it."""
+ if git_meta is not None:
+ return _build_origin_story(path, git_meta, governing)
+ 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
@@ -302,6 +352,7 @@ async def _build_target_context(
all_git_meta_list = await _all_git_metadata(session2, repository.id)
root = served_root(repository, ctx.path)
+ exclude_spec = _get_exclude_spec(ctx.path)
target_context: dict[str, Any] = {}
for t in targets:
target_context[t] = await _target_card(
@@ -311,6 +362,7 @@ async def _build_target_context(
all_git_meta_list,
root,
accepted or set(),
+ _rows_under(t, all_git_meta_list, exclude_spec),
)
return target_context
@@ -334,6 +386,7 @@ async def _target_card(
all_git_meta_list: list,
repo_root: str | None,
accepted_ids: set[str],
+ rows_under: list,
) -> dict[str, Any]:
"""One target's card: its rules, its candidates, its origin, and archaeology."""
rows = [
@@ -348,14 +401,7 @@ async def _target_card(
]
t_governing = [r for r in rows if r["authority"] == "accepted"]
t_candidates = [r for r in rows if r["authority"] != "accepted"]
- origin = (
- _build_origin_story(t, git_m, t_governing)
- if git_m
- else {
- "available": False,
- "summary": f"No git history for {t}.",
- }
- )
+ origin = _origin_for(t, git_m, rows_under, t_governing)
ctx_entry: dict[str, Any] = {
"governing_decisions": t_governing,
"origin": origin,
diff --git a/tests/unit/server/mcp/test_why.py b/tests/unit/server/mcp/test_why.py
index 4ea132614..23a0e070b 100644
--- a/tests/unit/server/mcp/test_why.py
+++ b/tests/unit/server/mcp/test_why.py
@@ -312,6 +312,66 @@ async def test_get_why_module_path(setup_mcp):
assert any(d["title"] == "SQLAlchemy as ORM" for d in result["candidates"])
+async def test_get_why_directory_origin_rolls_up_its_files(setup_mcp):
+ """A directory has no git row of its own; its files' rows are its history."""
+ from repowise.server.mcp_server import get_why
+
+ origin = (await get_why("src/"))["origin_story"]
+ assert origin["available"] is True
+ assert origin["scope"] == "directory"
+ assert origin["files_with_history"] == 2
+ assert (origin["first_commit"], origin["last_commit"]) == ("2025-01-01", "2026-03-15")
+ assert [c["sha"] for c in origin["key_commits"]] == ["abc1234", "def5678", "111aaa"]
+ # Per-file totals and owners do not add up to a directory's, so none is claimed.
+ assert "total_commits" not in origin and "primary_author" not in origin
+ assert "No git history" not in origin["summary"]
+
+
+async def test_get_why_target_cards_roll_up_a_directory(setup_mcp):
+ from repowise.server.mcp_server import get_why
+
+ result = await get_why(targets=["src/db", "src/auth/service.py"])
+ db = result["target_context"]["src/db"]["origin"]
+ assert db["scope"] == "directory"
+ assert db["files_with_history"] == 1
+ assert result["target_context"]["src/auth/service.py"]["origin"]["total_commits"] == 42
+
+
+def test_directory_origin_lists_a_shared_commit_once():
+ from types import SimpleNamespace
+
+ from repowise.server.mcp_server._helpers import _build_directory_origin
+
+ shared = '[{"sha": "s1", "date": "2026-01-02", "message": "m", "author": "a"}]'
+ metas = [
+ SimpleNamespace(first_commit_at=None, last_commit_at=None, significant_commits_json=shared)
+ for _ in range(2)
+ ]
+ origin = _build_directory_origin("pkg", metas, [])
+ assert len(origin["key_commits"]) == 1
+ assert origin["first_commit"] == "unknown"
+ assert _build_directory_origin("pkg", [], [])["available"] is False
+
+
+def test_directory_rows_skip_excluded_files_and_sibling_prefixes():
+ from types import SimpleNamespace
+
+ import pathspec
+
+ from repowise.server.mcp_server.tool_why.path_mode 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"):
+ assert [m.file_path for m in _rows_under(query, rows, spec)] == ["src/db/models.py"]
+ assert len(_rows_under(".", rows, None)) == 3
+
+
@pytest.mark.asyncio
async def test_get_why_path_surfaces_code_rationale(setup_mcp, tmp_path):
"""Ungoverned file whose 'why' lives in a code comment → code_rationale."""