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.

refactor(mcp): decompose high-complexity MCP tool handlers (#527)

Raghav Chamadiyab46988a352b6
diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.py
index 282baa992..d21586740 100644
--- a/packages/server/src/repowise/server/mcp_server/_helpers.py
+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py
@@ -108,9 +108,7 @@ def _is_path(query: str) -> bool:
return False
# Sentence-shaped input (multiple words including a question word) → NL.
- if len(tokens) >= 4 and any(
- t.lower().rstrip(",.;:") in _NL_QUESTION_TOKENS for t in tokens
- ):
+ if len(tokens) >= 4 and any(t.lower().rstrip(",.;:") in _NL_QUESTION_TOKENS for t in tokens):
return False
# A path can't contain whitespace.
@@ -212,82 +210,73 @@ def _unsupported_repo_all(tool_name: str) -> dict:
# Origin story & alignment (used by get_context, get_why)
# ---------------------------------------------------------------------------
+# Common stop-words stripped before commit/decision keyword overlap.
+_ORIGIN_STOP_WORDS = frozenset(
+ {"the", "a", "an", "is", "for", "to", "of", "in", "and", "or", "with"}
+)
-def _build_origin_story(
- file_path: str,
- git_meta: Any | None,
- governing_decisions: list[dict],
-) -> dict:
- """Build the human context / origin story for a file from stored metadata."""
- if git_meta is None:
- return {
- "available": False,
- "summary": f"No git history available for {file_path}.",
- }
- authors = json.loads(git_meta.top_authors_json) if git_meta.top_authors_json else []
- commits = (
- json.loads(git_meta.significant_commits_json) if git_meta.significant_commits_json else []
+def _meaningful_words(text: str) -> set[str]:
+ """Lowercase keyword set with common stop-words removed."""
+ return set(text.lower().split()) - _ORIGIN_STOP_WORDS
+
+
+def _commits_matching_decision(decision: dict, commits: list[dict]) -> list[dict]:
+ """Return commits whose messages share at least one keyword with *decision*."""
+ decision_text = (
+ f"{decision.get('title', '')} {decision.get('decision', '')} "
+ f"{decision.get('rationale', '')}"
)
+ decision_words = _meaningful_words(decision_text)
- # Find the earliest significant commit as the "creation" context
- earliest_commit = None
- if commits:
- sorted_commits = sorted(commits, key=lambda c: c.get("date", ""))
- earliest_commit = sorted_commits[0]
+ related_commits = []
+ for c in commits:
+ overlap = decision_words & _meaningful_words(c.get("message", ""))
+ if not overlap:
+ continue
+ related_commits.append(
+ {
+ "sha": c.get("sha", ""),
+ "message": c.get("message", ""),
+ "author": c.get("author", ""),
+ "date": c.get("date", ""),
+ "matching_keywords": sorted(overlap)[:5],
+ }
+ )
+ return related_commits
- # Link commits to decisions via keyword overlap
+
+def _link_decisions_to_commits(governing_decisions: list[dict], commits: list[dict]) -> list[dict]:
+ """Attach commit evidence to each governing decision via keyword overlap."""
linked_decisions = []
for d in governing_decisions:
- # Build a keyword set from the decision
- decision_text = (
- f"{d.get('title', '')} {d.get('decision', '')} {d.get('rationale', '')}".lower()
- )
- decision_words = set(decision_text.split())
- decision_words -= {"the", "a", "an", "is", "for", "to", "of", "in", "and", "or", "with"}
-
- # Find commits whose messages overlap with this decision
- related_commits = []
- for c in commits:
- msg = c.get("message", "").lower()
- msg_words = set(msg.split())
- msg_words -= {"the", "a", "an", "is", "for", "to", "of", "in", "and", "or", "with"}
- overlap = decision_words & msg_words
- # Require at least 1 meaningful word match
- if len(overlap) >= 1:
- related_commits.append(
- {
- "sha": c.get("sha", ""),
- "message": c.get("message", ""),
- "author": c.get("author", ""),
- "date": c.get("date", ""),
- "matching_keywords": sorted(overlap)[:5],
- }
- )
-
linked_decisions.append(
{
"title": d.get("title", ""),
"status": d.get("status", ""),
"source": d.get("source", ""),
"rationale": d.get("rationale", ""),
- "evidence_commits": related_commits,
+ "evidence_commits": _commits_matching_decision(d, commits),
}
)
-
- # Build narrative summary
- primary = git_meta.primary_owner_name or "unknown"
- total = git_meta.commit_count_total or 0
- first_date = (
- git_meta.first_commit_at.strftime("%Y-%m-%d") if git_meta.first_commit_at else "unknown"
- )
- last_date = (
- git_meta.last_commit_at.strftime("%Y-%m-%d") if git_meta.last_commit_at else "unknown"
- )
- age = git_meta.age_days or 0
-
- parts = [f"Created ~{first_date}, last modified {last_date} ({age} days old)."]
- parts.append(f"Primary author: {primary} ({total} total commits).")
+ return linked_decisions
+
+
+def _origin_summary_parts(
+ authors: list,
+ earliest_commit: dict | None,
+ linked_decisions: list[dict],
+ primary: str,
+ total: int,
+ first_date: str,
+ last_date: str,
+ age: int,
+) -> list[str]:
+ """Assemble the narrative sentences for an origin story."""
+ parts = [
+ f"Created ~{first_date}, last modified {last_date} ({age} days old).",
+ f"Primary author: {primary} ({total} total commits).",
+ ]
if earliest_commit:
parts.append(
@@ -298,7 +287,6 @@ def _build_origin_story(
if linked_decisions:
decision_titles = [d["title"] for d in linked_decisions[:3]]
parts.append(f"Governed by: {', '.join(decision_titles)}.")
- # Highlight any commit-decision links
for ld in linked_decisions:
if ld["evidence_commits"]:
ec = ld["evidence_commits"][0]
@@ -306,11 +294,58 @@ def _build_origin_story(
f'Commit "{ec["message"]}" by {ec["author"]} is evidence for "{ld["title"]}".'
)
- contributor_count = len(authors)
- if contributor_count > 1:
+ if len(authors) > 1:
names = [a.get("name", "") for a in authors[:3]]
parts.append(f"Contributors: {', '.join(names)}.")
+ return parts
+
+
+def _build_origin_story(
+ file_path: str,
+ git_meta: Any | None,
+ governing_decisions: list[dict],
+) -> dict:
+ """Build the human context / origin story for a file from stored metadata."""
+ if git_meta is None:
+ return {
+ "available": False,
+ "summary": f"No git history available for {file_path}.",
+ }
+
+ authors = json.loads(git_meta.top_authors_json) if git_meta.top_authors_json else []
+ commits = (
+ json.loads(git_meta.significant_commits_json) if git_meta.significant_commits_json else []
+ )
+
+ # Find the earliest significant commit as the "creation" context
+ earliest_commit = None
+ if commits:
+ earliest_commit = sorted(commits, key=lambda c: c.get("date", ""))[0]
+
+ linked_decisions = _link_decisions_to_commits(governing_decisions, commits)
+
+ primary = git_meta.primary_owner_name or "unknown"
+ total = git_meta.commit_count_total or 0
+ first_date = (
+ git_meta.first_commit_at.strftime("%Y-%m-%d") if git_meta.first_commit_at else "unknown"
+ )
+ last_date = (
+ git_meta.last_commit_at.strftime("%Y-%m-%d") if git_meta.last_commit_at else "unknown"
+ )
+ age = git_meta.age_days or 0
+
+ parts = _origin_summary_parts(
+ authors,
+ earliest_commit,
+ linked_decisions,
+ primary,
+ total,
+ first_date,
+ last_date,
+ age,
+ )
+
return {
"available": True,
"primary_author": primary,
@@ -326,6 +361,71 @@ def _build_origin_story(
}
+def _sibling_coverage(file_path: str, governing: list[dict], all_decisions: list) -> float | None:
+ """Fraction of sibling-file decisions that also cover *file_path* (None if no siblings)."""
+ dir_path = "/".join(file_path.split("/")[:-1])
+ sibling_decision_ids = set()
+ file_decision_titles = {d["title"] for d in governing}
+
+ for d in all_decisions:
+ affected = json.loads(d.affected_files_json)
+ json.loads(d.affected_modules_json)
+ for af in affected:
+ af_dir = "/".join(af.split("/")[:-1])
+ if af_dir == dir_path and af != file_path:
+ sibling_decision_ids.add(d.title)
+
+ if not sibling_decision_ids:
+ return None # No siblings to compare
+ shared = file_decision_titles & sibling_decision_ids
+ return len(shared) / len(sibling_decision_ids)
+
+
+def _active_alignment(active: list, dir_path: str, sibling_coverage: float | None) -> tuple:
+ """Score/explanation when active decisions govern the file."""
+ if sibling_coverage is not None and sibling_coverage >= 0.5:
+ return "high", (
+ f"Follows {len(active)} active decision(s) shared with sibling files. "
+ f"This file aligns with established patterns in {dir_path}/."
+ )
+ if sibling_coverage is not None and sibling_coverage < 0.5:
+ return "medium", (
+ f"Has {len(active)} active decision(s) but limited overlap with "
+ f"sibling files in {dir_path}/. May use a different pattern than neighbors."
+ )
+ return "high", f"Governed by {len(active)} active decision(s)."
+
+
+def _alignment_score(
+ governing: list[dict],
+ active: list,
+ deprecated: list,
+ stale: list,
+ proposed: list,
+ dir_path: str,
+ sibling_coverage: float | None,
+) -> tuple:
+ """Derive the (score, explanation) tuple from decision status counts."""
+ if deprecated and not active and not proposed:
+ return "low", (
+ "All governing decisions are deprecated/superseded. "
+ "This file likely contains technical debt that should be migrated."
+ )
+ if stale and len(stale) >= len(governing) / 2:
+ return "low", (
+ f"{len(stale)} of {len(governing)} governing decision(s) are stale. "
+ f"The architectural rationale may no longer apply."
+ )
+ if active:
+ return _active_alignment(active, dir_path, sibling_coverage)
+ if proposed:
+ return "medium", (
+ f"Governed by {len(proposed)} proposed (unreviewed) decision(s). "
+ f"Patterns are established but not yet formally approved."
+ )
+ return "medium", f"Governed by {len(governing)} decision(s) with mixed status."
+
+
def _compute_alignment(
file_path: str,
governing: list[dict],
@@ -352,64 +452,12 @@ def _compute_alignment(
stale = [d for d in governing if d.get("staleness_score", 0) > 0.5]
proposed = [d for d in governing if d["status"] == "proposed"]
- # Check sibling files — do neighbors share the same decisions?
dir_path = "/".join(file_path.split("/")[:-1])
- sibling_decision_ids = set()
- file_decision_titles = {d["title"] for d in governing}
-
- for d in all_decisions:
- affected = json.loads(d.affected_files_json)
- _affected_modules = json.loads(d.affected_modules_json)
- for af in affected:
- af_dir = "/".join(af.split("/")[:-1])
- if af_dir == dir_path and af != file_path:
- sibling_decision_ids.add(d.title)
-
- # Overlap: how many of sibling decisions also cover this file
- if sibling_decision_ids:
- shared = file_decision_titles & sibling_decision_ids
- sibling_coverage = len(shared) / len(sibling_decision_ids)
- else:
- sibling_coverage = None # No siblings to compare
+ sibling_coverage = _sibling_coverage(file_path, governing, all_decisions)
- # Compute alignment score
- if deprecated and not active and not proposed:
- score = "low"
- explanation = (
- "All governing decisions are deprecated/superseded. "
- "This file likely contains technical debt that should be migrated."
- )
- elif stale and len(stale) >= len(governing) / 2:
- score = "low"
- explanation = (
- f"{len(stale)} of {len(governing)} governing decision(s) are stale. "
- f"The architectural rationale may no longer apply."
- )
- elif active:
- if sibling_coverage is not None and sibling_coverage >= 0.5:
- score = "high"
- explanation = (
- f"Follows {len(active)} active decision(s) shared with sibling files. "
- f"This file aligns with established patterns in {dir_path}/."
- )
- elif sibling_coverage is not None and sibling_coverage < 0.5:
- score = "medium"
- explanation = (
- f"Has {len(active)} active decision(s) but limited overlap with "
- f"sibling files in {dir_path}/. May use a different pattern than neighbors."
- )
- else:
- score = "high"
- explanation = f"Governed by {len(active)} active decision(s)."
- elif proposed:
- score = "medium"
- explanation = (
- f"Governed by {len(proposed)} proposed (unreviewed) decision(s). "
- f"Patterns are established but not yet formally approved."
- )
- else:
- score = "medium"
- explanation = f"Governed by {len(governing)} decision(s) with mixed status."
+ score, explanation = _alignment_score(
+ governing, active, deprecated, stale, proposed, dir_path, sibling_coverage
+ )
return {
"score": score,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
index 36441bf44..653b4a931 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
@@ -3,6 +3,8 @@
from __future__ import annotations
import json
+from collections.abc import Callable
+from dataclasses import dataclass, field
from typing import Any
from sqlalchemy import select
@@ -30,6 +32,185 @@ from repowise.server.mcp_server._helpers import (
from repowise.server.mcp_server._meta import build_meta as _build_meta
+@dataclass
+class _FindingFilters:
+ """Filter parameters shared by the single-repo and workspace code paths."""
+
+ kind: str | None
+ safe_only: bool
+ min_confidence: float
+ directory: str | None
+ owner: str | None
+ excluded_kinds: set[str] = field(default_factory=set)
+
+
+def _compute_excluded_kinds(
+ *,
+ no_unreachable: bool,
+ no_unused_exports: bool,
+ include_internals: bool,
+ include_zombie_packages: bool,
+) -> set[str]:
+ """Derive the set of finding kinds to exclude from the scope flags."""
+ excluded: set[str] = set()
+ if no_unreachable:
+ excluded.add("unreachable_file")
+ if no_unused_exports:
+ excluded.add("unused_export")
+ if not include_internals:
+ excluded.add("unused_internal")
+ if not include_zombie_packages:
+ excluded.add("zombie_package")
+ return excluded
+
+
+def _apply_finding_filters(findings: list, filters: _FindingFilters) -> list:
+ """Apply the kind/safety/confidence/directory/owner filters in order."""
+ filtered = findings
+ if filters.kind:
+ filtered = [f for f in filtered if f.kind == filters.kind]
+ elif filters.excluded_kinds:
+ filtered = [f for f in filtered if f.kind not in filters.excluded_kinds]
+ if filters.safe_only:
+ filtered = [f for f in filtered if _effective_safe(f)]
+ if filters.min_confidence > 0:
+ filtered = [f for f in filtered if f.confidence >= filters.min_confidence]
+ if filters.directory:
+ prefix = filters.directory.rstrip("/") + "/"
+ filtered = [f for f in filtered if f.file_path.startswith(prefix)]
+ if filters.owner:
+ owner_lower = filters.owner.lower()
+ filtered = [
+ f for f in filtered if f.primary_owner and f.primary_owner.lower() == owner_lower
+ ]
+ return filtered
+
+
+async def _get_dead_code_all_repos(
+ filters: _FindingFilters,
+ limit: int,
+ tier: str | None,
+ apply_limit_note: Callable[[dict[str, Any]], None],
+) -> dict:
+ """Aggregate dead-code findings across every repo in the workspace."""
+ contexts = await _resolve_all_contexts()
+ merged_findings: list[dict] = []
+ total_all = 0
+ total_deletable = 0
+ total_safe = 0
+ merged_by_kind: dict[str, int] = {}
+
+ for ctx in contexts:
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
+
+ all_query = select(DeadCodeFinding).where(
+ DeadCodeFinding.repository_id == repository.id,
+ DeadCodeFinding.status == "open",
+ )
+ all_result = await session.execute(all_query)
+ repo_findings = filter_rows_by_attr(
+ list(all_result.scalars().all()), "file_path", _get_exclude_spec(ctx.path)
+ )
+
+ git_meta_map = await _load_git_meta_map(session, repository.id, repo_findings)
+
+ repo_filtered = _apply_finding_filters(repo_findings, filters)
+
+ for f in repo_filtered:
+ serialized = _serialize_finding(f, git_meta_map)
+ serialized["repo"] = ctx.alias
+ merged_findings.append(serialized)
+
+ # Accumulate summary stats from unfiltered findings
+ total_all += len(repo_findings)
+ total_deletable += sum(f.lines for f in repo_findings if _effective_safe(f))
+ total_safe += sum(1 for f in repo_findings if _effective_safe(f))
+ for f in repo_findings:
+ merged_by_kind[f.kind] = merged_by_kind.get(f.kind, 0) + 1
+
+ # Sort merged findings by confidence descending
+ merged_findings.sort(key=lambda d: (-d["confidence"], -d["lines"]))
+
+ summary = {
+ "total_findings": total_all,
+ "filtered_findings": len(merged_findings),
+ "deletable_lines": total_deletable,
+ "safe_to_delete_count": total_safe,
+ "by_kind": merged_by_kind,
+ }
+
+ tiers = _build_tiers_from_dicts(merged_findings, limit, tier)
+
+ # Cross-repo confidence adjustment for workspace-wide findings
+ _adjust_dead_code_cross_repo(tiers, None)
+
+ result_ws: dict[str, Any] = {
+ "workspace": True,
+ "summary": summary,
+ "tiers": tiers,
+ "impact": _compute_impact(tiers),
+ }
+ apply_limit_note(result_ws)
+ result_ws["_meta"] = _build_meta()
+ return result_ws
+
+
+def _build_tiers_from_dicts(
+ merged_findings: list[dict], limit: int, tier: str | None
+) -> dict[str, Any]:
+ """Build the high/medium/low tier structure from pre-serialized dicts."""
+ high = [f for f in merged_findings if f["confidence"] >= 0.8]
+ medium = [f for f in merged_findings if 0.5 <= f["confidence"] < 0.8]
+ low = [f for f in merged_findings if f["confidence"] < 0.5]
+
+ def _tier_from_dicts(items: list[dict], desc: str) -> dict:
+ return {
+ "description": desc,
+ "count": len(items),
+ "lines": sum(f["lines"] for f in items),
+ "safe_count": sum(1 for f in items if f["safe_to_delete"]),
+ "findings": items[:limit],
+ "truncated": len(items) > limit,
+ }
+
+ tiers: dict[str, Any] = {}
+ if tier is None or tier == "high":
+ tiers["high"] = _tier_from_dicts(high, _TIER_DESC_HIGH)
+ if tier is None or tier == "medium":
+ tiers["medium"] = _tier_from_dicts(medium, _TIER_DESC_MEDIUM)
+ if tier is None or tier == "low":
+ tiers["low"] = _tier_from_dicts(low, _TIER_DESC_LOW)
+ return tiers
+
+
+async def _load_git_meta_map(session: Any, repository_id: Any, findings: list) -> dict[str, Any]:
+ """Load git metadata keyed by file path for the given findings."""
+ finding_paths = list({f.file_path for f in findings})
+ if not finding_paths:
+ return {}
+ git_res = await session.execute(
+ select(GitMetadata).where(
+ GitMetadata.repository_id == repository_id,
+ GitMetadata.file_path.in_(finding_paths),
+ )
+ )
+ return {g.file_path: g for g in git_res.scalars().all()}
+
+
+_TIER_DESC_HIGH = (
+ "High confidence (>=0.8): No references found in the codebase. "
+ "Strong cleanup candidates — review (especially runtime-loaded files) before deleting."
+)
+_TIER_DESC_MEDIUM = (
+ "Medium confidence (0.5-0.8): Likely unused but may have indirect references. "
+ "Review before deleting."
+)
+_TIER_DESC_LOW = (
+ "Low confidence (<0.5): Potentially used via dynamic imports or reflection. Investigate first."
+)
+
+
@mcp.tool()
async def get_dead_code(
repo: str | None = None,
@@ -75,143 +256,31 @@ async def get_dead_code(
limit = min(max(limit, 1), max_per_tier)
limit_clamped = requested_limit > max_per_tier
- # --- repo="all": aggregate dead code across all repos ---
- if repo == "all":
- contexts = await _resolve_all_contexts()
- merged_findings: list[dict] = []
- total_all = 0
- total_deletable = 0
- total_safe = 0
- merged_by_kind: dict[str, int] = {}
-
- for ctx in contexts:
- async with get_session(ctx.session_factory) as session:
- repository = await _get_repo(session)
-
- all_query = select(DeadCodeFinding).where(
- DeadCodeFinding.repository_id == repository.id,
- DeadCodeFinding.status == "open",
- )
- all_result = await session.execute(all_query)
- repo_findings = filter_rows_by_attr(
- list(all_result.scalars().all()), "file_path", _get_exclude_spec(ctx.path)
- )
-
- finding_paths = list({f.file_path for f in repo_findings})
- git_meta_map: dict[str, Any] = {}
- if finding_paths:
- git_res = await session.execute(
- select(GitMetadata).where(
- GitMetadata.repository_id == repository.id,
- GitMetadata.file_path.in_(finding_paths),
- )
- )
- git_meta_map = {g.file_path: g for g in git_res.scalars().all()}
-
- # Apply scope-based exclusions
- _excluded_kinds: set[str] = set()
- if no_unreachable:
- _excluded_kinds.add("unreachable_file")
- if no_unused_exports:
- _excluded_kinds.add("unused_export")
- if not include_internals:
- _excluded_kinds.add("unused_internal")
- if not include_zombie_packages:
- _excluded_kinds.add("zombie_package")
-
- repo_filtered = repo_findings
- if kind:
- repo_filtered = [f for f in repo_filtered if f.kind == kind]
- elif _excluded_kinds:
- repo_filtered = [f for f in repo_filtered if f.kind not in _excluded_kinds]
- if safe_only:
- repo_filtered = [f for f in repo_filtered if _effective_safe(f)]
- if min_confidence > 0:
- repo_filtered = [f for f in repo_filtered if f.confidence >= min_confidence]
- if directory:
- prefix = directory.rstrip("/") + "/"
- repo_filtered = [f for f in repo_filtered if f.file_path.startswith(prefix)]
- if owner:
- owner_lower = owner.lower()
- repo_filtered = [
- f
- for f in repo_filtered
- if f.primary_owner and f.primary_owner.lower() == owner_lower
- ]
-
- for f in repo_filtered:
- serialized = _serialize_finding(f, git_meta_map)
- serialized["repo"] = ctx.alias
- merged_findings.append(serialized)
-
- # Accumulate summary stats from unfiltered findings
- total_all += len(repo_findings)
- total_deletable += sum(f.lines for f in repo_findings if _effective_safe(f))
- total_safe += sum(1 for f in repo_findings if _effective_safe(f))
- for f in repo_findings:
- merged_by_kind[f.kind] = merged_by_kind.get(f.kind, 0) + 1
-
- # Sort merged findings by confidence descending
- merged_findings.sort(key=lambda d: (-d["confidence"], -d["lines"]))
-
- summary = {
- "total_findings": total_all,
- "filtered_findings": len(merged_findings),
- "deletable_lines": total_deletable,
- "safe_to_delete_count": total_safe,
- "by_kind": merged_by_kind,
- }
-
- # Build pseudo-tiered structure from serialized dicts
- high = [f for f in merged_findings if f["confidence"] >= 0.8]
- medium = [f for f in merged_findings if 0.5 <= f["confidence"] < 0.8]
- low = [f for f in merged_findings if f["confidence"] < 0.5]
-
- def _tier_from_dicts(items: list[dict], desc: str) -> dict:
- return {
- "description": desc,
- "count": len(items),
- "lines": sum(f["lines"] for f in items),
- "safe_count": sum(1 for f in items if f["safe_to_delete"]),
- "findings": items[:limit],
- "truncated": len(items) > limit,
- }
-
- tiers: dict[str, Any] = {}
- if tier is None or tier == "high":
- tiers["high"] = _tier_from_dicts(
- high,
- "High confidence (>=0.8): No references found in the codebase. "
- "Strong cleanup candidates — review (especially runtime-loaded files) before deleting.",
- )
- if tier is None or tier == "medium":
- tiers["medium"] = _tier_from_dicts(
- medium,
- "Medium confidence (0.5-0.8): Likely unused but may have indirect references. Review before deleting.",
- )
- if tier is None or tier == "low":
- tiers["low"] = _tier_from_dicts(
- low,
- "Low confidence (<0.5): Potentially used via dynamic imports or reflection. Investigate first.",
- )
-
- # Cross-repo confidence adjustment for workspace-wide findings
- _adjust_dead_code_cross_repo(tiers, None)
+ filters = _FindingFilters(
+ kind=kind,
+ safe_only=safe_only,
+ min_confidence=min_confidence,
+ directory=directory,
+ owner=owner,
+ excluded_kinds=_compute_excluded_kinds(
+ no_unreachable=no_unreachable,
+ no_unused_exports=no_unused_exports,
+ include_internals=include_internals,
+ include_zombie_packages=include_zombie_packages,
+ ),
+ )
- result_ws: dict[str, Any] = {
- "workspace": True,
- "summary": summary,
- "tiers": tiers,
- "impact": _compute_impact(tiers),
- }
+ def _maybe_limit_note(target: dict[str, Any]) -> None:
if limit_clamped:
- result_ws["limit_note"] = (
+ target["limit_note"] = (
f"Requested limit={requested_limit} exceeded the MCP transport budget "
f"and was clamped to {max_per_tier}. Use tier/directory/owner filters "
"or paginate to see more findings."
)
- result_ws["_meta"] = _build_meta()
- return result_ws
+
+ # --- repo="all": aggregate dead code across all repos ---
+ if repo == "all":
+ return await _get_dead_code_all_repos(filters, limit, tier, _maybe_limit_note)
# --- Single repo path ---
ctx = await _resolve_repo_context(repo)
@@ -230,46 +299,10 @@ async def get_dead_code(
all_findings = list(all_result.scalars().all())
# Phase 4: load git metadata for "last meaningful change" enrichment
- finding_paths = list({f.file_path for f in all_findings})
- git_meta_map: dict[str, Any] = {}
- if finding_paths:
- git_res = await session.execute(
- select(GitMetadata).where(
- GitMetadata.repository_id == repository.id,
- GitMetadata.file_path.in_(finding_paths),
- )
- )
- git_meta_map = {g.file_path: g for g in git_res.scalars().all()}
-
- # --- Build excluded kinds from scope flags ---
- _excluded_kinds: set[str] = set()
- if no_unreachable:
- _excluded_kinds.add("unreachable_file")
- if no_unused_exports:
- _excluded_kinds.add("unused_export")
- if not include_internals:
- _excluded_kinds.add("unused_internal")
- if not include_zombie_packages:
- _excluded_kinds.add("zombie_package")
+ git_meta_map = await _load_git_meta_map(session, repository.id, all_findings)
# --- Apply filters ---
- filtered = all_findings
- if kind:
- filtered = [f for f in filtered if f.kind == kind]
- elif _excluded_kinds:
- filtered = [f for f in filtered if f.kind not in _excluded_kinds]
- if safe_only:
- filtered = [f for f in filtered if _effective_safe(f)]
- if min_confidence > 0:
- filtered = [f for f in filtered if f.confidence >= min_confidence]
- if directory:
- prefix = directory.rstrip("/") + "/"
- filtered = [f for f in filtered if f.file_path.startswith(prefix)]
- if owner:
- owner_lower = owner.lower()
- filtered = [
- f for f in filtered if f.primary_owner and f.primary_owner.lower() == owner_lower
- ]
+ filtered = _apply_finding_filters(all_findings, filters)
# --- Build tiered structure ---
tiers = _build_tiers(filtered, limit, tier, git_meta_map, collector)
@@ -301,12 +334,7 @@ async def get_dead_code(
# --- Impact estimate ---
result["impact"] = _compute_impact(tiers)
- if limit_clamped:
- result["limit_note"] = (
- f"Requested limit={requested_limit} exceeded the MCP transport budget "
- f"and was clamped to {max_per_tier}. Use tier/directory/owner filters "
- "or paginate to see more findings."
- )
+ _maybe_limit_note(result)
result["_meta"] = _build_meta(repository=repository)
collector.attach(result)
@@ -447,24 +475,11 @@ def _build_tiers(
tiers = {}
if tier_filter is None or tier_filter == "high":
- tiers["high"] = _tier_block(
- "high",
- high,
- "High confidence (>=0.8): No references found in the codebase. "
- "Strong cleanup candidates — review (especially runtime-loaded files) before deleting.",
- )
+ tiers["high"] = _tier_block("high", high, _TIER_DESC_HIGH)
if tier_filter is None or tier_filter == "medium":
- tiers["medium"] = _tier_block(
- "medium",
- medium,
- "Medium confidence (0.5-0.8): Likely unused but may have indirect references. Review before deleting.",
- )
+ tiers["medium"] = _tier_block("medium", medium, _TIER_DESC_MEDIUM)
if tier_filter is None or tier_filter == "low":
- tiers["low"] = _tier_block(
- "low",
- low,
- "Low confidence (<0.5): Potentially used via dynamic imports or reflection. Investigate first.",
- )
+ tiers["low"] = _tier_block("low", low, _TIER_DESC_LOW)
return tiers
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 993dadcca..c848c82ef 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py
@@ -216,6 +216,454 @@ def _build_workspace_footer() -> dict | None:
return footer
+async def _load_overview_page(session: Any, repository: Any) -> Page | None:
+ """Repo overview page, preferring the canonical target_path=<repo_name> row."""
+ result = await session.execute(
+ select(Page)
+ .where(
+ Page.repository_id == repository.id,
+ Page.page_type == "repo_overview",
+ )
+ .order_by(
+ (Page.target_path == repository.name).desc(),
+ Page.updated_at.desc(),
+ )
+ )
+ return result.scalars().first()
+
+
+async def _load_module_pages(
+ session: Any, repository: Any, collector: OmissionCollector
+) -> list[Page]:
+ """Module pages capped to 20; the remainder goes to the omission store."""
+ result = await session.execute(
+ select(Page)
+ .where(
+ Page.repository_id == repository.id,
+ Page.page_type == "module_page",
+ )
+ .order_by(Page.title)
+ )
+ all_module_pages = result.scalars().all()
+ if len(all_module_pages) > 20:
+ collector.add(
+ f"module pages beyond cap=20 ({len(all_module_pages) - 20} dropped)",
+ "\n".join(f"{p.title}: {p.target_path}" for p in all_module_pages[20:]),
+ )
+ return all_module_pages[:20]
+
+
+def _drop_fixtures(ids: list[str], exclude_spec: Any) -> list[str]:
+ """Drop excluded ids and obvious fixture/test-data paths."""
+ return [
+ nid
+ for nid in ids
+ if not is_excluded(nid, exclude_spec)
+ and not any(
+ seg in nid.lower() for seg in ("fixture", "test_data", "testdata", "sample_repo")
+ )
+ ]
+
+
+async def _resolve_entry_point_ids(session: Any, repository: Any, exclude_spec: Any) -> list[str]:
+ """Curated orientation entry points, falling back to the raw is_entry_point flag.
+
+ Re-export barrels and package-export sinks are demoted; survivors are ranked
+ by execution centrality. Older indexes (no kg_project_meta row) fall back to
+ the flag.
+ """
+ proj_meta = await _get_kg_project_meta(session, repository.id)
+ curated_ids: list[str] = []
+ if proj_meta is not None:
+ try:
+ curated_ids = json.loads(proj_meta.entry_points_json or "[]")
+ except (json.JSONDecodeError, TypeError):
+ curated_ids = []
+
+ if curated_ids:
+ return _drop_fixtures(curated_ids, exclude_spec)
+
+ result = await session.execute(
+ select(GraphNode).where(
+ GraphNode.repository_id == repository.id,
+ GraphNode.is_entry_point == True, # noqa: E712
+ GraphNode.is_test == False, # noqa: E712
+ )
+ )
+ entry_nodes = filter_graph_nodes(
+ [
+ n
+ for n in result.scalars().all()
+ if not any(
+ seg in n.node_id.lower()
+ for seg in ("fixture", "test_data", "testdata", "sample_repo")
+ )
+ ],
+ exclude_spec,
+ )
+ return [n.node_id for n in entry_nodes]
+
+
+def _build_git_health(all_git: list) -> dict[str, Any]:
+ """Repo-wide git health summary (hotspots, bus factor, churn trend, top modules)."""
+ if not all_git:
+ return {}
+
+ hotspot_count = sum(1 for g in all_git if g.is_hotspot)
+ bus_factors = [getattr(g, "bus_factor", 0) or 0 for g in all_git]
+ avg_bus = sum(bus_factors) / len(bus_factors) if bus_factors else 0
+ bf1 = sum(1 for b in bus_factors if b == 1)
+ c30_total = sum(g.commit_count_30d or 0 for g in all_git)
+ c90_total = sum(g.commit_count_90d or 0 for g in all_git)
+ baseline = c90_total - c30_total
+ if baseline > 0:
+ ratio = (c30_total / 30.0) / (baseline / 60.0)
+ churn_trend = "increasing" if ratio > 1.5 else ("decreasing" if ratio < 0.5 else "stable")
+ else:
+ churn_trend = "increasing" if c30_total > 0 else "stable"
+ # Top churn modules (group by first directory component)
+ module_churn: Counter = Counter()
+ for g in all_git:
+ parts = g.file_path.split("/")
+ mod = parts[0] if len(parts) == 1 else "/".join(parts[:2])
+ module_churn[mod] += g.commit_count_90d or 0
+ top_modules = [m for m, _ in module_churn.most_common(5) if module_churn[m] > 0]
+
+ return {
+ "total_files_indexed": len(all_git),
+ "hotspot_count": hotspot_count,
+ "avg_bus_factor": round(avg_bus, 1),
+ "files_with_bus_factor_1": bf1,
+ "churn_trend": churn_trend,
+ "top_churn_modules": top_modules,
+ }
+
+
+def _build_knowledge_map(all_git: list) -> dict[str, Any]:
+ """Top owners and knowledge silos aggregated across all indexed files."""
+ if not all_git:
+ return {}
+
+ owner_file_count: dict[str, int] = defaultdict(int)
+ owner_pct_sum: dict[str, float] = defaultdict(float)
+ for g in all_git:
+ email = g.primary_owner_email or ""
+ if email:
+ owner_file_count[email] += 1
+ owner_pct_sum[email] += float(g.primary_owner_commit_pct or 0.0)
+
+ total_files = len(all_git) or 1
+ top_owners = sorted(
+ [
+ {
+ "email": email,
+ "files_owned": count,
+ "percentage": round(count / total_files * 100.0, 1),
+ }
+ for email, count in owner_file_count.items()
+ ],
+ key=lambda x: -x["files_owned"],
+ )[:10]
+
+ # knowledge_silos: files where primary owner has > 80% ownership.
+ # Filter out boilerplate (migrations, __init__.py, config, lock files).
+ silo_exclude_patterns = (
+ "alembic/versions/",
+ "__init__.py",
+ "migrations/",
+ ".lock",
+ "package-lock",
+ "conftest.py",
+ )
+ knowledge_silos = [
+ g.file_path
+ for g in sorted(all_git, key=lambda g: -(g.primary_owner_commit_pct or 0.0))
+ if (g.primary_owner_commit_pct or 0.0) > 0.8
+ and not any(pat in g.file_path for pat in silo_exclude_patterns)
+ ][:10]
+
+ return {
+ "top_owners": top_owners,
+ "knowledge_silos": knowledge_silos,
+ }
+
+
+async def _load_community_nodes(
+ session: Any, repository: Any, exclude_spec: Any, all_git: list
+) -> list[GraphNode]:
+ """File nodes for community grouping; widened to all non-test nodes when git data exists."""
+ if not all_git:
+ node_result = await session.execute(
+ select(GraphNode).where(
+ GraphNode.repository_id == repository.id,
+ GraphNode.node_type == "file",
+ )
+ )
+ else:
+ node_result = await session.execute(
+ select(GraphNode).where(
+ GraphNode.repository_id == repository.id,
+ GraphNode.is_test == False, # noqa: E712
+ )
+ )
+ return filter_graph_nodes(list(node_result.scalars().all()), exclude_spec)
+
+
+def _community_display_label(
+ label: str, members: list[GraphNode], cid: int, generic_labels: set[str]
+) -> str:
+ """Use the heuristic label, or the dominant specific directory when it's generic."""
+ if label and label.lower() not in generic_labels:
+ return label
+ dir_counts: Counter = Counter()
+ for m in members:
+ parts = m.node_id.split("/")
+ # Use the deepest meaningful directory segment
+ for p in reversed(parts[:-1]):
+ if p.lower() not in generic_labels and p not in ("src",):
+ dir_counts[p] += 1
+ break
+ return dir_counts.most_common(1)[0][0] if dir_counts else f"cluster_{cid}"
+
+
+def _build_community_summary(all_nodes: list[GraphNode]) -> list[dict[str, Any]]:
+ """Top-10 communities by size, skipping generic/unhelpful labels."""
+ community_groups: dict[int, list[GraphNode]] = defaultdict(list)
+ for n in all_nodes:
+ if n.node_type == "file" and n.community_id is not None:
+ community_groups[n.community_id].append(n)
+
+ generic_labels = {"packages", "src", "lib", "core", "app", ""}
+ community_summary: list[dict[str, Any]] = []
+ for cid, members in sorted(community_groups.items(), key=lambda x: -len(x[1])):
+ if len(community_summary) >= 10:
+ break
+ label = ""
+ cohesion = 0.0
+ if members:
+ try:
+ meta = json.loads(members[0].community_meta_json or "{}")
+ label = meta.get("label", "")
+ cohesion = meta.get("cohesion", 0.0)
+ except (json.JSONDecodeError, TypeError):
+ pass
+
+ community_summary.append(
+ {
+ "id": cid,
+ "label": _community_display_label(label, members, cid, generic_labels),
+ "size": len(members),
+ "cohesion": round(cohesion, 3),
+ }
+ )
+ return community_summary
+
+
+async def _build_architecture(session: Any, repository: Any) -> dict[str, Any]:
+ """KG architecture layers + tour availability."""
+ kg_layers = await _get_kg_layers(session, repository.id)
+ kg_tour = await _get_kg_tour_steps(session, repository.id)
+ if not kg_layers:
+ return {}
+ return {
+ "layers": [
+ {
+ "name": layer.name,
+ "description": _truncate_at_word(layer.description or "", 120),
+ "file_count": len(json.loads(layer.node_ids_json) if layer.node_ids_json else []),
+ }
+ for layer in kg_layers
+ ],
+ "tour_available": bool(kg_tour),
+ "tour_step_count": len(kg_tour),
+ }
+
+
+async def _build_reading_order(session: Any, repository: Any) -> list[dict[str, Any]]:
+ """Canonical onboarding spine — only slots that actually produced a page."""
+ ro_result = await session.execute(
+ select(Page).where(
+ Page.repository_id == repository.id,
+ Page.page_type.in_(["onboarding", *PROMOTED_SLOTS.keys()]),
+ )
+ )
+ slot_to_page: dict[str, Page] = {}
+ for p in ro_result.scalars().all():
+ if p.page_type == "onboarding":
+ slot = (p.target_path or "").rsplit("/", 1)[-1]
+ else:
+ slot = PROMOTED_SLOTS.get(p.page_type, "")
+ if slot and slot not in slot_to_page:
+ slot_to_page[slot] = p
+ reading_order: list[dict[str, Any]] = []
+ for slot in ONBOARDING_ORDER:
+ p = slot_to_page.get(slot)
+ if p is None:
+ continue
+ reading_order.append(
+ {
+ "order": len(reading_order) + 1,
+ "slot": slot,
+ "title": p.title,
+ "page_id": p.id,
+ "target_path": p.target_path,
+ }
+ )
+ return reading_order
+
+
+def _resolve_title(overview_page: Page | None, repository: Any) -> str:
+ """Substitute the real repo name back into legacy "Repository Overview: repo" titles.
+
+ Exact match only: a prefix replace would corrupt any repo whose name starts
+ with "repo" ("Repository Overview: repowise" -> "...repowisewise").
+ """
+ if not overview_page:
+ return repository.name
+ persisted_title = overview_page.title or ""
+ if persisted_title.strip() == "Repository Overview: repo":
+ return f"Repository Overview: {repository.name}"
+ return persisted_title
+
+
+async def _build_code_health(session: Any, repository: Any) -> dict[str, Any]:
+ """Headline code-health KPIs; empty when health hasn't been run on this repo."""
+ try:
+ health_summary = await _get_health_summary(session, repository.id)
+ metrics_rows = await _get_health_metrics(session, repository.id)
+ if not metrics_rows:
+ return {}
+ # Hotspot health: NLOC-weighted avg over the top-25% files by NLOC,
+ # matching the dashboard KPI definition.
+ sorted_by_nloc = sorted(metrics_rows, key=lambda m: m.nloc or 0, reverse=True)
+ top_q = sorted_by_nloc[: max(1, len(sorted_by_nloc) // 4)]
+ tot = sum(max(m.nloc, 1) for m in top_q)
+ hotspot_avg = sum(m.score * max(m.nloc, 1) for m in top_q) / tot if tot else 10.0
+ return {
+ "average_health": health_summary["average_health"],
+ "band": band_for(float(health_summary["average_health"])),
+ "hotspot_health": round(hotspot_avg, 2),
+ "worst_performer_path": health_summary["worst_performer_path"],
+ "worst_performer_score": health_summary["worst_performer_score"],
+ "open_findings": health_summary["open_findings"],
+ "file_count": health_summary["file_count"],
+ "distribution": health_distribution(metrics_rows),
+ }
+ except Exception:
+ return {}
+
+
+async def _build_recent_reversals(session: Any, repository: Any) -> list[dict[str, Any]]:
+ """Recent supersede edges resolved to newer/older decision title pairs."""
+ supersede_edges_res = await session.execute(
+ select(DecisionEdge)
+ .where(
+ DecisionEdge.repository_id == repository.id,
+ DecisionEdge.kind == "supersedes",
+ )
+ .order_by(DecisionEdge.created_at.desc())
+ .limit(5)
+ )
+ supersede_edges = supersede_edges_res.scalars().all()
+ if not supersede_edges:
+ return []
+ all_edge_ids = list(
+ {e.src_decision_id for e in supersede_edges} | {e.dst_decision_id for e in supersede_edges}
+ )
+ edge_recs_res = await session.execute(
+ select(DecisionRecord).where(DecisionRecord.id.in_(all_edge_ids))
+ )
+ edge_recs = {r.id: r for r in edge_recs_res.scalars().all()}
+ recent_reversals: list[dict[str, Any]] = []
+ for edge in supersede_edges:
+ src = edge_recs.get(edge.src_decision_id)
+ dst = edge_recs.get(edge.dst_decision_id)
+ if src and dst:
+ recent_reversals.append(
+ {
+ "newer": {"id": src.id, "title": src.title},
+ "older": {
+ "id": dst.id,
+ "title": dst.title,
+ "status": dst.status,
+ },
+ }
+ )
+ return recent_reversals
+
+
+async def _build_key_decisions(session: Any, repository: Any) -> dict[str, Any]:
+ """Top active decisions + recent reversals (Phase 4A)."""
+ try:
+ top_decisions_res = await session.execute(
+ select(DecisionRecord)
+ .where(
+ DecisionRecord.repository_id == repository.id,
+ DecisionRecord.status == "active",
+ )
+ .order_by(DecisionRecord.confidence.desc())
+ .limit(5)
+ )
+ top_decisions = top_decisions_res.scalars().all()
+ if not top_decisions:
+ return {}
+ key_decisions_list = []
+ for dr in top_decisions:
+ try:
+ affected_files = json.loads(dr.affected_files_json or "[]")[:3]
+ except (json.JSONDecodeError, TypeError):
+ affected_files = []
+ key_decisions_list.append(
+ {
+ "id": dr.id,
+ "title": dr.title,
+ "status": dr.status,
+ "confidence": dr.confidence,
+ "verification": dr.verification,
+ "affected_files": affected_files,
+ }
+ )
+ return {
+ "top_active": key_decisions_list,
+ "recent_reversals": await _build_recent_reversals(session, repository),
+ }
+ except Exception:
+ return {}
+
+
+def _build_guided_tour(overview_page: Page, result: dict[str, Any]) -> None:
+ """Attach the topology-driven guided tour + layer order from overview page metadata."""
+ from repowise.core.generation.models import compute_page_id
+
+ try:
+ ov_meta = json.loads(overview_page.metadata_json or "{}")
+ except (json.JSONDecodeError, TypeError):
+ ov_meta = {}
+ tour = ov_meta.get("guided_tour") or []
+ if tour:
+ result["guided_tour"] = [
+ {
+ "order": s.get("order"),
+ "title": s.get("title"),
+ "kind": s.get("kind"),
+ "reason": s.get("reason"),
+ "target_path": s.get("target_path"),
+ "page_id": compute_page_id(
+ s.get("page_type", "file_page"), s.get("target_path", "")
+ ),
+ }
+ for s in tour
+ ]
+ result["guided_tour_hint"] = (
+ "Topology-ordered walk of the codebase: read these page_ids "
+ "in order — entry points first, then the files they import, "
+ "with infrastructure last. Each step builds on the previous."
+ )
+ layer_order = ov_meta.get("layer_order") or []
+ if layer_order:
+ result.setdefault("architecture", {})["layer_order"] = layer_order
+
+
@mcp.tool()
async def get_overview(repo: str | None = None) -> dict:
"""Architecture map for an unfamiliar repo — first call when you don't know your way around.
@@ -246,89 +694,9 @@ async def get_overview(repo: str | None = None) -> dict:
async with get_session(ctx.session_factory) as session:
repository = await _get_repo(session)
- # Get repo overview page. Older indexes occasionally left a stale
- # row with target_path='repo' alongside the canonical
- # target_path=<repo_name> row, so prefer the row matching the repo
- # name and fall back to the most recently updated one. Using
- # scalar_one_or_none here would crash with MultipleResultsFound on
- # those legacy DBs.
- result = await session.execute(
- select(Page)
- .where(
- Page.repository_id == repository.id,
- Page.page_type == "repo_overview",
- )
- .order_by(
- (Page.target_path == repository.name).desc(),
- Page.updated_at.desc(),
- )
- )
- overview_page = result.scalars().first()
-
- # Get module pages
- result = await session.execute(
- select(Page)
- .where(
- Page.repository_id == repository.id,
- Page.page_type == "module_page",
- )
- .order_by(Page.title)
- )
- all_module_pages = result.scalars().all()
- module_pages = all_module_pages[:20] # Cap to keep response bounded
- if len(all_module_pages) > 20:
- collector.add(
- f"module pages beyond cap=20 ({len(all_module_pages) - 20} dropped)",
- "\n".join(f"{p.title}: {p.target_path}" for p in all_module_pages[20:]),
- )
-
- # Entry points: prefer the curated orientation list — re-export barrels
- # and package-export sinks demoted, survivors ranked by execution
- # centrality. The raw ``is_entry_point`` flag also tags every npm-exported
- # file (cn.ts, types/*.ts): high fan-in sinks that are the opposite of
- # where a reader starts. Fall back to the flag only for indexes built
- # before the curation pass (no ``kg_project_meta`` row).
- def _drop_fixtures(ids: list[str]) -> list[str]:
- return [
- nid
- for nid in ids
- if not is_excluded(nid, exclude_spec)
- and not any(
- seg in nid.lower()
- for seg in ("fixture", "test_data", "testdata", "sample_repo")
- )
- ]
-
- proj_meta = await _get_kg_project_meta(session, repository.id)
- curated_ids: list[str] = []
- if proj_meta is not None:
- try:
- curated_ids = json.loads(proj_meta.entry_points_json or "[]")
- except (json.JSONDecodeError, TypeError):
- curated_ids = []
-
- if curated_ids:
- entry_point_ids = _drop_fixtures(curated_ids)
- else:
- result = await session.execute(
- select(GraphNode).where(
- GraphNode.repository_id == repository.id,
- GraphNode.is_entry_point == True, # noqa: E712
- GraphNode.is_test == False, # noqa: E712
- )
- )
- entry_nodes = filter_graph_nodes(
- [
- n
- for n in result.scalars().all()
- if not any(
- seg in n.node_id.lower()
- for seg in ("fixture", "test_data", "testdata", "sample_repo")
- )
- ],
- exclude_spec,
- )
- entry_point_ids = [n.node_id for n in entry_nodes]
+ overview_page = await _load_overview_page(session, repository)
+ module_pages = await _load_module_pages(session, repository, collector)
+ entry_point_ids = await _resolve_entry_point_ids(session, repository, exclude_spec)
# Phase 4: repo-wide git health summary
git_res = await session.execute(
@@ -338,312 +706,15 @@ async def get_overview(repo: str | None = None) -> dict:
)
all_git = filter_rows_by_attr(list(git_res.scalars().all()), "file_path", exclude_spec)
- git_health: dict[str, Any] = {}
- if all_git:
- hotspot_count = sum(1 for g in all_git if g.is_hotspot)
- bus_factors = [getattr(g, "bus_factor", 0) or 0 for g in all_git]
- avg_bus = sum(bus_factors) / len(bus_factors) if bus_factors else 0
- bf1 = sum(1 for b in bus_factors if b == 1)
- c30_total = sum(g.commit_count_30d or 0 for g in all_git)
- c90_total = sum(g.commit_count_90d or 0 for g in all_git)
- baseline = c90_total - c30_total
- if baseline > 0:
- ratio = (c30_total / 30.0) / (baseline / 60.0)
- churn_trend = (
- "increasing" if ratio > 1.5 else ("decreasing" if ratio < 0.5 else "stable")
- )
- else:
- churn_trend = "increasing" if c30_total > 0 else "stable"
- # Top churn modules (group by first directory component)
- module_churn: Counter = Counter()
- for g in all_git:
- parts = g.file_path.split("/")
- mod = parts[0] if len(parts) == 1 else "/".join(parts[:2])
- module_churn[mod] += g.commit_count_90d or 0
- top_modules = [m for m, _ in module_churn.most_common(5) if module_churn[m] > 0]
-
- git_health = {
- "total_files_indexed": len(all_git),
- "hotspot_count": hotspot_count,
- "avg_bus_factor": round(avg_bus, 1),
- "files_with_bus_factor_1": bf1,
- "churn_trend": churn_trend,
- "top_churn_modules": top_modules,
- }
-
- # B. Knowledge map -------------------------------------------------------
- knowledge_map: dict[str, Any] = {}
- if all_git:
- # top_owners: aggregate primary_owner_email across all files
- owner_file_count: dict[str, int] = defaultdict(int)
- owner_pct_sum: dict[str, float] = defaultdict(float)
- for g in all_git:
- email = g.primary_owner_email or ""
- if email:
- owner_file_count[email] += 1
- owner_pct_sum[email] += float(g.primary_owner_commit_pct or 0.0)
-
- total_files = len(all_git) or 1
- top_owners = sorted(
- [
- {
- "email": email,
- "files_owned": count,
- "percentage": round(count / total_files * 100.0, 1),
- }
- for email, count in owner_file_count.items()
- ],
- key=lambda x: -x["files_owned"],
- )[:10]
-
- # knowledge_silos: files where primary owner has > 80% ownership
- # Filter out boilerplate (migrations, __init__.py, config, lock files)
- silo_exclude_patterns = (
- "alembic/versions/",
- "__init__.py",
- "migrations/",
- ".lock",
- "package-lock",
- "conftest.py",
- )
- knowledge_silos = [
- g.file_path
- for g in sorted(all_git, key=lambda g: -(g.primary_owner_commit_pct or 0.0))
- if (g.primary_owner_commit_pct or 0.0) > 0.8
- and not any(pat in g.file_path for pat in silo_exclude_patterns)
- ][:10]
-
- knowledge_map = {
- "top_owners": top_owners,
- "knowledge_silos": knowledge_silos,
- }
-
- # C. Community summary ---------------------------------------------------
- community_summary: list[dict[str, Any]] = []
- # Fetch file nodes for community grouping
- if not all_git:
- node_result = await session.execute(
- select(GraphNode).where(
- GraphNode.repository_id == repository.id,
- GraphNode.node_type == "file",
- )
- )
- all_nodes = filter_graph_nodes(list(node_result.scalars().all()), exclude_spec)
- else:
- node_result = await session.execute(
- select(GraphNode).where(
- GraphNode.repository_id == repository.id,
- GraphNode.is_test == False, # noqa: E712
- )
- )
- all_nodes = filter_graph_nodes(list(node_result.scalars().all()), exclude_spec)
-
- # Group file nodes by community_id
- community_groups: dict[int, list[GraphNode]] = defaultdict(list)
- for n in all_nodes:
- if n.node_type == "file" and n.community_id is not None:
- community_groups[n.community_id].append(n)
-
- # Sort communities by size descending, take top 10
- # Skip communities with generic/unhelpful labels
- generic_labels = {"packages", "src", "lib", "core", "app", ""}
- for cid, members in sorted(community_groups.items(), key=lambda x: -len(x[1])):
- if len(community_summary) >= 10:
- break
- label = ""
- cohesion = 0.0
- if members:
- try:
- meta = json.loads(members[0].community_meta_json or "{}")
- label = meta.get("label", "")
- cohesion = meta.get("cohesion", 0.0)
- except (json.JSONDecodeError, TypeError):
- pass
-
- # Build a useful label: if the heuristic label is generic,
- # use the most common directory segment among members
- display_label = label
- if not label or label.lower() in generic_labels:
- # Find dominant specific directory
- dir_counts: Counter = Counter()
- for m in members:
- parts = m.node_id.split("/")
- # Use the deepest meaningful directory segment
- for p in reversed(parts[:-1]):
- if p.lower() not in generic_labels and p not in ("src",):
- dir_counts[p] += 1
- break
- display_label = dir_counts.most_common(1)[0][0] if dir_counts else f"cluster_{cid}"
-
- community_summary.append(
- {
- "id": cid,
- "label": display_label,
- "size": len(members),
- "cohesion": round(cohesion, 3),
- }
- )
-
- # D. KG architecture layers + tour availability -------------------------
- kg_layers = await _get_kg_layers(session, repository.id)
- kg_tour = await _get_kg_tour_steps(session, repository.id)
- architecture: dict[str, Any] = {}
- if kg_layers:
- architecture["layers"] = [
- {
- "name": layer.name,
- "description": _truncate_at_word(layer.description or "", 120),
- "file_count": len(
- json.loads(layer.node_ids_json) if layer.node_ids_json else []
- ),
- }
- for layer in kg_layers
- ]
- architecture["tour_available"] = bool(kg_tour)
- architecture["tour_step_count"] = len(kg_tour)
-
- # E. Reading order — the canonical onboarding spine, mirrored for agents
- # so they can walk the wiki in the same order a human would (§ dual
- # audience). Only slots that actually produced a page are listed.
- ro_result = await session.execute(
- select(Page).where(
- Page.repository_id == repository.id,
- Page.page_type.in_(["onboarding", *PROMOTED_SLOTS.keys()]),
- )
- )
- slot_to_page: dict[str, Page] = {}
- for p in ro_result.scalars().all():
- if p.page_type == "onboarding":
- slot = (p.target_path or "").rsplit("/", 1)[-1]
- else:
- slot = PROMOTED_SLOTS.get(p.page_type, "")
- if slot and slot not in slot_to_page:
- slot_to_page[slot] = p
- reading_order: list[dict[str, Any]] = []
- for slot in ONBOARDING_ORDER:
- p = slot_to_page.get(slot)
- if p is None:
- continue
- reading_order.append(
- {
- "order": len(reading_order) + 1,
- "slot": slot,
- "title": p.title,
- "page_id": p.id,
- "target_path": p.target_path,
- }
- )
-
- # 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 ""
- 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
- # summary. Falls back to defaults (avg 10/10, no worst file) when
- # health hasn't been run on this repo yet.
- code_health: dict[str, Any] = {}
- try:
- health_summary = await _get_health_summary(session, repository.id)
- metrics_rows = await _get_health_metrics(session, repository.id)
- if metrics_rows:
- # Hotspot health: NLOC-weighted avg over the top-25% files
- # by NLOC, matching the dashboard KPI definition.
- sorted_by_nloc = sorted(metrics_rows, key=lambda m: m.nloc or 0, reverse=True)
- top_q = sorted_by_nloc[: max(1, len(sorted_by_nloc) // 4)]
- tot = sum(max(m.nloc, 1) for m in top_q)
- hotspot_avg = sum(m.score * max(m.nloc, 1) for m in top_q) / tot if tot else 10.0
- code_health = {
- "average_health": health_summary["average_health"],
- "band": band_for(float(health_summary["average_health"])),
- "hotspot_health": round(hotspot_avg, 2),
- "worst_performer_path": health_summary["worst_performer_path"],
- "worst_performer_score": health_summary["worst_performer_score"],
- "open_findings": health_summary["open_findings"],
- "file_count": health_summary["file_count"],
- "distribution": health_distribution(metrics_rows),
- }
- except Exception:
- code_health = {}
-
- # F. Key decisions + recent reversals (Phase 4A) -----------------------
- key_decisions_section: dict[str, Any] = {}
- try:
- top_decisions_res = await session.execute(
- select(DecisionRecord)
- .where(
- DecisionRecord.repository_id == repository.id,
- DecisionRecord.status == "active",
- )
- .order_by(DecisionRecord.confidence.desc())
- .limit(5)
- )
- top_decisions = top_decisions_res.scalars().all()
- if top_decisions:
- key_decisions_list = []
- for dr in top_decisions:
- try:
- affected_files = json.loads(dr.affected_files_json or "[]")[:3]
- except (json.JSONDecodeError, TypeError):
- affected_files = []
- key_decisions_list.append(
- {
- "id": dr.id,
- "title": dr.title,
- "status": dr.status,
- "confidence": dr.confidence,
- "verification": dr.verification,
- "affected_files": affected_files,
- }
- )
- recent_reversals: list[dict[str, Any]] = []
- supersede_edges_res = await session.execute(
- select(DecisionEdge)
- .where(
- DecisionEdge.repository_id == repository.id,
- DecisionEdge.kind == "supersedes",
- )
- .order_by(DecisionEdge.created_at.desc())
- .limit(5)
- )
- supersede_edges = supersede_edges_res.scalars().all()
- if supersede_edges:
- all_edge_ids = list(
- {e.src_decision_id for e in supersede_edges}
- | {e.dst_decision_id for e in supersede_edges}
- )
- edge_recs_res = await session.execute(
- select(DecisionRecord).where(DecisionRecord.id.in_(all_edge_ids))
- )
- edge_recs = {r.id: r for r in edge_recs_res.scalars().all()}
- for edge in supersede_edges:
- src = edge_recs.get(edge.src_decision_id)
- dst = edge_recs.get(edge.dst_decision_id)
- if src and dst:
- recent_reversals.append(
- {
- "newer": {"id": src.id, "title": src.title},
- "older": {
- "id": dst.id,
- "title": dst.title,
- "status": dst.status,
- },
- }
- )
- key_decisions_section = {
- "top_active": key_decisions_list,
- "recent_reversals": recent_reversals,
- }
- except Exception:
- key_decisions_section = {}
+ git_health = _build_git_health(all_git)
+ knowledge_map = _build_knowledge_map(all_git)
+ all_nodes = await _load_community_nodes(session, repository, exclude_spec, all_git)
+ community_summary = _build_community_summary(all_nodes)
+ architecture = await _build_architecture(session, repository)
+ reading_order = await _build_reading_order(session, repository)
+ title = _resolve_title(overview_page, repository)
+ code_health = await _build_code_health(session, repository)
+ key_decisions_section = await _build_key_decisions(session, repository)
result = {
"title": title,
@@ -681,35 +752,7 @@ async def get_overview(repo: str | None = None) -> dict:
# from the import graph (entry points first, then inward, infra last).
# Persisted on the repo_overview page metadata at generation time.
if overview_page:
- from repowise.core.generation.models import compute_page_id
-
- try:
- ov_meta = json.loads(overview_page.metadata_json or "{}")
- except (json.JSONDecodeError, TypeError):
- ov_meta = {}
- tour = ov_meta.get("guided_tour") or []
- if tour:
- result["guided_tour"] = [
- {
- "order": s.get("order"),
- "title": s.get("title"),
- "kind": s.get("kind"),
- "reason": s.get("reason"),
- "target_path": s.get("target_path"),
- "page_id": compute_page_id(
- s.get("page_type", "file_page"), s.get("target_path", "")
- ),
- }
- for s in tour
- ]
- result["guided_tour_hint"] = (
- "Topology-ordered walk of the codebase: read these page_ids "
- "in order — entry points first, then the files they import, "
- "with infrastructure last. Each step builds on the previous."
- )
- layer_order = ov_meta.get("layer_order") or []
- if layer_order:
- result.setdefault("architecture", {})["layer_order"] = layer_order
+ _build_guided_tour(overview_page, result)
# Append workspace context footer when in workspace mode
ws_footer = _build_workspace_footer()
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 7437c0024..4d45cb1e8 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk.py
@@ -233,6 +233,43 @@ async def _get_security_signals(session: AsyncSession, repo_id: str, target: str
return []
+def _build_co_changes(meta: Any, import_related: set[str], exclude_spec: Any) -> list[dict]:
+ """Top-5 co-change partners for *meta*, by frequency, with import-link flags.
+
+ Larger lists make MCP responses verbose without adding signal: top-5 captures
+ the bulk of the temporal-coupling mass and keeps tool output tight for agents.
+ """
+ partners = json.loads(meta.co_change_partners_json)
+ partners_sorted = sorted(
+ partners,
+ key=lambda p: p.get("co_change_count", p.get("count", 0)) or 0,
+ reverse=True,
+ )[:5]
+ return filter_dicts_by_key(
+ [
+ {
+ "file_path": p.get("file_path", p.get("path", "")),
+ "count": p.get("co_change_count", p.get("count", 0)),
+ "last_co_change": p.get("last_co_change"),
+ "has_import_link": p.get("file_path", p.get("path", "")) in import_related,
+ }
+ for p in partners_sorted
+ ],
+ "file_path",
+ exclude_spec,
+ )
+
+
+def _load_commit_categories(meta: Any) -> dict:
+ """Parse the persisted commit-category counts, tolerating malformed JSON."""
+ categories: dict = {}
+ cat_json = getattr(meta, "commit_categories_json", None)
+ if cat_json:
+ with contextlib.suppress(json.JSONDecodeError, TypeError):
+ categories = json.loads(cat_json)
+ return categories
+
+
async def _assess_one_target(
session: AsyncSession,
repository: Repository,
@@ -285,29 +322,7 @@ async def _assess_one_target(
hotspot_score = meta.churn_percentile or 0.0
- # Co-change partners — keep only the top-5 by frequency. Larger lists make
- # MCP responses verbose without adding signal: top-5 captures the bulk of
- # the temporal-coupling mass and keeps tool output tight for LLM agents.
- partners = json.loads(meta.co_change_partners_json)
- partners_sorted = sorted(
- partners,
- key=lambda p: p.get("co_change_count", p.get("count", 0)) or 0,
- reverse=True,
- )[:5]
- import_related = import_links.get(target, set())
- co_changes = filter_dicts_by_key(
- [
- {
- "file_path": p.get("file_path", p.get("path", "")),
- "count": p.get("co_change_count", p.get("count", 0)),
- "last_co_change": p.get("last_co_change"),
- "has_import_link": p.get("file_path", p.get("path", "")) in import_related,
- }
- for p in partners_sorted
- ],
- "file_path",
- exclude_spec,
- )
+ co_changes = _build_co_changes(meta, import_links.get(target, set()), exclude_spec)
owner = meta.primary_owner_name or "unknown"
pct = meta.primary_owner_commit_pct or 0.0
@@ -321,49 +336,35 @@ async def _assess_one_target(
# --- Impact surface ---
impact_surface = _compute_impact_surface(target, reverse_deps, node_meta, exclude_spec)
- # Phase 2: diff size & change magnitude
- lines_added = getattr(meta, "lines_added_90d", 0) or 0
- lines_deleted = getattr(meta, "lines_deleted_90d", 0) or 0
- avg_size = getattr(meta, "avg_commit_size", 0.0) or 0.0
-
# Phase 2: commit classification → change_pattern
- categories = {}
- cat_json = getattr(meta, "commit_categories_json", None)
- if cat_json:
- with contextlib.suppress(json.JSONDecodeError, TypeError):
- categories = json.loads(cat_json)
- change_pattern = _derive_change_pattern(categories)
+ change_pattern = _derive_change_pattern(_load_commit_categories(meta))
# Phase 2: recent owner & bus factor
- recent_owner = getattr(meta, "recent_owner_name", None)
- recent_owner_pct = getattr(meta, "recent_owner_commit_pct", None)
bus_factor = getattr(meta, "bus_factor", 0) or 0
- contributor_count = getattr(meta, "contributor_count", 0) or 0
-
- # Phase 3: rename tracking & merge commit proxy
- original_path = getattr(meta, "original_path", None)
- merge_commit_count = getattr(meta, "merge_commit_count_90d", 0) or 0
result_data["hotspot_score"] = hotspot_score
result_data["dependents_count"] = dep_count
result_data["co_change_partners"] = co_changes
result_data["primary_owner"] = owner
result_data["owner_pct"] = pct
- result_data["recent_owner"] = recent_owner
- result_data["recent_owner_pct"] = recent_owner_pct
+ result_data["recent_owner"] = getattr(meta, "recent_owner_name", None)
+ result_data["recent_owner_pct"] = getattr(meta, "recent_owner_commit_pct", None)
result_data["bus_factor"] = bus_factor
- result_data["contributor_count"] = contributor_count
+ result_data["contributor_count"] = getattr(meta, "contributor_count", 0) or 0
result_data["trend"] = trend
result_data["risk_type"] = risk_type
result_data["change_pattern"] = change_pattern
result_data["change_magnitude"] = {
- "lines_added_90d": lines_added,
- "lines_deleted_90d": lines_deleted,
- "avg_commit_size": round(avg_size, 1),
+ "lines_added_90d": getattr(meta, "lines_added_90d", 0) or 0,
+ "lines_deleted_90d": getattr(meta, "lines_deleted_90d", 0) or 0,
+ "avg_commit_size": round(getattr(meta, "avg_commit_size", 0.0) or 0.0, 1),
}
result_data["impact_surface"] = impact_surface
+ # Phase 3: rename tracking & merge commit proxy
+ original_path = getattr(meta, "original_path", None)
if original_path:
result_data["original_path"] = original_path
+ merge_commit_count = getattr(meta, "merge_commit_count_90d", 0) or 0
if merge_commit_count > 0:
result_data["merge_commit_count_90d"] = merge_commit_count
@@ -586,6 +587,309 @@ def _trim_blast_lists(
return trimmed_blast
+async def _enrich_cross_repo(results: list[dict], alias: str) -> None:
+ """Annotate per-target results with cross-repo partners, affected repos and
+ contract links (workspace mode only). Mutates *results* in place; no-op when
+ no enricher data is available. Behavior preserved verbatim from inline form.
+ """
+ enricher = _state._cross_repo_enricher
+ if enricher is None or not enricher.has_data or not _is_workspace_mode():
+ return
+ for r in results:
+ target = r["target"]
+ cross_partners = enricher.get_cross_repo_partners(alias, target)
+ affected_repos = enricher.get_affected_repos(alias, target)
+ if cross_partners or affected_repos:
+ r["cross_repo_impact"] = {
+ "cross_repo_consumers": [
+ {"repo": p["repo"], "file": p["file"], "strength": p["strength"]}
+ for p in cross_partners[:5]
+ ],
+ "affected_repos": affected_repos,
+ }
+ r["dependents_count"] = r.get("dependents_count", 0) + len(cross_partners)
+ # Rebuild risk_summary with updated dependents count
+ if "_base_dep_count" in r:
+ r["risk_summary"] = r["risk_summary"].replace(
+ f"{r['_base_dep_count']} dependents",
+ f"{r['dependents_count']} dependents",
+ )
+
+ # Contract links (Phase 4)
+ if not enricher.has_contract_data:
+ continue
+ provider_links = enricher.get_contract_links_as_provider(alias, target)
+ consumer_links = enricher.get_contract_links_as_consumer(alias, target)
+ if not (provider_links or consumer_links):
+ continue
+ impact = r.setdefault("cross_repo_impact", {})
+ if provider_links:
+ impact["contract_consumers"] = [
+ {
+ "consumer_repo": lk["consumer_repo"],
+ "consumer_file": lk["consumer_file"],
+ "contract_id": lk["contract_id"],
+ "type": lk["contract_type"],
+ }
+ for lk in provider_links[:5]
+ ]
+ r["dependents_count"] = r.get("dependents_count", 0) + len(provider_links)
+ if consumer_links:
+ impact["contract_providers"] = [
+ {
+ "provider_repo": lk["provider_repo"],
+ "provider_file": lk["provider_file"],
+ "contract_id": lk["contract_id"],
+ "type": lk["contract_type"],
+ }
+ for lk in consumer_links[:5]
+ ]
+
+
+def _finalize_dep_summaries(results: list[dict]) -> None:
+ """Rebuild risk_summary for any post-enrichment dependents_count change and
+ drop the internal ``_base_dep_count`` key. Mutates *results* in place.
+ """
+ for r in results:
+ base = r.pop("_base_dep_count", None)
+ if base is not None and r.get("dependents_count", base) != base:
+ r["risk_summary"] = r["risk_summary"].replace(
+ f"{base} dependents",
+ f"{r['dependents_count']} dependents",
+ )
+
+
+async def _enrich_health(results: list[dict], ctx: Any, repo_id: str) -> None:
+ """Attach per-file health_score, coverage, and top_biomarkers from the health
+ tables. Conservative: missing data → no field, never invented. Never raises.
+ """
+ try:
+ from repowise.core.persistence.models import HealthFileMetric, HealthFinding
+
+ target_paths = [r["target"] for r in results if r.get("target")]
+ if not target_paths:
+ return
+ async with get_session(ctx.session_factory) as _h_session:
+ m_res = await _h_session.execute(
+ select(HealthFileMetric).where(
+ HealthFileMetric.repository_id == repo_id,
+ HealthFileMetric.file_path.in_(target_paths),
+ )
+ )
+ metric_map = {m.file_path: m for m in m_res.scalars().all()}
+
+ f_res = await _h_session.execute(
+ select(HealthFinding)
+ .where(
+ HealthFinding.repository_id == repo_id,
+ HealthFinding.file_path.in_(target_paths),
+ HealthFinding.status == "open",
+ )
+ .order_by(HealthFinding.health_impact.desc())
+ )
+ top_by_file: dict[str, list[dict]] = {}
+ for f in f_res.scalars().all():
+ lst = top_by_file.setdefault(f.file_path, [])
+ if len(lst) >= 3:
+ continue
+ lst.append(
+ {
+ "biomarker_type": f.biomarker_type,
+ "severity": f.severity,
+ "function_name": f.function_name,
+ "impact": round(f.health_impact, 2),
+ }
+ )
+
+ for r in results:
+ path = r.get("target")
+ m = metric_map.get(path)
+ if m is not None:
+ r["health_score"] = round(m.score, 2)
+ if m.line_coverage_pct is not None:
+ r["coverage_pct"] = round(m.line_coverage_pct, 2)
+ if m.branch_coverage_pct is not None:
+ r["branch_coverage_pct"] = round(m.branch_coverage_pct, 2)
+ if path in top_by_file:
+ r["top_biomarkers"] = top_by_file[path]
+ except Exception:
+ pass
+
+
+async def _governance_directive(ctx: Any, changed_files: list[str]) -> list[dict[str, Any]]:
+ """Governing decisions over *changed_files* that are stale, superseded, or
+ contradicted. Bounded to 5 entries. Never raises (returns what it has).
+ """
+ governance_risk: list[dict[str, Any]] = []
+ try:
+ async with get_session(ctx.session_factory) as _gr_session:
+ _gr_repo = await _get_repo(_gr_session)
+ _gr_repo_id = _gr_repo.id
+ conflict_edges = await list_conflict_edges(_gr_session, _gr_repo_id)
+ conflict_decision_ids: set[str] = set()
+ for ce in conflict_edges:
+ conflict_decision_ids.add(ce.src_decision_id)
+ conflict_decision_ids.add(ce.dst_decision_id)
+ seen_dr_ids: set[str] = set()
+ for cf in changed_files:
+ for dr in await get_governing_decisions(_gr_session, _gr_repo_id, cf):
+ if dr.id in seen_dr_ids:
+ continue
+ seen_dr_ids.add(dr.id)
+ reason = _governance_reason(dr, conflict_decision_ids)
+ if reason is None:
+ continue
+ governance_risk.append(
+ {
+ "file": cf,
+ "decision_id": dr.id,
+ "title": dr.title,
+ "status": dr.status,
+ "reason": reason,
+ }
+ )
+ if len(governance_risk) >= 5:
+ break
+ if len(governance_risk) >= 5:
+ break
+ except Exception:
+ pass
+ return governance_risk
+
+
+def _governance_reason(dr: Any, conflict_decision_ids: set[str]) -> str | None:
+ """Map a governing decision to a directive reason, or None when clean."""
+ staleness = dr.staleness_score or 0.0
+ if dr.status == "active" and staleness >= 0.5:
+ return "stale_governance"
+ if dr.status == "superseded":
+ return "superseded_decision"
+ if dr.id in conflict_decision_ids:
+ return "contradicted_decision"
+ return None
+
+
+def _build_pr_directive(
+ response: dict,
+ pr_blast_radius: dict,
+ changed_files: list[str],
+ exclude_spec: Any,
+ collector: OmissionCollector,
+ governance_risk: list[dict[str, Any]],
+ alias: str,
+) -> None:
+ """Assemble PR-mode output: trim co-change lists + blast radius, then build
+ the directive block. Mutates *response* in place. Behavior preserved.
+ """
+ # PR mode — drop global_hotspots (irrelevant to a specific diff), trim
+ # per-target co-change lists, and synthesize a tight directive the
+ # agent can act on without parsing the whole blast-radius dossier.
+ # Everything trimmed below is persisted via the collector so the
+ # response carries an expandable [repowise#<ref>] marker for it.
+ for r in response["targets"].values():
+ partners = r.get("co_change_partners") or []
+ if len(partners) > 3:
+ r["co_change_partners"] = partners[:3]
+ collector.add(
+ f"{r.get('target')} :: co_change_partners beyond 3",
+ partners[3:],
+ )
+
+ trimmed_blast = _trim_blast_lists(pr_blast_radius, exclude_spec, collector)
+ response["pr_blast_radius"] = trimmed_blast
+
+ # Directive: 3 short lists the agent can read in one glance. Each
+ # entry is a file path (string), never a dossier. Designed to answer
+ # "what should I do about this PR" in three lines.
+
+ will_break = filter_path_list(
+ [p for p in (_as_path(e) for e in trimmed_blast.get("transitive_affected", [])) if p],
+ exclude_spec,
+ )[:5]
+ missing_cochanges = filter_path_list(
+ [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 pr_blast_radius.get("test_gaps", []))
+ if p and p in changed_set
+ ],
+ exclude_spec,
+ )[:3]
+
+ gov_count = len(governance_risk)
+ gov_suffix = f" {gov_count} governance risk(s) detected." if gov_count > 0 else ""
+
+ # Cross-repo directive (workspace mode only). Resolve the changed repo to
+ # its system-graph nodes and walk reachability to find downstream
+ # services in OTHER repos — split structural (will break) from behavioral
+ # (co-change only). Repo-scoped: it answers "can this PR's repo break
+ # something across a repo boundary?" using the same reachability the map
+ # and get_blast_radius use.
+ will_break_consumers, missing_cross_repo_cochanges = _cross_repo_directive(alias)
+ xr_suffix = ""
+ if will_break_consumers or missing_cross_repo_cochanges:
+ xr_suffix = (
+ f" Cross-repo: {len(will_break_consumers)} consumer service(s) may break, "
+ f"{len(missing_cross_repo_cochanges)} cross-repo co-changer(s) missing."
+ )
+
+ # Breaking-change guard — incompatible provider changes (removed route /
+ # field, type change, ...) in this repo and the consumers they endanger.
+ # Schema-level truth, distinct from the topology-level will_break_consumers.
+ breaking_changes = _breaking_change_directive(alias)
+ bc_suffix = ""
+ if breaking_changes:
+ bc_consumers = sum(len(b["impacted_consumers"]) for b in breaking_changes)
+ bc_suffix = (
+ f" Breaking changes: {len(breaking_changes)} provider contract(s) changed "
+ f"incompatibly, endangering {bc_consumers} consumer(s)."
+ )
+
+ # Architecture conformance — declared dependency-rule violations and
+ # dependency cycles this repo participates in. Governance-level truth,
+ # distinct from the topology / schema directives above.
+ conformance_violations, dependency_cycles = _conformance_directive(alias)
+ cf_suffix = ""
+ if conformance_violations or dependency_cycles:
+ cf_suffix = (
+ f" Conformance: {len(conformance_violations)} architecture rule "
+ f"violation(s), {len(dependency_cycles)} dependency cycle(s) involving "
+ f"this repo."
+ )
+
+ response["directive"] = {
+ "will_break": will_break,
+ "missing_cochanges": missing_cochanges,
+ "missing_tests": missing_tests,
+ "will_break_consumers": will_break_consumers,
+ "missing_cross_repo_cochanges": missing_cross_repo_cochanges,
+ "breaking_changes": breaking_changes,
+ "conformance_violations": conformance_violations,
+ "dependency_cycles": dependency_cycles,
+ "governance_risk": governance_risk,
+ "overall_risk_score": trimmed_blast.get("overall_risk_score"),
+ "summary": (
+ f"PR touches {len(changed_files)} file(s). "
+ f"~{len(will_break)} downstream file(s) likely affected, "
+ f"{len(missing_cochanges)} historical co-changer(s) missing, "
+ f"{len(missing_tests)} file(s) without tests."
+ f"{gov_suffix}{xr_suffix}{bc_suffix}{cf_suffix}"
+ ),
+ }
+
+
@mcp.tool()
async def get_risk(
targets: list[str],
@@ -691,119 +995,16 @@ async def get_risk(
pr_blast_radius = await analyzer.analyze_files(changed_files)
# Cross-repo blast radius enrichment (Phase 3 + 4)
- enricher = _state._cross_repo_enricher
- if enricher is not None and enricher.has_data and _is_workspace_mode():
- for r in results:
- target = r["target"]
- cross_partners = enricher.get_cross_repo_partners(ctx.alias, target)
- affected_repos = enricher.get_affected_repos(ctx.alias, target)
- if cross_partners or affected_repos:
- r["cross_repo_impact"] = {
- "cross_repo_consumers": [
- {"repo": p["repo"], "file": p["file"], "strength": p["strength"]}
- for p in cross_partners[:5]
- ],
- "affected_repos": affected_repos,
- }
- r["dependents_count"] = r.get("dependents_count", 0) + len(cross_partners)
- # Rebuild risk_summary with updated dependents count
- if "_base_dep_count" in r:
- r["risk_summary"] = r["risk_summary"].replace(
- f"{r['_base_dep_count']} dependents",
- f"{r['dependents_count']} dependents",
- )
-
- # Contract links (Phase 4)
- if enricher.has_contract_data:
- provider_links = enricher.get_contract_links_as_provider(ctx.alias, target)
- consumer_links = enricher.get_contract_links_as_consumer(ctx.alias, target)
- if provider_links or consumer_links:
- impact = r.setdefault("cross_repo_impact", {})
- if provider_links:
- impact["contract_consumers"] = [
- {
- "consumer_repo": lk["consumer_repo"],
- "consumer_file": lk["consumer_file"],
- "contract_id": lk["contract_id"],
- "type": lk["contract_type"],
- }
- for lk in provider_links[:5]
- ]
- r["dependents_count"] = r.get("dependents_count", 0) + len(provider_links)
- if consumer_links:
- impact["contract_providers"] = [
- {
- "provider_repo": lk["provider_repo"],
- "provider_file": lk["provider_file"],
- "contract_id": lk["contract_id"],
- "type": lk["contract_type"],
- }
- for lk in consumer_links[:5]
- ]
+ await _enrich_cross_repo(results, ctx.alias)
# Final risk_summary rebuild for any remaining dependents_count updates
# (e.g. contract provider links) and cleanup of internal keys.
- for r in results:
- base = r.pop("_base_dep_count", None)
- if base is not None and r.get("dependents_count", base) != base:
- r["risk_summary"] = r["risk_summary"].replace(
- f"{base} dependents",
- f"{r['dependents_count']} dependents",
- )
+ _finalize_dep_summaries(results)
# ---- Code-health enrichment --------------------------------------------
# Attach per-file health_score + top_biomarkers (up to 3) drawn from the
# health tables. Conservative: missing data → no field, never invented.
- try:
- from repowise.core.persistence.models import HealthFileMetric, HealthFinding
-
- target_paths = [r["target"] for r in results if r.get("target")]
- if target_paths:
- async with get_session(ctx.session_factory) as _h_session:
- m_res = await _h_session.execute(
- select(HealthFileMetric).where(
- HealthFileMetric.repository_id == repo_id,
- HealthFileMetric.file_path.in_(target_paths),
- )
- )
- metric_map = {m.file_path: m for m in m_res.scalars().all()}
-
- f_res = await _h_session.execute(
- select(HealthFinding)
- .where(
- HealthFinding.repository_id == repo_id,
- HealthFinding.file_path.in_(target_paths),
- HealthFinding.status == "open",
- )
- .order_by(HealthFinding.health_impact.desc())
- )
- top_by_file: dict[str, list[dict]] = {}
- for f in f_res.scalars().all():
- lst = top_by_file.setdefault(f.file_path, [])
- if len(lst) >= 3:
- continue
- lst.append(
- {
- "biomarker_type": f.biomarker_type,
- "severity": f.severity,
- "function_name": f.function_name,
- "impact": round(f.health_impact, 2),
- }
- )
-
- for r in results:
- path = r.get("target")
- m = metric_map.get(path)
- if m is not None:
- r["health_score"] = round(m.score, 2)
- if m.line_coverage_pct is not None:
- r["coverage_pct"] = round(m.line_coverage_pct, 2)
- if m.branch_coverage_pct is not None:
- r["branch_coverage_pct"] = round(m.branch_coverage_pct, 2)
- if path in top_by_file:
- r["top_biomarkers"] = top_by_file[path]
- except Exception:
- pass
+ await _enrich_health(results, ctx, repo_id)
response: dict = {
"targets": {r["target"]: r for r in results},
@@ -811,158 +1012,17 @@ async def get_risk(
collector = OmissionCollector("get_risk", repo_root=ctx.path)
if pr_blast_radius is not None:
- # PR mode — drop global_hotspots (irrelevant to a specific diff), trim
- # per-target co-change lists, and synthesize a tight directive the
- # agent can act on without parsing the whole blast-radius dossier.
- # Everything trimmed below is persisted via the collector so the
- # response carries an expandable [repowise#<ref>] marker for it.
- for r in response["targets"].values():
- partners = r.get("co_change_partners") or []
- if len(partners) > 3:
- r["co_change_partners"] = partners[:3]
- collector.add(
- f"{r.get('target')} :: co_change_partners beyond 3",
- partners[3:],
- )
-
- trimmed_blast = _trim_blast_lists(pr_blast_radius, exclude_spec, collector)
- response["pr_blast_radius"] = trimmed_blast
-
- # Directive: 3 short lists the agent can read in one glance. Each
- # entry is a file path (string), never a dossier. Designed to answer
- # "what should I do about this PR" in three lines.
-
- will_break = filter_path_list(
- [p for p in (_as_path(e) for e in trimmed_blast.get("transitive_affected", [])) if p],
- exclude_spec,
- )[:5]
- missing_cochanges = filter_path_list(
- [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 pr_blast_radius.get("test_gaps", []))
- if p and p in changed_set
- ],
- exclude_spec,
- )[:3]
-
# Governance risk — bounded query over changed_files (small set).
- governance_risk: list[dict[str, Any]] = []
- try:
- async with get_session(ctx.session_factory) as _gr_session:
- _gr_repo = await _get_repo(_gr_session)
- _gr_repo_id = _gr_repo.id
- conflict_edges = await list_conflict_edges(_gr_session, _gr_repo_id)
- conflict_decision_ids: set[str] = set()
- for ce in conflict_edges:
- conflict_decision_ids.add(ce.src_decision_id)
- conflict_decision_ids.add(ce.dst_decision_id)
- seen_dr_ids: set[str] = set()
- for cf in changed_files:
- for dr in await get_governing_decisions(_gr_session, _gr_repo_id, cf):
- if dr.id in seen_dr_ids:
- continue
- seen_dr_ids.add(dr.id)
- staleness = dr.staleness_score or 0.0
- is_stale = dr.status == "active" and staleness >= 0.5
- is_superseded = dr.status == "superseded"
- is_conflicted = dr.id in conflict_decision_ids
- if is_stale:
- reason = "stale_governance"
- elif is_superseded:
- reason = "superseded_decision"
- elif is_conflicted:
- reason = "contradicted_decision"
- else:
- continue
- governance_risk.append(
- {
- "file": cf,
- "decision_id": dr.id,
- "title": dr.title,
- "status": dr.status,
- "reason": reason,
- }
- )
- if len(governance_risk) >= 5:
- break
- if len(governance_risk) >= 5:
- break
- except Exception:
- pass
-
- gov_count = len(governance_risk)
- gov_suffix = f" {gov_count} governance risk(s) detected." if gov_count > 0 else ""
-
- # Cross-repo directive (workspace mode only). Resolve the changed repo to
- # its system-graph nodes and walk reachability to find downstream
- # services in OTHER repos — split structural (will break) from behavioral
- # (co-change only). Repo-scoped: it answers "can this PR's repo break
- # something across a repo boundary?" using the same reachability the map
- # and get_blast_radius use.
- will_break_consumers, missing_cross_repo_cochanges = _cross_repo_directive(ctx.alias)
- xr_suffix = ""
- if will_break_consumers or missing_cross_repo_cochanges:
- xr_suffix = (
- f" Cross-repo: {len(will_break_consumers)} consumer service(s) may break, "
- f"{len(missing_cross_repo_cochanges)} cross-repo co-changer(s) missing."
- )
-
- # Breaking-change guard — incompatible provider changes (removed route /
- # field, type change, ...) in this repo and the consumers they endanger.
- # Schema-level truth, distinct from the topology-level will_break_consumers.
- breaking_changes = _breaking_change_directive(ctx.alias)
- bc_suffix = ""
- if breaking_changes:
- bc_consumers = sum(len(b["impacted_consumers"]) for b in breaking_changes)
- bc_suffix = (
- f" Breaking changes: {len(breaking_changes)} provider contract(s) changed "
- f"incompatibly, endangering {bc_consumers} consumer(s)."
- )
-
- # Architecture conformance — declared dependency-rule violations and
- # dependency cycles this repo participates in. Governance-level truth,
- # distinct from the topology / schema directives above.
- conformance_violations, dependency_cycles = _conformance_directive(ctx.alias)
- cf_suffix = ""
- if conformance_violations or dependency_cycles:
- cf_suffix = (
- f" Conformance: {len(conformance_violations)} architecture rule "
- f"violation(s), {len(dependency_cycles)} dependency cycle(s) involving "
- f"this repo."
- )
-
- response["directive"] = {
- "will_break": will_break,
- "missing_cochanges": missing_cochanges,
- "missing_tests": missing_tests,
- "will_break_consumers": will_break_consumers,
- "missing_cross_repo_cochanges": missing_cross_repo_cochanges,
- "breaking_changes": breaking_changes,
- "conformance_violations": conformance_violations,
- "dependency_cycles": dependency_cycles,
- "governance_risk": governance_risk,
- "overall_risk_score": trimmed_blast.get("overall_risk_score"),
- "summary": (
- f"PR touches {len(changed_files)} file(s). "
- f"~{len(will_break)} downstream file(s) likely affected, "
- f"{len(missing_cochanges)} historical co-changer(s) missing, "
- f"{len(missing_tests)} file(s) without tests."
- f"{gov_suffix}{xr_suffix}{bc_suffix}{cf_suffix}"
- ),
- }
+ governance_risk = await _governance_directive(ctx, changed_files)
+ _build_pr_directive(
+ response,
+ pr_blast_radius,
+ changed_files,
+ exclude_spec,
+ collector,
+ governance_risk,
+ ctx.alias,
+ )
else:
# Standard per-file risk request (no diff) — keep global hotspots as
# ambient awareness. Cheap (≤5 entries) and useful for orientation.
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 f4d1262a0..04f4f5305 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_search.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py
@@ -219,27 +219,88 @@ def _classify_hit_kind(target_path: str, page_type: str) -> str:
return "implementation"
-async def _search_single_repo(
- ctx, query: str, limit: int, page_type: str | None, kind: str | None = None
-) -> tuple[list[dict], str]:
- """Run search against a single repo context.
+def _filter_by_kind(output: list[dict], kind: str | None) -> list[dict]:
+ """Keep only hits classified as ``kind`` (no-op when ``kind`` is falsy).
- Returns ``(results, method)`` where ``method`` is ``"embedding"`` or
- ``"bm25"`` so the caller can surface which retrieval backend produced
- the list — embedding misses fall through to FTS silently in the existing
- code, and the agent has no way to distinguish a strong embedding hit
- from a fallback BM25 hit otherwise.
+ Runs on the over-fetched list BEFORE the limit cut so the caller still
+ gets up to ``limit`` results of the requested kind.
+ """
+ if not kind:
+ return output
+ return [
+ item
+ for item in output
+ if _classify_hit_kind(item.get("target_path", ""), item.get("page_type", "")) == kind
+ ]
- The ``kind`` filter runs here, on the over-fetched list and BEFORE the
- limit cut — filtering after per-repo truncation returned fewer than
- ``limit`` results (frequently zero) in the federated path.
+
+async def _load_page_info(
+ session, output: list[dict], *, with_git: bool = False
+) -> tuple[dict, set, dict]:
+ """Batch-load target paths, tombstones, and optionally git metadata.
+
+ Returns ``(page_info, tombstoned, git_map)`` where ``page_info`` maps
+ page_id -> target_path, ``tombstoned`` is the set of tombstoned page_ids,
+ and ``git_map`` maps file_path -> GitMetadata (empty unless ``with_git``).
"""
- # Wait for vector store readiness
+ page_ids = [item["page_id"] for item in output]
+ res = await session.execute(
+ select(Page.id, Page.target_path, Page.freshness_status).where(Page.id.in_(page_ids))
+ )
+ rows = res.all()
+ page_info = {row[0]: row[1] for row in rows}
+ tombstoned = {row[0] for row in rows if row[2] == "tombstone"}
+
+ git_map: dict[str, GitMetadata] = {}
+ if with_git:
+ target_paths = [tp for tp in page_info.values() if tp]
+ if target_paths:
+ git_res = await session.execute(
+ select(GitMetadata).where(GitMetadata.file_path.in_(target_paths))
+ )
+ git_map = {g.file_path: g for g in git_res.scalars().all()}
+ return page_info, tombstoned, git_map
+
+
+def _apply_freshness_boost(item: dict, gm: GitMetadata | None) -> None:
+ """Boost an item's relevance for recently-active files (in place)."""
+ if not gm or not item.get("relevance_score"):
+ return
+ c30 = gm.commit_count_30d or 0
+ c90 = gm.commit_count_90d or 0
+ if c30 > 0:
+ recency = 1.0
+ elif c90 > 0:
+ recency = 0.5
+ else:
+ recency = 0.0
+ item["relevance_score"] = round(item["relevance_score"] * (1 + 0.2 * recency), 4)
+
+
+def _assign_confidence(output: list[dict], score_key: str, target_key: str) -> None:
+ """Derive ``target_key`` for each item from its ``score_key`` position (in place)."""
+ if not output:
+ return
+ max_score = max((item.get(score_key) or 0) for item in output)
+ for item in output:
+ raw = item.get(score_key) or 0
+ item[target_key] = round(raw / max_score, 2) if max_score > 0 else 0.0
+
+
+async def _wait_for_vector_store(ctx) -> None:
+ """Block (bounded) until the vector store signals readiness, if it tracks it."""
if ctx.vector_store_ready is not None:
with contextlib.suppress(TimeoutError):
await asyncio.wait_for(ctx.vector_store_ready.wait(), timeout=30.0)
- fetch_limit = _fetch_limit_for(limit, kind)
+
+async def _retrieve_with_method(ctx, query: str, fetch_limit: int) -> tuple[list, str]:
+ """Try semantic search, fall back to FTS.
+
+ Returns ``(results, method)`` where ``method`` is ``"embedding"`` or
+ ``"bm25"`` so callers can surface which retrieval backend produced the
+ list — embedding misses fall through to FTS silently otherwise.
+ """
results = []
method = "embedding"
with contextlib.suppress(TimeoutError, Exception):
@@ -251,22 +312,56 @@ async def _search_single_repo(
method = "bm25"
with contextlib.suppress(Exception):
results = await ctx.fts.search(query, limit=fetch_limit)
+ return results, method
+
+def _build_output(
+ results: list, page_type: str | None, search_method: str | None = None
+) -> list[dict]:
+ """Map raw search hits to result dicts, dropping off-type and low-score hits.
+
+ When ``search_method`` is given it is attached to each item; the federated
+ path attaches it later per-repo so it passes ``None``.
+ """
output = []
for r in results:
if page_type and r.page_type != page_type:
continue
if r.score < _MIN_RELEVANCE_SCORE:
continue
- output.append(
- {
- "page_id": r.page_id,
- "title": r.title,
- "page_type": r.page_type,
- "snippet": r.snippet,
- "relevance_score": r.score,
- }
- )
+ item = {
+ "page_id": r.page_id,
+ "title": r.title,
+ "page_type": r.page_type,
+ "snippet": r.snippet,
+ "relevance_score": r.score,
+ }
+ if search_method is not None:
+ item["search_method"] = search_method
+ output.append(item)
+ return output
+
+
+async def _search_single_repo(
+ ctx, query: str, limit: int, page_type: str | None, kind: str | None = None
+) -> tuple[list[dict], str]:
+ """Run search against a single repo context.
+
+ Returns ``(results, method)`` where ``method`` is ``"embedding"`` or
+ ``"bm25"`` so the caller can surface which retrieval backend produced
+ the list — embedding misses fall through to FTS silently in the existing
+ code, and the agent has no way to distinguish a strong embedding hit
+ from a fallback BM25 hit otherwise.
+
+ The ``kind`` filter runs here, on the over-fetched list and BEFORE the
+ limit cut — filtering after per-repo truncation returned fewer than
+ ``limit`` results (frequently zero) in the federated path.
+ """
+ await _wait_for_vector_store(ctx)
+
+ fetch_limit = _fetch_limit_for(limit, kind)
+ results, method = await _retrieve_with_method(ctx, query, fetch_limit)
+ output = _build_output(results, page_type)
_downweight_decisions(output, query)
output = await _rescue_all_decision_window(ctx, output, query, fetch_limit)
@@ -276,28 +371,14 @@ async def _search_single_repo(
# honours each repo's own exclude_patterns) before aggregation. Runs on
# the over-fetched list so the kind filter below has real headroom.
if output:
- page_ids = [item["page_id"] for item in output]
async with get_session(ctx.session_factory) as session:
- res = await session.execute(
- select(Page.id, Page.target_path, Page.freshness_status).where(
- Page.id.in_(page_ids)
- )
- )
- rows = res.all()
- page_info = {row[0]: row[1] for row in rows}
- tombstoned = {row[0] for row in rows if row[2] == "tombstone"}
+ page_info, tombstoned, _ = await _load_page_info(session, output)
output = [item for item in output if item["page_id"] not in tombstoned]
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))
- if kind:
- output = [
- item
- for item in output
- if _classify_hit_kind(item.get("target_path", ""), item.get("page_type", "")) == kind
- ]
-
+ output = _filter_by_kind(output, kind)
return output[:limit], method
@@ -321,15 +402,29 @@ async def _federated_search(
output = all_results[:limit]
# Derive confidence from RRF position
- if output:
- max_rrf = max(item.get("rrf_score", 0) for item in output)
- for item in output:
- raw = item.get("rrf_score", 0)
- item["confidence_score"] = round(raw / max_rrf, 2) if max_rrf > 0 else 0.0
+ _assign_confidence(output, "rrf_score", "confidence_score")
return {"results": output, "_meta": _build_meta()}
+def _grep_hint_for(query: str) -> str | None:
+ """Build a Grep nudge for identifier-shaped queries, else ``None``."""
+ if _looks_like_exact_token(query):
+ return (
+ f"Query {query!r} looks like an exact identifier. Grep will find "
+ "literal usages faster and without thematic drift. This tool ran "
+ "the search anyway — verify before relying on the results."
+ )
+ if idents := _embedded_identifiers(query):
+ shown = ", ".join(repr(t) for t in idents[:3])
+ return (
+ f"Query names identifier(s) {shown} — for their exact "
+ "definition/usages, Grep is faster and never drifts "
+ "thematically. Semantic results below are concept-level."
+ )
+ return None
+
+
@mcp.tool()
async def search_codebase(
query: str,
@@ -353,20 +448,7 @@ async def search_codebase(
kind: implementation | test | config | doc.
repo: alias, or "all" for workspace-wide.
"""
- grep_hint: str | None = None
- if _looks_like_exact_token(query):
- grep_hint = (
- f"Query {query!r} looks like an exact identifier. Grep will find "
- "literal usages faster and without thematic drift. This tool ran "
- "the search anyway — verify before relying on the results."
- )
- elif idents := _embedded_identifiers(query):
- shown = ", ".join(repr(t) for t in idents[:3])
- grep_hint = (
- f"Query names identifier(s) {shown} — for their exact "
- "definition/usages, Grep is faster and never drifts "
- "thematically. Semantic results below are concept-level."
- )
+ grep_hint = _grep_hint_for(query)
if repo == "all":
# kind is filtered per-repo inside _search_single_repo, before each
@@ -382,10 +464,7 @@ async def search_codebase(
# Validate repo exists in DB
repository = await _get_repo(session)
- # Wait for vector store readiness
- if ctx.vector_store_ready is not None:
- with contextlib.suppress(TimeoutError):
- await asyncio.wait_for(ctx.vector_store_ready.wait(), timeout=30.0)
+ await _wait_for_vector_store(ctx)
# Try semantic search, fall back to FTS. Track which backend supplied the
# hits so the response can surface it per-result — silent fallback hides
@@ -393,34 +472,8 @@ async def search_codebase(
# Always over-fetch (see _fetch_limit_for): post-filters trim hits, and
# decision down-weighting needs file pages inside the window to promote.
fetch_limit = _fetch_limit_for(limit, kind)
- results = []
- search_method = "embedding"
- with contextlib.suppress(TimeoutError, Exception):
- results = await asyncio.wait_for(
- ctx.vector_store.search(query, limit=fetch_limit),
- timeout=8.0,
- )
- if not results:
- search_method = "bm25"
- with contextlib.suppress(Exception):
- results = await ctx.fts.search(query, limit=fetch_limit)
-
- output = []
- for r in results:
- if page_type and r.page_type != page_type:
- continue
- if r.score < _MIN_RELEVANCE_SCORE:
- continue
- output.append(
- {
- "page_id": r.page_id,
- "title": r.title,
- "page_type": r.page_type,
- "snippet": r.snippet,
- "relevance_score": r.score,
- "search_method": search_method,
- }
- )
+ results, search_method = await _retrieve_with_method(ctx, query, fetch_limit)
+ output = _build_output(results, page_type, search_method)
_downweight_decisions(output, query)
rescued = await _rescue_all_decision_window(ctx, output, query, fetch_limit)
@@ -433,28 +486,10 @@ async def search_codebase(
# 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:
- res = await session.execute(
- select(Page.id, Page.target_path, Page.freshness_status).where(
- Page.id.in_(page_ids)
- )
- )
- rows = res.all()
- page_info = {row[0]: row[1] for row in rows}
- tombstoned = {row[0] for row in rows if row[2] == "tombstone"}
- # Tombstoned pages document deleted/renamed files — never results.
- output = [item for item in output if item["page_id"] not in tombstoned]
-
- # 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:
- git_res = await session.execute(
- select(GitMetadata).where(GitMetadata.file_path.in_(target_paths))
- )
- git_map = {g.file_path: g for g in git_res.scalars().all()}
+ page_info, tombstoned, git_map = await _load_page_info(session, output, with_git=True)
+ # Tombstoned pages document deleted/renamed files — never results.
+ output = [item for item in output if item["page_id"] not in tombstoned]
# Attach target_path to each item so the kind filter (path-prefix
# heuristic) and downstream get_context callers can act on it.
@@ -467,37 +502,16 @@ async def search_codebase(
# Freshness boost: recently-active files rank higher
target_path = page_info.get(item["page_id"])
gm = git_map.get(target_path) if target_path else None
- if gm and item.get("relevance_score"):
- c30 = gm.commit_count_30d or 0
- c90 = gm.commit_count_90d or 0
- if c30 > 0:
- recency = 1.0
- elif c90 > 0:
- recency = 0.5
- else:
- recency = 0.0
- item["relevance_score"] = round(item["relevance_score"] * (1 + 0.2 * recency), 4)
+ _apply_freshness_boost(item, gm)
# Re-sort by boosted relevance, decisions hard-demoted on non-why queries
_sort_demoting_decisions(output, query)
- # 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 = _filter_by_kind(output, 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)
- for item in output:
- raw = item.get("relevance_score") or 0
- item["confidence_score"] = round(raw / max_score, 2) if max_score > 0 else 0.0
+ _assign_confidence(output, "relevance_score", "confidence_score")
response: dict = {"results": output, "_meta": _build_meta(repository=repository)}
if grep_hint:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.py
index 7dc9bd49e..6b4b74d01 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_why.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py
@@ -55,92 +55,26 @@ async def get_why(
if repo == "all":
if not query:
return _unsupported_repo_all("get_why (health dashboard)")
-
- contexts = await _resolve_all_contexts()
- merged: list[dict] = []
- for ctx in contexts:
- async with get_session(ctx.session_factory) as session:
- repository = await _get_repo(session)
- res = await session.execute(
- select(DecisionRecord).where(
- DecisionRecord.repository_id == repository.id,
- )
- )
- for d in res.scalars().all():
- text = f"{d.title} {d.decision} {d.rationale} {d.context}".lower()
- if any(w in text for w in query.lower().split()):
- merged.append(
- {
- "repo": ctx.alias,
- "id": d.id,
- "title": d.title,
- "status": d.status,
- "decision": d.decision,
- "rationale": d.rationale,
- "source": d.source,
- "confidence": d.confidence,
- }
- )
- return {
- "mode": "search",
- "query": query,
- "workspace": True,
- "decisions": merged[:15],
- "_meta": _build_meta(),
- }
+ return await _why_workspace_search(query)
# --- Mode 1: No query → health dashboard ---
if not query:
- from repowise.core.persistence.crud import get_decision_health_summary
-
- ctx = await _resolve_repo_context(repo)
- async with get_session(ctx.session_factory) as session:
- repository = await _get_repo(session)
- health = await get_decision_health_summary(session, repository.id)
-
- stale = health["stale_decisions"]
- proposed = health["proposed_awaiting_review"]
- ungoverned = health["ungoverned_hotspots"]
-
- return {
- "mode": "health",
- "summary": (
- f"{health['summary'].get('active', 0)} active · "
- f"{health['summary'].get('stale', 0)} stale · "
- f"{len(proposed)} proposed · "
- f"{len(ungoverned)} ungoverned hotspots"
- ),
- "counts": health["summary"],
- "stale_decisions": [
- {
- "id": d.id,
- "title": d.title,
- "staleness_score": d.staleness_score,
- "affected_files": filter_path_list(
- json.loads(d.affected_files_json), _get_exclude_spec(ctx.path)
- )[:5],
- }
- for d in stale[:10]
- ],
- "proposed_awaiting_review": [
- {
- "id": d.id,
- "title": d.title,
- "source": d.source,
- "confidence": d.confidence,
- }
- for d in proposed[:10]
- ],
- "ungoverned_hotspots": ungoverned[:15],
- "conflicts": health.get("conflicts", [])[:10],
- "_meta": _build_meta(repository=repository),
- }
+ return await _why_health_dashboard(repo)
# --- Mode 2: Path → decisions, origin story, alignment ---
if _is_path(query):
- ctx = await _resolve_repo_context(repo)
- if is_excluded(query, _get_exclude_spec(ctx.path)):
- return {"query": query, "error": f"'{query}' is excluded by exclude_patterns."}
+ return await _why_path(query, repo)
+
+ # --- Mode 3: Natural language → target-aware search ---
+ return await _why_search(query, targets, repo)
+
+
+async def _why_workspace_search(query: str) -> dict:
+ """repo="all": keyword-search decisions across every repo in the workspace."""
+ contexts = await _resolve_all_contexts()
+ merged: list[dict] = []
+ query_words = query.lower().split()
+ for ctx in contexts:
async with get_session(ctx.session_factory) as session:
repository = await _get_repo(session)
res = await session.execute(
@@ -148,154 +82,242 @@ async def get_why(
DecisionRecord.repository_id == repository.id,
)
)
- all_decisions = res.scalars().all()
-
- # Load git metadata for origin story
- git_res = await session.execute(
- select(GitMetadata).where(
- GitMetadata.repository_id == repository.id,
- GitMetadata.file_path == query,
- )
- )
- git_meta = git_res.scalar_one_or_none()
-
- # Pre-load all git metadata for cross-file search (used by fallback)
- all_git_res = await session.execute(
- select(GitMetadata).where(
- GitMetadata.repository_id == repository.id,
- )
- )
- all_git_meta = all_git_res.scalars().all()
-
- from repowise.core.persistence.decision_graph import build_lineage_chain
-
- governing = []
- for d in all_decisions:
- affected_files = json.loads(d.affected_files_json)
- affected_modules = json.loads(d.affected_modules_json)
- if query in affected_files or query in affected_modules:
- # Walk supersedes/refines back to roots so the answer is a
- # lineage chain (sessions → JWT → OAuth2), not a flat list.
- lineage = await build_lineage_chain(session, d.id)
- governing.append(
+ for d in res.scalars().all():
+ text = f"{d.title} {d.decision} {d.rationale} {d.context}".lower()
+ if any(w in text for w in query_words):
+ merged.append(
{
+ "repo": ctx.alias,
"id": d.id,
"title": d.title,
"status": d.status,
- "context": d.context,
"decision": d.decision,
"rationale": d.rationale,
- "alternatives": json.loads(d.alternatives_json),
- "consequences": json.loads(d.consequences_json),
- "affected_files": affected_files,
"source": d.source,
"confidence": d.confidence,
- "staleness_score": d.staleness_score,
- "lineage": lineage if len(lineage) > 1 else [],
}
)
+ return {
+ "mode": "search",
+ "query": query,
+ "workspace": True,
+ "decisions": merged[:15],
+ "_meta": _build_meta(),
+ }
- result_data: dict[str, Any] = {
- "mode": "path",
- "path": query,
- "decisions": governing,
- "origin_story": _build_origin_story(query, git_meta, governing),
- "alignment": _compute_alignment(query, governing, all_decisions),
- }
- # --- Fallback: git archaeology when no decisions found ---
- if not governing:
- result_data["git_archaeology"] = await _git_archaeology_fallback(
- query,
- git_meta,
- all_git_meta,
- repository,
- )
+async def _why_health_dashboard(repo: str | None) -> dict:
+ """Mode 1: no query — return the decision health dashboard."""
+ from repowise.core.persistence.crud import get_decision_health_summary
- result_data["_meta"] = _build_meta(repository=repository)
- return result_data
+ ctx = await _resolve_repo_context(repo)
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
+ health = await get_decision_health_summary(session, repository.id)
- # --- Mode 3: Natural language → target-aware search ---
- from repowise.core.persistence.crud import list_decisions as _list_decisions
+ stale = health["stale_decisions"]
+ proposed = health["proposed_awaiting_review"]
+ ungoverned = health["ungoverned_hotspots"]
+
+ return {
+ "mode": "health",
+ "summary": (
+ f"{health['summary'].get('active', 0)} active · "
+ f"{health['summary'].get('stale', 0)} stale · "
+ f"{len(proposed)} proposed · "
+ f"{len(ungoverned)} ungoverned hotspots"
+ ),
+ "counts": health["summary"],
+ "stale_decisions": [
+ {
+ "id": d.id,
+ "title": d.title,
+ "staleness_score": d.staleness_score,
+ "affected_files": filter_path_list(
+ json.loads(d.affected_files_json), _get_exclude_spec(ctx.path)
+ )[:5],
+ }
+ for d in stale[:10]
+ ],
+ "proposed_awaiting_review": [
+ {
+ "id": d.id,
+ "title": d.title,
+ "source": d.source,
+ "confidence": d.confidence,
+ }
+ for d in proposed[:10]
+ ],
+ "ungoverned_hotspots": ungoverned[:15],
+ "conflicts": health.get("conflicts", [])[:10],
+ "_meta": _build_meta(repository=repository),
+ }
+
+
+def _governing_decision_entry(d: Any, affected_files: list, lineage: list[dict]) -> dict:
+ """Serialize a decision that governs a path, including its lineage chain."""
+ return {
+ "id": d.id,
+ "title": d.title,
+ "status": d.status,
+ "context": d.context,
+ "decision": d.decision,
+ "rationale": d.rationale,
+ "alternatives": json.loads(d.alternatives_json),
+ "consequences": json.loads(d.consequences_json),
+ "affected_files": affected_files,
+ "source": d.source,
+ "confidence": d.confidence,
+ "staleness_score": d.staleness_score,
+ "lineage": lineage if len(lineage) > 1 else [],
+ }
+
+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)
+ if is_excluded(query, _get_exclude_spec(ctx.path)):
+ 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)
- all_decisions = await _list_decisions(
- session, repository.id, include_proposed=True, limit=200
+ res = await session.execute(
+ select(DecisionRecord).where(
+ DecisionRecord.repository_id == repository.id,
+ )
)
+ all_decisions = res.scalars().all()
- # Load git metadata for targets (for origin context in results)
- target_git: dict[str, Any] = {}
- if targets:
- for t in targets:
- git_res = await session.execute(
- select(GitMetadata).where(
- GitMetadata.repository_id == repository.id,
- GitMetadata.file_path == t,
- )
- )
- meta = git_res.scalar_one_or_none()
- if meta:
- target_git[t] = meta
+ # Load git metadata for origin story
+ git_res = await session.execute(
+ select(GitMetadata).where(
+ GitMetadata.repository_id == repository.id,
+ GitMetadata.file_path == query,
+ )
+ )
+ git_meta = git_res.scalar_one_or_none()
- # Build target file set for boosting
- target_set = set(targets) if targets else set()
+ # Pre-load all git metadata for cross-file search (used by fallback)
+ all_git_res = await session.execute(
+ select(GitMetadata).where(
+ GitMetadata.repository_id == repository.id,
+ )
+ )
+ all_git_meta = all_git_res.scalars().all()
+
+ from repowise.core.persistence.decision_graph import build_lineage_chain
+
+ governing = []
+ for d in all_decisions:
+ affected_files = json.loads(d.affected_files_json)
+ affected_modules = json.loads(d.affected_modules_json)
+ if query not in affected_files and query not in affected_modules:
+ continue
+ # Walk supersedes/refines back to roots so the answer is a
+ # lineage chain (sessions → JWT → OAuth2), not a flat list.
+ lineage = await build_lineage_chain(session, d.id)
+ governing.append(_governing_decision_entry(d, affected_files, lineage))
+
+ result_data: dict[str, Any] = {
+ "mode": "path",
+ "path": query,
+ "decisions": governing,
+ "origin_story": _build_origin_story(query, git_meta, governing),
+ "alignment": _compute_alignment(query, governing, all_decisions),
+ }
- # Weighted keyword scoring across ALL decision fields
- query_lower = query.lower()
- query_words = set(query_lower.split())
- # Remove stop words for better matching
- stop_words = {
- "why",
- "was",
- "is",
- "the",
- "a",
- "an",
- "this",
- "that",
- "how",
- "what",
- "when",
- "where",
- "for",
- "to",
- "of",
- "in",
- "it",
- "be",
- }
- query_words -= stop_words
+ # --- Fallback: git archaeology when no decisions found ---
+ if not governing:
+ result_data["git_archaeology"] = await _git_archaeology_fallback(
+ query,
+ git_meta,
+ all_git_meta,
+ repository,
+ )
+
+ result_data["_meta"] = _build_meta(repository=repository)
+ return result_data
+
+
+# Stop words removed before keyword matching for better signal.
+_QUERY_STOP_WORDS = {
+ "why",
+ "was",
+ "is",
+ "the",
+ "a",
+ "an",
+ "this",
+ "that",
+ "how",
+ "what",
+ "when",
+ "where",
+ "for",
+ "to",
+ "of",
+ "in",
+ "it",
+ "be",
+}
+
+
+async def _load_target_git(
+ session: Any, repository_id: Any, targets: list[str] | None
+) -> dict[str, Any]:
+ """Load per-target git metadata keyed by file path (only present ones)."""
+ target_git: dict[str, Any] = {}
+ if not targets:
+ return target_git
+ for t in targets:
+ git_res = await session.execute(
+ select(GitMetadata).where(
+ GitMetadata.repository_id == repository_id,
+ GitMetadata.file_path == t,
+ )
+ )
+ meta = git_res.scalar_one_or_none()
+ if meta:
+ target_git[t] = meta
+ return target_git
+
+def _rank_keyword_matches(all_decisions: list, query: str, target_set: set[str]) -> list:
+ """Score decisions by weighted keyword overlap and return the top 8."""
+ query_words = set(query.lower().split()) - _QUERY_STOP_WORDS
scored_decisions: list[tuple[float, Any]] = []
for d in all_decisions:
score = _score_decision(d, query_words, target_set)
if score > 0:
scored_decisions.append((score, d))
scored_decisions.sort(key=lambda t: t[0], reverse=True)
- keyword_matches = [d for _, d in scored_decisions[:8]]
+ return [d for _, d in scored_decisions[:8]]
+
- # Semantic search over the shared page store, filtered to the decision: namespace.
- # Over-fetch because decisions are a small slice of a page-dominated store.
- decision_results = []
+async def _semantic_decision_results(ctx: Any, query: str) -> list:
+ """Semantic search of the page store, filtered to the decision: namespace."""
+ decision_results: list = []
with contextlib.suppress(Exception):
if ctx.vector_store is not None:
_raw = await ctx.vector_store.search(query, limit=50)
decision_results = [
r for r in _raw if getattr(r, "page_id", "").startswith(DECISION_VECTOR_PREFIX)
][:5]
+ return decision_results
- # Semantic search over documentation
- doc_results = []
+
+async def _semantic_doc_results(ctx: Any, query: str) -> list:
+ """Semantic search over documentation, falling back to FTS."""
try:
- doc_results = await ctx.vector_store.search(query, limit=3)
+ return await ctx.vector_store.search(query, limit=3)
except Exception:
+ doc_results: list = []
with contextlib.suppress(Exception):
doc_results = await ctx.fts.search(query, limit=3)
+ return doc_results
+
- # Lineage for the keyword matches: walk supersedes/refines back to roots so
- # a "why is X structured this way?" answer renders the chain, not a flat list.
+async def _lineage_for_matches(ctx: Any, keyword_matches: list) -> dict[str, list[dict]]:
+ """Walk lineage chains for the keyword matches; keep only multi-node chains."""
from repowise.core.persistence.decision_graph import build_lineage_chain
lineage_by_id: dict[str, list[dict]] = {}
@@ -305,42 +327,120 @@ async def get_why(
chain = await build_lineage_chain(session3, d.id)
if len(chain) > 1:
lineage_by_id[d.id] = chain
+ return lineage_by_id
- # Merge keyword matches with semantic results (dedup by ID)
+
+def _merge_decisions(
+ keyword_matches: list,
+ decision_results: list,
+ lineage_by_id: dict[str, list[dict]],
+) -> list[dict]:
+ """Merge keyword and semantic decision hits, deduplicated by id."""
seen_ids: set[str] = set()
- merged_decisions = []
+ merged_decisions: list[dict] = []
for d in keyword_matches:
- if d.id not in seen_ids:
- seen_ids.add(d.id)
- merged_decisions.append(
- {
- "id": d.id,
- "title": d.title,
- "status": d.status,
- "decision": d.decision,
- "rationale": d.rationale,
- "context": d.context,
- "consequences": json.loads(d.consequences_json),
- "affected_files": json.loads(d.affected_files_json),
- "source": d.source,
- "confidence": d.confidence,
- "lineage": lineage_by_id.get(d.id, []),
- }
- )
+ if d.id in seen_ids:
+ continue
+ seen_ids.add(d.id)
+ merged_decisions.append(
+ {
+ "id": d.id,
+ "title": d.title,
+ "status": d.status,
+ "decision": d.decision,
+ "rationale": d.rationale,
+ "context": d.context,
+ "consequences": json.loads(d.consequences_json),
+ "affected_files": json.loads(d.affected_files_json),
+ "source": d.source,
+ "confidence": d.confidence,
+ "lineage": lineage_by_id.get(d.id, []),
+ }
+ )
for r in decision_results:
# Strip the "decision:" prefix so the returned id matches the SQL primary key.
real_id = r.page_id[len(DECISION_VECTOR_PREFIX) :]
- if real_id not in seen_ids:
- seen_ids.add(real_id)
- merged_decisions.append(
- {
- "id": real_id,
- "title": r.title,
- "snippet": r.snippet,
- "relevance_score": r.score,
- }
+ if real_id in seen_ids:
+ continue
+ seen_ids.add(real_id)
+ merged_decisions.append(
+ {
+ "id": real_id,
+ "title": r.title,
+ "snippet": r.snippet,
+ "relevance_score": r.score,
+ }
+ )
+ return merged_decisions
+
+
+async def _build_target_context(
+ ctx: Any,
+ repository: Any,
+ all_decisions: list,
+ target_git: dict[str, Any],
+ targets: list[str],
+) -> dict[str, Any]:
+ """Per-target governing decisions + origin story, with archaeology fallback."""
+ async with get_session(ctx.session_factory) as session2:
+ # Load all git metadata for cross-file search
+ all_git_res = await session2.execute(
+ select(GitMetadata).where(
+ GitMetadata.repository_id == repository.id,
)
+ )
+ all_git_meta_list = all_git_res.scalars().all()
+
+ target_context: dict[str, Any] = {}
+ for t in targets:
+ t_governing = []
+ for d in all_decisions:
+ affected = json.loads(d.affected_files_json)
+ affected_mods = json.loads(d.affected_modules_json)
+ if t in affected or any(t.startswith(m + "/") for m in affected_mods):
+ t_governing.append({"title": d.title, "status": d.status})
+ git_m = target_git.get(t)
+ ctx_entry: dict[str, Any] = {
+ "governing_decisions": t_governing,
+ "origin": _build_origin_story(t, git_m, t_governing)
+ if git_m
+ else {
+ "available": False,
+ "summary": f"No git history for {t}.",
+ },
+ }
+ # Git archaeology fallback when no decisions found
+ if not t_governing:
+ ctx_entry["git_archaeology"] = await _git_archaeology_fallback(
+ t,
+ git_m,
+ all_git_meta_list,
+ repository,
+ )
+ target_context[t] = ctx_entry
+ return target_context
+
+
+async def _why_search(query: str, targets: list[str] | None, repo: str | None) -> dict:
+ """Mode 3: natural-language, target-aware decision + documentation search."""
+ from repowise.core.persistence.crud import list_decisions as _list_decisions
+
+ ctx = await _resolve_repo_context(repo)
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
+ all_decisions = await _list_decisions(
+ session, repository.id, include_proposed=True, limit=200
+ )
+ # Load git metadata for targets (for origin context in results)
+ target_git = await _load_target_git(session, repository.id, targets)
+
+ target_set = set(targets) if targets else set()
+ keyword_matches = _rank_keyword_matches(all_decisions, query, target_set)
+ decision_results = await _semantic_decision_results(ctx, query)
+ doc_results = await _semantic_doc_results(ctx, query)
+ lineage_by_id = await _lineage_for_matches(ctx, keyword_matches)
+ merged_decisions = _merge_decisions(keyword_matches, decision_results, lineage_by_id)
result_data: dict[str, Any] = {
"mode": "search",
@@ -360,43 +460,9 @@ async def get_why(
# If targets provided, include target context
if targets:
- async with get_session(ctx.session_factory) as session2:
- # Load all git metadata for cross-file search
- all_git_res = await session2.execute(
- select(GitMetadata).where(
- GitMetadata.repository_id == repository.id,
- )
- )
- all_git_meta_list = all_git_res.scalars().all()
-
- target_context = {}
- for t in targets:
- t_governing = []
- for d in all_decisions:
- affected = json.loads(d.affected_files_json)
- affected_mods = json.loads(d.affected_modules_json)
- if t in affected or any(t.startswith(m + "/") for m in affected_mods):
- t_governing.append({"title": d.title, "status": d.status})
- git_m = target_git.get(t)
- ctx_entry: dict[str, Any] = {
- "governing_decisions": t_governing,
- "origin": _build_origin_story(t, git_m, t_governing)
- if git_m
- else {
- "available": False,
- "summary": f"No git history for {t}.",
- },
- }
- # Git archaeology fallback when no decisions found
- if not t_governing:
- ctx_entry["git_archaeology"] = await _git_archaeology_fallback(
- t,
- git_m,
- all_git_meta_list,
- repository,
- )
- target_context[t] = ctx_entry
- result_data["target_context"] = target_context
+ result_data["target_context"] = await _build_target_context(
+ ctx, repository, all_decisions, target_git, targets
+ )
result_data["_meta"] = _build_meta(repository=repository)
return result_data