Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

Feat UI beautification (#8)

Swati Ahuja0443bd8e02b7
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
index 12e353970..281672dfa 100644
--- a/.claude/settings.local.json
+++ b/.claude/settings.local.json
@@ -108,7 +108,58 @@
"Bash(find /c/Users/ragha/Desktop/repowise/docs -type f \\\\\\(-name *.md -o -name *.txt \\\\\\))",
"Bash(grep -r \"def get_\" /c/Users/ragha/Desktop/repowise/packages/server/src/repowise/server/mcp_server/*.py)",
"Bash(npm install:*)",
- "Bash(npm run:*)"
+ "Bash(npm run:*)",
+ "Bash(ls:*)",
+ "Bash(find /Users/swati.ahuja/Desktop/wise/repowise/packages/web -name *search* -type f)",
+ "Bash(grep -E \"\\\\.\\(md|txt|adr\\)$\")",
+ "Bash(grep -r hybrid /Users/swati.ahuja/Desktop/wise/repowise/packages/core --include=*.py)",
+ "Bash(find /Users/swati.ahuja/Desktop/wise/repowise/tests -name *search* -o -name *vector*)",
+ "Bash(grep -r \"get_vector_store\\\\|get_fts\\\\|vector_store\\\\|_state\\\\._vector_store\" /Users/swati.ahuja/Desktop/wise/repowise/packages/server/src/repowise/server --include=*.py)",
+ "Bash(grep -rn \"transaction\\\\|consistency\\\\|crash\\\\|atomic\\\\|two-phase\" /Users/swati.ahuja/Desktop/wise/repowise/packages/core/src/repowise/core/persistence/*.py)",
+ "Bash(git push:*)",
+ "Bash(source /Users/swati.ahuja/Desktop/wise/repowise/venv/bin/activate)",
+ "Bash(curl -s http://localhost:7337/api/repos)",
+ "Bash(curl -s http://localhost:7337/health)",
+ "Bash(curl -s \"http://localhost:7337/api/pages?repo_id=e0779e597a3142e59e3dd57435f0ef1b\")",
+ "Bash(curl -s http://localhost:3000)",
+ "Bash(curl -s http://localhost:3000/api/repos)",
+ "Bash(curl -s http://localhost:3000/health)",
+ "Bash(curl -s \"http://localhost:3000/api/pages?repo_id=e0779e597a3142e59e3dd57435f0ef1b&limit=5\")",
+ "Bash(curl -s \"http://localhost:3000/api/repos/e0779e597a3142e59e3dd57435f0ef1b/stats\")",
+ "Bash(find /Users/swati.ahuja/Desktop/wise/repowise/packages/web/src/components/graph -type f -name *.ts -o -name *.tsx -o -name *.css -o -name *.json)",
+ "Bash(find /Users/swati.ahuja/Desktop/wise/repowise/packages/web/src/app -name *.tsx)",
+ "Bash(find /Users/swati.ahuja/Desktop/wise/repowise/packages/server /Users/swati.ahuja/Desktop/wise/repowise/packages/core -type f -name *.py)",
+ "Bash(curl -s http://localhost:3000/api/graph/e0779e597a3142e59e3dd57435f0ef1b/dead-nodes)",
+ "Bash(find /Users/swati.ahuja/Desktop/wise/repowise -name *.db -o -name *.sqlite -o -name *.sqlite3)",
+ "Bash(find /Users/swati.ahuja/Desktop/wise/repowise/packages/server -name \"__pycache__\" -type d -exec rm -rf {} +)",
+ "Bash(find /Users/swati.ahuja/Desktop/wise/repowise/packages/server -name \"*.pyc\" -delete)",
+ "Bash(curl -s http://localhost:7337/api/graph/e0779e597a3142e59e3dd57435f0ef1b/dead-nodes)",
+ "Bash(kill 67304)",
+ "Bash(xargs kill:*)",
+ "Bash(.venv/bin/python -c \"import repowise.server.routers.graph; print\\(repowise.server.routers.graph.__file__\\)\")",
+ "Bash(# Apply the same fix to the installed copy in venv/\ncp packages/server/src/repowise/server/routers/graph.py venv/lib/python3.13/site-packages/repowise/server/routers/graph.py && rm -f venv/lib/python3.13/site-packages/repowise/server/routers/__pycache__/graph.cpython-313.pyc && echo \"Copied and cleared cache\")",
+ "Bash(grep -r \"from.*tabs\\\\|import.*Tabs\\\\|<Tabs\" /Users/swati.ahuja/Desktop/wise/repowise/packages/web/src --include=*.tsx)",
+ "Bash(grep -E \"\\\\.py$\")",
+ "Bash(grep -r use-elk-layout /Users/swati.ahuja/Desktop/wise/repowise/packages/web/src --include=*.tsx --include=*.ts)",
+ "Bash(.venv/bin/python -m pytest tests/providers/test_mock_provider.py -x)",
+ "Bash(.venv/bin/python -m pytest tests/unit/server/ -x)",
+ "Bash(.venv/bin/python -m pytest --tb=short -q)",
+ "Bash(.venv/bin/python -m pytest tests/unit/test_providers/ tests/unit/test_persistence/ -v 2>&1)",
+ "Bash(.venv/bin/python -m pytest tests/unit/test_providers/test_anthropic_provider.py tests/unit/test_providers/test_gemini_provider.py tests/unit/test_providers/test_openai_provider.py tests/unit/test_persistence/test_openai_embedder.py -v 2>&1)",
+ "Bash(.venv/bin/python -c \"import anthropic; print\\(anthropic.__version__\\)\")",
+ "Bash(.venv/bin/python -c \"import openai; print\\(openai.__version__\\)\")",
+ "Bash(.venv/bin/python -c \"import google.genai; print\\(''ok''\\)\")",
+ "Bash(/Users/swati.ahuja/Desktop/wise/repowise/venv/bin/python -m pytest tests/ -x --tb=short -q)",
+ "Bash(/Users/swati.ahuja/Desktop/wise/repowise/venv/bin/python -m pytest tests/ --tb=short -q)",
+ "Bash(find . -path */bin/pytest -o -path */bin/python*)",
+ "Bash(/Users/swati.ahuja/Desktop/wise/repowise/venv/bin/python -m pytest tests/unit/server/test_repos.py::test_create_repo -v --tb=long)",
+ "Bash(/Users/swati.ahuja/Desktop/wise/repowise/venv/bin/python -m pytest tests/providers/test_mock_provider.py::TestBaseProviderInterface::test_generate_returns_generated_response -v --tb=long)",
+ "Bash(/Users/swati.ahuja/Desktop/wise/repowise/venv/bin/python -m pytest tests/unit/cli/test_commands.py::TestErrorCases::test_init_no_provider -v --tb=long)",
+ "Bash(./.venv/bin/pytest tests/unit/server/test_mcp.py -x -q)",
+ "Bash(/Users/swati.ahuja/Desktop/wise/repowise/venv/bin/python -m pytest tests/unit/persistence/test_vector_store.py::test_mock_embedder_returns_unit_vectors -v --tb=long)",
+ "Bash(source venv/bin/activate)",
+ "Bash(pip uninstall:*)",
+ "Bash(ruff check:*)"
]
},
"enableAllProjectMcpServers": true,
diff --git a/.gitignore b/.gitignore
index 5d036515a..e6dae4067 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,6 +13,7 @@ dist/
downloads/
eggs/
.eggs/
+.claude/
# Python build dirs (only at root, not packages/web/src/lib/)
/lib/
/lib64/
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 7862d93d6..0dedb77cc 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -78,7 +78,7 @@ For per-package detail (installation, full API reference, all CLI flags, file ma
│ Three Stores │ │ Consumers │
│ │ │ │
│ SQL (wiki pages, │ │ Web UI MCP Server GitHub Action │
-│ jobs, symbols, │ │ (Next.js) (8 tools) (CI/CD) │
+│ jobs, symbols, │ │ (Next.js) (9 tools) (CI/CD) │
│ versions) │ │ │
│ │ │ repowise CLI │
│ Vector (LanceDB / │ │ (init, update, watch, │
@@ -954,7 +954,7 @@ and supports two transports:
- **stdio** — for Claude Code, Cursor, Cline (add to their MCP config)
- **SSE** — for web-based MCP clients (served on port 7338)
-### Tools (8 total)
+### Tools (9 total)
| Tool | What it answers | When to call |
|------|----------------|-------------|
@@ -962,6 +962,7 @@ and supports two transports:
| `get_context(targets, include?)` | Docs, ownership, history, decisions, freshness for files/modules/symbols. Pass multiple targets in one call. | When you need to understand specific code before reading or modifying it. |
| `get_risk(targets)` | Hotspot score, dependents, co-change partners, risk summary per target. Also returns top 5 global hotspots. | Before modifying files — assess what could break. |
| `get_why(query?)` | Three modes: NL search over decisions, path-based decisions for a file, no-arg health dashboard. | Before making architectural changes — understand existing intent. |
+| `update_decision_records(action, ...)` | Full CRUD on decision records: create, update, update_status, delete, list, get. | After every coding task — record new decisions and keep existing ones current. |
| `search_codebase(query)` | Semantic search over the full wiki. Natural language. | When you don't know where something lives. |
| `get_dependency_path(from, to)` | Connection path between two files/modules in the dependency graph. | When you need to understand how two things are connected. |
| `get_dead_code` | Dead/unused code findings sorted by confidence and cleanup impact. | Before cleanup tasks. |
diff --git a/docs/MCP_AND_STATE_REVIEW.md b/docs/MCP_AND_STATE_REVIEW.md
index a174fefbc..bf2cf8624 100644
--- a/docs/MCP_AND_STATE_REVIEW.md
+++ b/docs/MCP_AND_STATE_REVIEW.md
@@ -72,7 +72,7 @@ server process.
## 2. MCP Tools Inventory
-The server implements **8 tools** (consolidated from 16 on 2026-03-25 to reduce
+The server implements **9 tools** (consolidated from 16 on 2026-03-25 to reduce
sequential tool calls for common tasks).
| # | Tool | Category | What It Answers |
@@ -85,6 +85,7 @@ sequential tool calls for common tasks).
| 6 | `get_dependency_path` | Graph | How two files/modules are connected |
| 7 | `get_dead_code` | Analysis | Dead/unused code findings |
| 8 | `get_architecture_diagram` | Visualization | Mermaid diagram for repo/module/file |
+| 9 | `update_decision_records(action, ...)` | Decision Management | CRUD on decision records: create, update, update_status, delete, list, get |
**Consolidation mapping** (old → new):
- `get_module_docs`, `get_file_docs`, `get_symbol`, `get_file_history`, `get_codebase_ownership` (partial), `get_stale_pages` → **`get_context`**
@@ -274,13 +275,13 @@ This is genuinely useful documentation that would take a human engineer signific
## 7. MCP Tool-by-Tool Assessment (Live Test Results)
All tools were tested live against the interview-coach wiki database on 2026-03-25
-(originally 16 tools; consolidated to 8 tools on 2026-03-25).
+(originally 16 tools; consolidated to 9 tools on 2026-03-25).
### Result Summary
| # | Tool | Status | Verdict |
|---|------|--------|---------|
-**Post-consolidation (8 tools, tested 2026-03-25):**
+**Post-consolidation (9 tools, tested 2026-03-25):**
| # | Tool | Status | Verdict |
|---|------|--------|---------|
@@ -546,7 +547,7 @@ files that are actively being changed but have no documented architectural decis
|---|-------|----------|-------------|
| C1 | **DB filename mismatch** (FIXED) | `mcp_server.py:64` | MCP server looked for `.repowise/repowise.db` but CLI creates `.repowise/wiki.db`. Fixed 2026-03-25: changed to `wiki.db`. |
| C2 | **LanceDB filter injection** (FIXED) | `vector_store.py:240,274` | `f"page_id = '{page_id}'"` — string interpolation in LanceDB delete filter. Fixed 2026-03-25: single quotes in page_id are now escaped before interpolation. |
-| C3 | **Tool count mismatch in docs** (FIXED) | Multiple files | Updated "13 tools" → "16 tools" → "8 tools" (after consolidation) in mcp_server.py, ARCHITECTURE.md, server README. |
+| C3 | **Tool count mismatch in docs** (FIXED) | Multiple files | Updated "13 tools" → "16 tools" → "9 tools" (after consolidation) in mcp_server.py, ARCHITECTURE.md, server README. |
### MAJOR (significant impact)
@@ -646,7 +647,7 @@ files that are actively being changed but have no documented architectural decis
2. ~~**Fix MCP embedder**~~ — DONE (M1)
3. ~~**Fix `update_cmd.py`**~~ — DONE (M5)
4. ~~**Install repowise-server in Makefile**~~ — DONE (M7): added as dependency in `packages/cli/pyproject.toml`
-5. ~~**Update tool count**~~ — DONE (C3): updated to 8 tools everywhere
+5. ~~**Update tool count**~~ — DONE (C3): updated to 9 tools everywhere
### Short-term Improvements
diff --git a/packages/core/src/repowise/core/persistence/crud.py b/packages/core/src/repowise/core/persistence/crud.py
index 1b0b3cf04..8c7428b71 100644
--- a/packages/core/src/repowise/core/persistence/crud.py
+++ b/packages/core/src/repowise/core/persistence/crud.py
@@ -16,6 +16,7 @@ from __future__ import annotations
import json
from datetime import UTC, datetime
+from typing import Any
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -1027,6 +1028,55 @@ async def update_decision_status(
return rec
+async def update_decision_by_id(
+ session: AsyncSession,
+ decision_id: str,
+ **fields: Any,
+) -> DecisionRecord | None:
+ """Update content fields of a decision record by ID (partial update).
+
+ Accepts keyword arguments for any updatable field:
+ title, context, decision, rationale, alternatives, consequences,
+ affected_files, affected_modules, tags, evidence_file, evidence_line,
+ confidence.
+
+ JSON list fields (alternatives, consequences, affected_files,
+ affected_modules, tags) accept Python lists and are serialized to JSON.
+
+ Returns None if the decision is not found.
+ """
+ rec = await session.get(DecisionRecord, decision_id)
+ if rec is None:
+ return None
+
+ _json_fields = {
+ "alternatives": "alternatives_json",
+ "consequences": "consequences_json",
+ "affected_files": "affected_files_json",
+ "affected_modules": "affected_modules_json",
+ "tags": "tags_json",
+ }
+ _scalar_fields = {
+ "title",
+ "context",
+ "decision",
+ "rationale",
+ "evidence_file",
+ "evidence_line",
+ "confidence",
+ }
+
+ for key, value in fields.items():
+ if key in _json_fields:
+ setattr(rec, _json_fields[key], json.dumps(value))
+ elif key in _scalar_fields:
+ setattr(rec, key, value)
+
+ rec.updated_at = _now_utc()
+ await session.flush()
+ return rec
+
+
async def delete_decision(session: AsyncSession, decision_id: str) -> bool:
"""Delete a decision record. Returns True if deleted, False if not found."""
rec = await session.get(DecisionRecord, decision_id)
diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.py
index baf6be606..8dd038e9b 100644
--- a/packages/server/src/repowise/server/mcp_server/__init__.py
+++ b/packages/server/src/repowise/server/mcp_server/__init__.py
@@ -1,4 +1,4 @@
-"""repowise MCP Server — 8 tools for AI coding assistants.
+"""repowise MCP Server — 9 tools for AI coding assistants.
Exposes the full repowise wiki as queryable tools via the MCP protocol.
Supports both stdio transport (Claude Code, Cursor, Cline) and SSE transport
@@ -29,6 +29,7 @@ from repowise.server.mcp_server._server import (
)
from repowise.server.mcp_server.tool_context import get_context
from repowise.server.mcp_server.tool_dead_code import get_dead_code
+from repowise.server.mcp_server.tool_decision_records import update_decision_records
from repowise.server.mcp_server.tool_dependency import (
_build_visual_context,
get_dependency_path,
@@ -99,4 +100,5 @@ __all__ = [
"mcp",
"run_mcp",
"search_codebase",
+ "update_decision_records",
]
diff --git a/packages/server/src/repowise/server/mcp_server/tool_decision_records.py b/packages/server/src/repowise/server/mcp_server/tool_decision_records.py
new file mode 100644
index 000000000..d9c1dbcb4
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_decision_records.py
@@ -0,0 +1,235 @@
+"""MCP Tool 9: update_decision_records — CRUD operations on architectural decision records."""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from repowise.core.persistence import crud
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import DecisionRecord
+from repowise.server.mcp_server import _state
+from repowise.server.mcp_server._helpers import _get_repo
+from repowise.server.mcp_server._server import mcp
+
+_VALID_ACTIONS = frozenset({"create", "update", "update_status", "delete", "list", "get"})
+
+
+def _serialize_decision(rec: DecisionRecord) -> dict[str, Any]:
+ """Convert a DecisionRecord ORM object to a plain dict."""
+ return {
+ "id": rec.id,
+ "repository_id": rec.repository_id,
+ "title": rec.title,
+ "status": rec.status,
+ "context": rec.context,
+ "decision": rec.decision,
+ "rationale": rec.rationale,
+ "alternatives": json.loads(rec.alternatives_json),
+ "consequences": json.loads(rec.consequences_json),
+ "affected_files": json.loads(rec.affected_files_json),
+ "affected_modules": json.loads(rec.affected_modules_json),
+ "tags": json.loads(rec.tags_json),
+ "source": rec.source,
+ "evidence_file": rec.evidence_file,
+ "confidence": rec.confidence,
+ "staleness_score": rec.staleness_score,
+ "superseded_by": rec.superseded_by,
+ "created_at": rec.created_at.isoformat() if rec.created_at else None,
+ "updated_at": rec.updated_at.isoformat() if rec.updated_at else None,
+ }
+
+
+async def update_decision_records(
+ action: str,
+ repo: str | None = None,
+ # --- Identifier ---
+ decision_id: str | None = None,
+ # --- Content fields (for create / update) ---
+ title: str | None = None,
+ status: str | None = None,
+ context: str | None = None,
+ decision: str | None = None,
+ rationale: str | None = None,
+ alternatives: list[str] | None = None,
+ consequences: list[str] | None = None,
+ affected_files: list[str] | None = None,
+ affected_modules: list[str] | None = None,
+ tags: list[str] | None = None,
+ # --- Status change ---
+ superseded_by: str | None = None,
+ # --- List filters ---
+ filter_status: str | None = None,
+ filter_source: str | None = None,
+ filter_tag: str | None = None,
+ filter_module: str | None = None,
+ include_proposed: bool = True,
+ limit: int = 50,
+ offset: int = 0,
+) -> dict:
+ """Create, update, or manage architectural decision records.
+
+ Six actions:
+ 1. create — Record a new decision. Requires `title`. Optional: context,
+ decision, rationale, alternatives, consequences, affected_files,
+ affected_modules, tags, status (defaults to "proposed").
+ 2. update — Update content fields of an existing decision by `decision_id`.
+ Pass only the fields you want to change.
+ 3. update_status — Change the status of a decision. Requires `decision_id`
+ and `status` (proposed | active | deprecated | superseded).
+ Optionally pass `superseded_by` with the ID of the replacement decision.
+ 4. delete — Remove a decision by `decision_id`.
+ 5. list — List decisions. Optional filters: filter_status, filter_source,
+ filter_tag, filter_module, include_proposed, limit, offset.
+ 6. get — Get a single decision by `decision_id`.
+
+ Always call this after making architectural changes to keep decision records
+ current. Use action="create" to record new decisions and action="update" to
+ refine existing ones.
+
+ Args:
+ action: One of: create, update, update_status, delete, list, get.
+ repo: Repository path, name, or ID.
+ decision_id: Required for get, update, update_status, delete.
+ title: Decision title (required for create).
+ status: Decision status (for create defaults to "proposed").
+ context: What forced this decision.
+ decision: What was chosen.
+ rationale: Why this was chosen.
+ alternatives: Rejected alternatives.
+ consequences: Tradeoffs / consequences.
+ affected_files: File paths affected by this decision.
+ affected_modules: Module paths affected.
+ tags: Category tags (e.g. auth, database, api, performance).
+ superseded_by: ID of the replacement decision (for update_status).
+ filter_status: Filter list by status.
+ filter_source: Filter list by source.
+ filter_tag: Filter list by tag.
+ filter_module: Filter list by module.
+ include_proposed: Include proposed decisions in list (default True).
+ limit: Max results for list (default 50).
+ offset: Offset for list pagination.
+ """
+ if action not in _VALID_ACTIONS:
+ return {
+ "error": f"Unknown action {action!r}. Valid actions: {', '.join(sorted(_VALID_ACTIONS))}"
+ }
+
+ # --- create ---
+ if action == "create":
+ if not title:
+ return {"error": "action 'create' requires 'title'"}
+ async with get_session(_state._session_factory) as session:
+ repository = await _get_repo(session, repo)
+ rec = await crud.upsert_decision(
+ session,
+ repository_id=repository.id,
+ title=title,
+ status=status or "proposed",
+ context=context or "",
+ decision=decision or "",
+ rationale=rationale or "",
+ alternatives=alternatives,
+ consequences=consequences,
+ affected_files=affected_files,
+ affected_modules=affected_modules,
+ tags=tags,
+ source="mcp_tool",
+ confidence=1.0,
+ )
+ return {"action": "created", "decision": _serialize_decision(rec)}
+
+ # --- get ---
+ if action == "get":
+ if not decision_id:
+ return {"error": "action 'get' requires 'decision_id'"}
+ async with get_session(_state._session_factory) as session:
+ rec = await crud.get_decision(session, decision_id)
+ if rec is None:
+ return {"error": f"Decision {decision_id} not found"}
+ return {"action": "get", "decision": _serialize_decision(rec)}
+
+ # --- list ---
+ if action == "list":
+ async with get_session(_state._session_factory) as session:
+ repository = await _get_repo(session, repo)
+ decisions = await crud.list_decisions(
+ session,
+ repository.id,
+ status=filter_status,
+ source=filter_source,
+ tag=filter_tag,
+ module=filter_module,
+ include_proposed=include_proposed,
+ limit=limit,
+ offset=offset,
+ )
+ return {
+ "action": "list",
+ "count": len(decisions),
+ "decisions": [_serialize_decision(d) for d in decisions],
+ }
+
+ # --- update ---
+ if action == "update":
+ if not decision_id:
+ return {"error": "action 'update' requires 'decision_id'"}
+ fields: dict[str, Any] = {}
+ if title is not None:
+ fields["title"] = title
+ if context is not None:
+ fields["context"] = context
+ if decision is not None:
+ fields["decision"] = decision
+ if rationale is not None:
+ fields["rationale"] = rationale
+ if alternatives is not None:
+ fields["alternatives"] = alternatives
+ if consequences is not None:
+ fields["consequences"] = consequences
+ if affected_files is not None:
+ fields["affected_files"] = affected_files
+ if affected_modules is not None:
+ fields["affected_modules"] = affected_modules
+ if tags is not None:
+ fields["tags"] = tags
+ if not fields:
+ return {"error": "action 'update' requires at least one field to change"}
+ async with get_session(_state._session_factory) as session:
+ rec = await crud.update_decision_by_id(session, decision_id, **fields)
+ if rec is None:
+ return {"error": f"Decision {decision_id} not found"}
+ return {"action": "updated", "decision": _serialize_decision(rec)}
+
+ # --- update_status ---
+ if action == "update_status":
+ if not decision_id:
+ return {"error": "action 'update_status' requires 'decision_id'"}
+ if not status:
+ return {"error": "action 'update_status' requires 'status'"}
+ async with get_session(_state._session_factory) as session:
+ try:
+ rec = await crud.update_decision_status(
+ session,
+ decision_id,
+ status,
+ superseded_by=superseded_by,
+ )
+ except ValueError as exc:
+ return {"error": str(exc)}
+ if rec is None:
+ return {"error": f"Decision {decision_id} not found"}
+ return {"action": "status_updated", "decision": _serialize_decision(rec)}
+
+ # --- delete ---
+ if action == "delete":
+ if not decision_id:
+ return {"error": "action 'delete' requires 'decision_id'"}
+ async with get_session(_state._session_factory) as session:
+ deleted = await crud.delete_decision(session, decision_id)
+ if not deleted:
+ return {"error": f"Decision {decision_id} not found"}
+ return {"action": "deleted", "decision_id": decision_id}
+
+ return {"error": f"Unhandled action {action!r}"}
diff --git a/packages/server/src/repowise/server/routers/graph.py b/packages/server/src/repowise/server/routers/graph.py
index 1338c8c14..8d3ba8507 100644
--- a/packages/server/src/repowise/server/routers/graph.py
+++ b/packages/server/src/repowise/server/routers/graph.py
@@ -333,11 +333,16 @@ async def dead_code_graph(
select(DeadCodeFinding).where(
DeadCodeFinding.repository_id == repo_id,
DeadCodeFinding.status == "open",
- DeadCodeFinding.kind.in_(["unreachable_file", "unused_export"]),
+ DeadCodeFinding.kind == "unreachable_file",
)
)
findings = finding_result.scalars().all()
+ if not findings:
+ return DeadCodeGraphResponse(nodes=[], links=[])
+
+ # Only consider high-confidence findings
+ findings = [f for f in findings if f.confidence >= 0.85]
if not findings:
return DeadCodeGraphResponse(nodes=[], links=[])
@@ -350,9 +355,34 @@ async def dead_code_graph(
GraphNode.node_id.in_(list(dead_paths)),
)
)
- dead_nodes = node_result.scalars().all()
+ all_candidates = node_result.scalars().all()
+
+ # Filter out false positives:
+ # - Entry points and test files are never truly dead
+ # - Files with incoming edges (in_degree > 0) are used
+ # - Framework files (Next.js pages/layouts, alembic, routers, etc.)
+ _framework_patterns = (
+ "alembic/versions/",
+ "__init__.py",
+ "conftest.py",
+ "fixtures/",
+ "/app/", # Next.js app router pages
+ "/pages/", # Next.js pages router
+ "/routers/", # FastAPI routers
+ "/commands/", # CLI commands
+ "/components/ui/", # UI component library
+ )
+ dead_nodes = [
+ n for n in all_candidates
+ if not n.is_entry_point
+ and not n.is_test
+ and not any(pat in n.node_id for pat in _framework_patterns)
+ ]
dead_node_ids = {n.node_id for n in dead_nodes}
+ if not dead_node_ids:
+ return DeadCodeGraphResponse(nodes=[], links=[])
+
out_edge_result = await session.execute(
select(GraphEdge).where(
GraphEdge.repository_id == repo_id,
diff --git a/packages/web/src/app/repos/[id]/docs/page.tsx b/packages/web/src/app/repos/[id]/docs/page.tsx
index 26f2ca2a8..e52d98840 100644
--- a/packages/web/src/app/repos/[id]/docs/page.tsx
+++ b/packages/web/src/app/repos/[id]/docs/page.tsx
@@ -1,7 +1,11 @@
"use client";
-import { use } from "react";
+import { use, useState } from "react";
+import { Download, Loader2 } from "lucide-react";
+import { Button } from "@/components/ui/button";
import { DocsExplorer } from "@/components/docs/docs-explorer";
+import { listAllPages } from "@/lib/api/pages";
+import { downloadTextFile } from "@/lib/utils/download";
export default function DocsPage({
params,
@@ -9,17 +13,48 @@ export default function DocsPage({
params: Promise<{ id: string }>;
}) {
const { id: repoId } = use(params);
+ const [isExporting, setIsExporting] = useState(false);
+
+ const handleExportAll = async () => {
+ setIsExporting(true);
+ try {
+ const pages = await listAllPages(repoId);
+ pages.sort((a, b) => a.target_path.localeCompare(b.target_path));
+ const content = pages
+ .map((p) => `# ${p.title}\n\n> ${p.target_path}\n\n${p.content}`)
+ .join("\n\n---\n\n");
+ downloadTextFile(content, "documentation-export.md");
+ } finally {
+ setIsExporting(false);
+ }
+ };
return (
<div className="flex flex-col h-screen">
{/* Header */}
- <div className="shrink-0 px-4 sm:px-6 py-3 border-b border-[var(--color-border-default)]">
- <h1 className="text-lg font-semibold text-[var(--color-text-primary)]">
- Documentation
- </h1>
- <p className="text-xs text-[var(--color-text-secondary)] mt-0.5">
- Browse AI-generated documentation for every file, module, and symbol.
- </p>
+ <div className="shrink-0 px-4 sm:px-6 py-3 border-b border-[var(--color-border-default)] flex items-start justify-between gap-4">
+ <div>
+ <h1 className="text-lg font-semibold text-[var(--color-text-primary)]">
+ Documentation
+ </h1>
+ <p className="text-xs text-[var(--color-text-secondary)] mt-0.5">
+ Browse AI-generated documentation for every file, module, and symbol.
+ </p>
+ </div>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleExportAll}
+ disabled={isExporting}
+ className="shrink-0"
+ >
+ {isExporting ? (
+ <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />
+ ) : (
+ <Download className="h-3.5 w-3.5 mr-1.5" />
+ )}
+ Export All
+ </Button>
</div>
{/* Explorer */}
diff --git a/packages/web/src/app/repos/[id]/ownership/page.tsx b/packages/web/src/app/repos/[id]/ownership/page.tsx
index b1b6454a0..fc05585fe 100644
--- a/packages/web/src/app/repos/[id]/ownership/page.tsx
+++ b/packages/web/src/app/repos/[id]/ownership/page.tsx
@@ -121,7 +121,7 @@ export default function OwnershipPage() {
<div key={o.email || `owner-${i}`} className="flex items-center justify-between text-xs">
<span className="text-[var(--color-text-secondary)] truncate">{o.name}</span>
<span className="text-[var(--color-text-tertiary)] tabular-nums ml-2">
- {Math.round(o.pct * 100)}%
+ {Math.round((o.pct ?? 0) * 100)}%
</span>
</div>
))}
diff --git a/packages/web/src/components/docs/docs-viewer.tsx b/packages/web/src/components/docs/docs-viewer.tsx
index 18b625fa3..a6c2ff262 100644
--- a/packages/web/src/components/docs/docs-viewer.tsx
+++ b/packages/web/src/components/docs/docs-viewer.tsx
@@ -8,6 +8,7 @@ import {
Cpu,
Hash,
ExternalLink,
+ Download,
ArrowRight,
RefreshCw,
Loader2,
@@ -18,6 +19,7 @@ import { ConfidenceBadge } from "@/components/wiki/confidence-badge";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { formatRelativeTime, formatTokens } from "@/lib/utils/format";
+import { downloadTextFile } from "@/lib/utils/download";
import type { PageResponse } from "@/lib/api/types";
interface DocsViewerProps {
@@ -84,6 +86,19 @@ export function DocsViewer({ page, repoId, isLoading }: DocsViewerProps) {
<span className="truncate max-w-[100px]">{page.model_name}</span>
</Badge>
+ {/* Download as markdown */}
+ <button
+ onClick={() => {
+ const filename = (page.target_path || page.title).replace(/\//g, "_") + ".md";
+ const header = `# ${page.title}\n\n> Path: ${page.target_path}\n\n`;
+ downloadTextFile(header + page.content, filename);
+ }}
+ className="text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-primary)] transition-colors shrink-0"
+ title="Download as Markdown"
+ >
+ <Download className="h-3.5 w-3.5" />
+ </button>
+
{/* Open full page link */}
<Link
href={`/repos/${repoId}/wiki/${encodeURIComponent(page.id)}`}
diff --git a/packages/web/src/components/git/contributor-bar.tsx b/packages/web/src/components/git/contributor-bar.tsx
index db340079e..c07d516ae 100644
--- a/packages/web/src/components/git/contributor-bar.tsx
+++ b/packages/web/src/components/git/contributor-bar.tsx
@@ -16,7 +16,7 @@ interface ContributorBarProps {
export function ContributorBar({ owners }: ContributorBarProps) {
const data = owners.slice(0, 5).map((o) => ({
name: o.name.split(" ")[0] ?? o.name,
- files: o.file_count,
+ files: o.file_count ?? 0,
}));
if (data.length === 0) return null;
diff --git a/packages/web/src/components/graph/edges/dependency-edge.tsx b/packages/web/src/components/graph/edges/dependency-edge.tsx
index 44c1d7ca9..27c7a2ed1 100644
--- a/packages/web/src/components/graph/edges/dependency-edge.tsx
+++ b/packages/web/src/components/graph/edges/dependency-edge.tsx
@@ -2,8 +2,7 @@
import { memo, useContext } from "react";
import {
- getSmoothStepPath,
- EdgeLabelRenderer,
+ getBezierPath,
type EdgeProps,
} from "@xyflow/react";
import { GraphContext } from "../graph-flow";
@@ -17,28 +16,33 @@ function DependencyEdgeInner({
targetY,
sourcePosition,
targetPosition,
+ source,
+ target,
data,
}: EdgeProps) {
const d = (data ?? { importedNames: [], edgeCount: 1 }) as DependencyEdgeData;
const ctx = useContext(GraphContext);
- const edgeKey = id;
- const isOnPath = ctx.highlightedEdges.has(edgeKey);
+ const isOnPath = ctx.highlightedEdges.has(id);
const hasActivePath = ctx.highlightedPath.size > 0;
const isDimmed = hasActivePath && !isOnPath;
const isDynamic = d.importedNames.length === 0;
- const [edgePath, labelX, labelY] = getSmoothStepPath({
+ // Hover-aware: highlight edges connected to hovered node
+ const isHoverHighlighted = ctx.connectedEdgeIds.has(id);
+ const hasHover = ctx.hoveredNodeId !== null;
+ const isHoverDimmed = hasHover && !isHoverHighlighted && !hasActivePath;
+
+ const [edgePath] = getBezierPath({
sourceX,
sourceY,
targetX,
targetY,
sourcePosition,
targetPosition,
- borderRadius: 12,
});
- const strokeWidth = Math.max(1, Math.min(4, 1 + Math.sqrt(d.edgeCount) * 0.5));
+ const strokeWidth = Math.max(1.5, Math.min(4, 1.5 + Math.sqrt(d.edgeCount) * 0.6));
let stroke: string;
let opacity: number;
@@ -51,43 +55,34 @@ function DependencyEdgeInner({
dashArray = "6 4";
animation = "graph-marching-ants 0.6s linear infinite";
} else if (isDimmed) {
- stroke = "rgba(91, 156, 246, 0.15)";
- opacity = 0.3;
- } else if (isDynamic) {
- stroke = "rgba(150, 150, 150, 0.5)";
+ stroke = "rgba(200, 215, 230, 0.25)";
+ opacity = 0.5;
+ } else if (isHoverHighlighted) {
+ stroke = "#93c5fd";
+ opacity = 1;
+ } else if (isHoverDimmed) {
+ stroke = "rgba(200, 215, 230, 0.15)";
opacity = 0.4;
+ } else if (isDynamic) {
+ stroke = "rgba(200, 215, 230, 0.5)";
+ opacity = 1;
dashArray = "4 4";
} else {
- stroke = "rgba(91, 156, 246, 0.35)";
- opacity = 0.6;
+ stroke = "rgba(200, 215, 230, 0.55)";
+ opacity = 1;
}
return (
- <>
- <path
- d={edgePath}
- fill="none"
- stroke={stroke}
- strokeWidth={strokeWidth}
- strokeOpacity={opacity}
- strokeDasharray={dashArray}
- style={{ animation }}
- className="transition-all duration-300"
- />
- {d.edgeCount > 1 && !isDimmed && (
- <EdgeLabelRenderer>
- <div
- className="nodrag nopan pointer-events-none absolute rounded-full bg-[var(--color-bg-elevated)] border border-[var(--color-border-default)] px-1.5 py-0.5 text-[9px] font-medium text-[var(--color-text-tertiary)] tabular-nums"
- style={{
- transform: `translate(-50%, -50%) translate(${labelX}px, ${labelY}px)`,
- opacity: isDimmed ? 0.15 : 0.8,
- }}
- >
- {d.edgeCount}
- </div>
- </EdgeLabelRenderer>
- )}
- </>
+ <path
+ d={edgePath}
+ fill="none"
+ stroke={stroke}
+ strokeWidth={isHoverHighlighted && !isOnPath ? strokeWidth + 0.5 : strokeWidth}
+ strokeOpacity={opacity}
+ strokeDasharray={dashArray}
+ style={{ animation }}
+ className="transition-all duration-200"
+ />
);
}
diff --git a/packages/web/src/components/graph/elk-layout.ts b/packages/web/src/components/graph/elk-layout.ts
index 3f48c0eda..42a432886 100644
--- a/packages/web/src/components/graph/elk-layout.ts
+++ b/packages/web/src/components/graph/elk-layout.ts
@@ -17,10 +17,10 @@ import type {
// ---- Constants ----
-const MODULE_NODE_WIDTH = 200;
-const MODULE_NODE_HEIGHT = 60;
-const FILE_NODE_WIDTH = 160;
-const FILE_NODE_HEIGHT = 40;
+const MODULE_NODE_WIDTH = 140;
+const MODULE_NODE_HEIGHT = 36;
+const FILE_NODE_WIDTH = 140;
+const FILE_NODE_HEIGHT = 36;
const elk = new ELK();
@@ -237,10 +237,10 @@ export async function layoutFileGraph(
layoutOptions: {
"elk.algorithm": "layered",
"elk.direction": "DOWN",
- "elk.layered.spacing.nodeNodeBetweenLayers": "60",
- "elk.layered.spacing.edgeNodeBetweenLayers": "30",
- "elk.spacing.nodeNode": "30",
- "elk.spacing.componentComponent": "50",
+ "elk.layered.spacing.nodeNodeBetweenLayers": "80",
+ "elk.layered.spacing.edgeNodeBetweenLayers": "35",
+ "elk.spacing.nodeNode": "40",
+ "elk.spacing.componentComponent": "60",
"elk.hierarchyHandling": "INCLUDE_CHILDREN",
"elk.layered.crossingMinimization.strategy": "LAYER_SWEEP",
"elk.padding": "[top=45,left=15,bottom=15,right=15]",
@@ -360,6 +360,9 @@ export async function layoutFileGraph(
isTest: apiNode.is_test,
isEntryPoint: apiNode.is_entry_point,
hasDoc: apiNode.has_doc,
+ // View-specific fields (dead code, hot files)
+ ...("confidence_group" in apiNode && { confidenceGroup: (apiNode as Record<string, unknown>).confidence_group }),
+ ...("commit_count" in apiNode && { commitCount: (apiNode as Record<string, unknown>).commit_count }),
} satisfies FileNodeData,
});
}
@@ -447,6 +450,8 @@ export async function layoutModuleGraph(
isTest: fileEntry.is_test,
isEntryPoint: fileEntry.is_entry_point,
hasDoc: fileEntry.has_doc,
+ ...("confidence_group" in fileEntry && { confidenceGroup: (fileEntry as Record<string, unknown>).confidence_group }),
+ ...("commit_count" in fileEntry && { commitCount: (fileEntry as Record<string, unknown>).commit_count }),
} satisfies FileNodeData,
};
}
diff --git a/packages/web/src/components/graph/graph-flow.tsx b/packages/web/src/components/graph/graph-flow.tsx
index b218c8a2e..f901e1177 100644
--- a/packages/web/src/components/graph/graph-flow.tsx
+++ b/packages/web/src/components/graph/graph-flow.tsx
@@ -6,6 +6,7 @@ import {
useMemo,
useState,
useEffect,
+ useRef,
} from "react";
import {
ReactFlow,
@@ -32,12 +33,13 @@ import {
import { ModuleGroupNode } from "./nodes/module-group-node";
import { FileNode } from "./nodes/file-node";
import { DependencyEdge } from "./edges/dependency-edge";
-import { groupNodesAsModules } from "./elk-layout";
+import { groupNodesAsModules, type FileNodeData } from "./elk-layout";
import { useModuleElkLayout, useFileElkLayout } from "./use-elk-layout";
import { PathFinderPanel } from "./path-finder-panel";
import { GraphToolbar, type ColorMode, type ViewMode } from "./graph-toolbar";
import { GraphLegend } from "./graph-legend";
import { GraphContextMenu } from "./graph-context-menu";
+import { GraphTooltip } from "./graph-tooltip";
import { languageColor } from "@/lib/utils/confidence";
// ---- Context ----
@@ -47,6 +49,10 @@ export interface GraphContextValue {
highlightedEdges: Set<string>;
colorMode: ColorMode;
riskScores: Map<string, number>;
+ hoveredNodeId: string | null;
+ connectedNodeIds: Set<string>;
+ connectedEdgeIds: Set<string>;
+ selectedNodeId: string | null;
}
export const GraphContext = createContext<GraphContextValue>({
@@ -54,6 +60,10 @@ export const GraphContext = createContext<GraphContextValue>({
highlightedEdges: new Set(),
colorMode: "language",
riskScores: new Map(),
+ hoveredNodeId: null,
+ connectedNodeIds: new Set(),
+ connectedEdgeIds: new Set(),
+ selectedNodeId: null,
});
// ---- Node/Edge types ----
@@ -104,6 +114,11 @@ function GraphFlowInner({
const [pathFrom, setPathFrom] = useState("");
const [pathTo, setPathTo] = useState("");
+ // Hover & selection tracking
+ const [hoveredNodeId, setHoveredNodeId] = useState<string | null>(null);
+ const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);
+ const [selectedNodeScreen, setSelectedNodeScreen] = useState<{ x: number; y: number } | null>(null);
+
// ---- Data fetching ----
const isModuleView = viewMode === "module";
@@ -206,6 +221,21 @@ function GraphFlowInner({
viewMode === "hotfiles" ? hotLoading : false;
const isLayouting = isModuleView ? moduleLayouting : fileLayouting;
+ // Compute connected nodes/edges for hover highlighting
+ const { connectedNodeIds, connectedEdgeIds } = useMemo(() => {
+ if (!hoveredNodeId) return { connectedNodeIds: new Set<string>(), connectedEdgeIds: new Set<string>() };
+ const nodeIds = new Set<string>([hoveredNodeId]);
+ const edgeIds = new Set<string>();
+ for (const edge of currentEdges) {
+ if (edge.source === hoveredNodeId || edge.target === hoveredNodeId) {
+ edgeIds.add(edge.id);
+ nodeIds.add(edge.source);
+ nodeIds.add(edge.target);
+ }
+ }
+ return { connectedNodeIds: nodeIds, connectedEdgeIds: edgeIds };
+ }, [hoveredNodeId, currentEdges]);
+
// Context value
const ctxValue = useMemo<GraphContextValue>(
() => ({
@@ -213,23 +243,45 @@ function GraphFlowInner({
highlightedEdges,
colorMode,
riskScores: new Map(),
+ hoveredNodeId,
+ connectedNodeIds,
+ connectedEdgeIds,
+ selectedNodeId,
}),
- [highlightedPath, highlightedEdges, colorMode],
+ [highlightedPath, highlightedEdges, colorMode, hoveredNodeId, connectedNodeIds, connectedEdgeIds, selectedNodeId],
);
// ---- Handlers ----
const handleNodeClick: NodeMouseHandler = useCallback(
- (_event, node) => {
+ (event, node) => {
if (node.type === "moduleGroup" && isModuleView) {
// Drill into this module — the node ID is the full module path
setModulePath((prev) => [...prev, node.id]);
+ setSelectedNodeId(null);
return;
}
- // File node or dir group in file view — pass to parent (opens docs)
- onNodeClick?.(node.id, node.type ?? "fileNode");
+ // Toggle selection — show tooltip on click
+ const mEvent = event as unknown as React.MouseEvent;
+ if (selectedNodeId === node.id) {
+ setSelectedNodeId(null);
+ setSelectedNodeScreen(null);
+ } else {
+ setSelectedNodeId(node.id);
+ setSelectedNodeScreen({ x: mEvent.clientX, y: mEvent.clientY });
+ }
},
- [isModuleView, onNodeClick],
+ [isModuleView, selectedNodeId],
+ );
+
+ const handleNodeMouseEnter: NodeMouseHandler = useCallback(
+ (_event, node) => { setHoveredNodeId(node.id); },
+ [],
+ );
+
+ const handleNodeMouseLeave: NodeMouseHandler = useCallback(
+ () => { setHoveredNodeId(null); },
+ [],
);
const handleNodeDoubleClick: NodeMouseHandler = useCallback(
@@ -300,6 +352,8 @@ function GraphFlowInner({
setModulePath([]);
setHighlightedPath(new Set());
setHighlightedEdges(new Set());
+ setSelectedNodeId(null);
+ setSelectedNodeScreen(null);
}, []);
// Breadcrumb
@@ -338,6 +392,45 @@ function GraphFlowInner({
setCtxMenu(null);
}, [ctxMenu]);
+ // After layout completes, zoom to entry-point nodes for a readable first view
+ const hasFocusedRef = useRef(false);
+
+ useEffect(() => {
+ // Only auto-focus once per view mode, after layout is done and nodes exist
+ if (isLayouting || filteredNodes.length === 0 || hasFocusedRef.current) return;
+ hasFocusedRef.current = true;
+
+ const timer = setTimeout(() => {
+ // Per-view zoom strategy
+ switch (viewMode) {
+ case "dead":
+ case "hotfiles":
+ case "architecture": {
+ // Small, focused graphs — fit all nodes, zoom in to read them
+ reactFlow.fitView({ padding: 0.3, duration: 600, maxZoom: 1.5 });
+ return;
+ }
+ case "module": {
+ // Module view — fit all, comfortable zoom
+ reactFlow.fitView({ padding: 0.2, duration: 600, maxZoom: 1 });
+ return;
+ }
+ default:
+ break;
+ }
+
+ // Full graph: zoom to show all nodes but cap zoom so they're readable
+ reactFlow.fitView({ padding: 0.15, duration: 600, maxZoom: 0.6 });
+ }, 100);
+
+ return () => clearTimeout(timer);
+ }, [isLayouting, filteredNodes, reactFlow]);
+
+ // Reset focus flag when view mode changes
+ useEffect(() => {
+ hasFocusedRef.current = false;
+ }, [viewMode]);
+
const minimapNodeColor = useCallback(
(node: Node) => {
if (node.type === "moduleGroup") {
@@ -353,15 +446,6 @@ function GraphFlowInner({
if (isLoading) return <Skeleton className="h-full w-full rounded-lg" />;
- if (filteredNodes.length === 0 && !isLayouting) {
- return (
- <EmptyState
- title="No graph data"
- description="Check that the backend is running and this repo has been indexed."
- />
- );
- }
-
return (
<GraphContext.Provider value={ctxValue}>
<div className="relative w-full h-full">
@@ -374,6 +458,14 @@ function GraphFlowInner({
</div>
)}
+ {filteredNodes.length === 0 && !isLayouting ? (
+ <div className="flex items-center justify-center h-full">
+ <EmptyState
+ title="No graph data"
+ description="Check that the backend is running and this repo has been indexed."
+ />
+ </div>
+ ) : (
<ReactFlow
nodes={filteredNodes}
edges={currentEdges}
@@ -382,16 +474,19 @@ function GraphFlowInner({
onNodeClick={handleNodeClick}
onNodeDoubleClick={handleNodeDoubleClick}
onNodeContextMenu={handleNodeContextMenu}
+ onNodeMouseEnter={handleNodeMouseEnter}
+ onNodeMouseLeave={handleNodeMouseLeave}
+ onPaneClick={() => { setSelectedNodeId(null); setSelectedNodeScreen(null); }}
fitView
- fitViewOptions={{ padding: 0.15 }}
- minZoom={0.02}
+ fitViewOptions={{ padding: 0.3, maxZoom: 1.2 }}
+ minZoom={0.05}
maxZoom={4}
proOptions={{ hideAttribution: true }}
className="!bg-transparent"
nodesDraggable={false}
defaultEdgeOptions={{ type: "dependency" }}
>
- <Background variant={BackgroundVariant.Dots} gap={20} size={1} color="rgba(255,255,255,0.04)" />
+ <Background variant={BackgroundVariant.Dots} gap={16} size={0.5} color="rgba(255,255,255,0.03)" />
<Controls
showInteractive={false}
className="!border-[var(--color-border-default)] !bg-[var(--color-bg-elevated)] !shadow-lg !shadow-black/20 [&>button]:!border-[var(--color-border-default)] [&>button]:!bg-[var(--color-bg-elevated)] [&>button]:!text-[var(--color-text-secondary)] [&>button:hover]:!bg-[var(--color-bg-overlay)] [&>button:hover]:!text-[var(--color-text-primary)]"
@@ -404,6 +499,7 @@ function GraphFlowInner({
zoomable
/>
</ReactFlow>
+ )}
{/* Breadcrumb — shown when drilled into a module */}
{isModuleView && isDrilledDown && (
@@ -493,6 +589,28 @@ function GraphFlowInner({
onPathTo={handleCtxPathTo}
/>
)}
+
+ {/* Node detail tooltip */}
+ {selectedNodeId && selectedNodeScreen && (() => {
+ const rfNode = filteredNodes.find((n) => n.id === selectedNodeId);
+ if (!rfNode) return null;
+ return (
+ <GraphTooltip
+ nodeId={selectedNodeId}
+ nodeType={rfNode.type ?? "fileNode"}
+ data={rfNode.data as Record<string, unknown>}
+ x={selectedNodeScreen.x}
+ y={selectedNodeScreen.y}
+ onClose={() => { setSelectedNodeId(null); setSelectedNodeScreen(null); }}
+ onViewDocs={() => { onNodeViewDocs?.(selectedNodeId); setSelectedNodeId(null); setSelectedNodeScreen(null); }}
+ onExplore={rfNode.type === "moduleGroup" && isModuleView ? () => {
+ setModulePath((prev) => [...prev, selectedNodeId]);
+ setSelectedNodeId(null);
+ setSelectedNodeScreen(null);
+ } : undefined}
+ />
+ );
+ })()}
</div>
</GraphContext.Provider>
);
diff --git a/packages/web/src/components/graph/graph-legend.tsx b/packages/web/src/components/graph/graph-legend.tsx
index 35149fa9e..892836abe 100644
--- a/packages/web/src/components/graph/graph-legend.tsx
+++ b/packages/web/src/components/graph/graph-legend.tsx
@@ -1,5 +1,7 @@
"use client";
+import { useState } from "react";
+import { ChevronDown, ChevronUp } from "lucide-react";
import { LANGUAGE_COLORS } from "@/lib/utils/confidence";
import type { ColorMode, ViewMode } from "./graph-toolbar";
@@ -35,90 +37,81 @@ export function GraphLegend({
colorMode,
viewMode,
}: GraphLegendProps) {
- return (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)]/80 backdrop-blur-sm p-2.5 text-xs space-y-1.5 min-w-[130px] max-w-[160px] shadow-lg shadow-black/20">
- <div className="font-medium text-[var(--color-text-secondary)] tabular-nums">
- {nodeCount} nodes &middot; {edgeCount} edges
- </div>
+ const [expanded, setExpanded] = useState(false);
- <div className="border-t border-[var(--color-border-default)] pt-1.5 space-y-1">
- {/* Doc status — always shown */}
- <div className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
- <span
- className="w-2 h-2 rounded-full shrink-0"
- style={{ background: "var(--color-node-documented)" }}
- />
- <span>Has docs</span>
- </div>
- <div className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
- <span
- className="w-2 h-2 rounded-full shrink-0"
- style={{ background: "var(--color-node-undocumented)" }}
- />
- <span>No docs</span>
- </div>
- </div>
+ return (
+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)]/80 backdrop-blur-sm text-xs shadow-lg shadow-black/20 min-w-[120px] max-w-[150px]">
+ {/* Header — always visible, clickable to expand */}
+ <button
+ onClick={() => setExpanded((s) => !s)}
+ className="flex items-center justify-between w-full px-2.5 py-2 text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"
+ >
+ <span className="font-medium tabular-nums">
+ {nodeCount} nodes &middot; {edgeCount} edges
+ </span>
+ {expanded ? (
+ <ChevronDown className="w-3 h-3 shrink-0 ml-1.5" />
+ ) : (
+ <ChevronUp className="w-3 h-3 shrink-0 ml-1.5" />
+ )}
+ </button>
- {/* Color mode legend */}
- <div className="border-t border-[var(--color-border-default)] pt-1.5 space-y-1">
- <p className="text-[9px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-medium mb-1">
- {colorMode === "language" ? "Language" : colorMode === "community" ? "Community" : "Risk"}
- </p>
+ {/* Expandable color legend */}
+ {expanded && (
+ <div className="px-2.5 pb-2.5 space-y-1.5 border-t border-[var(--color-border-default)] pt-2">
+ <p className="text-[9px] text-[var(--color-text-tertiary)] uppercase tracking-wider font-medium">
+ {colorMode === "language" ? "Language" : colorMode === "community" ? "Community" : "Risk"}
+ </p>
- {colorMode === "language" &&
- LANGUAGE_LEGEND.map((l) => (
- <div key={l.lang} className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
- <span
- className="w-2 h-2 rounded-full shrink-0"
- style={{ background: l.color }}
- />
- <span>{l.label}</span>
- </div>
- ))}
+ {colorMode === "language" &&
+ LANGUAGE_LEGEND.map((l) => (
+ <div key={l.lang} className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
+ <span
+ className="w-2 h-2 rounded-full shrink-0"
+ style={{ background: l.color }}
+ />
+ <span>{l.label}</span>
+ </div>
+ ))}
- {colorMode === "community" &&
- COMMUNITY_SAMPLE.map((c, i) => (
- <div key={i} className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
- <span
- className="w-2 h-2 rounded-full shrink-0"
- style={{ background: c.color }}
- />
- <span>{c.label}</span>
- </div>
- ))}
+ {colorMode === "community" &&
+ COMMUNITY_SAMPLE.map((c, i) => (
+ <div key={i} className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
+ <span
+ className="w-2 h-2 rounded-full shrink-0"
+ style={{ background: c.color }}
+ />
+ <span>{c.label}</span>
+ </div>
+ ))}
- {colorMode === "risk" && (
- <>
- <div className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
- <span className="w-2 h-2 rounded-full shrink-0 bg-[#22c55e]" />
- <span>Low risk</span>
- </div>
- <div className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
- <span className="w-2 h-2 rounded-full shrink-0 bg-[#f59520]" />
- <span>Medium risk</span>
- </div>
- <div className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
- <span className="w-2 h-2 rounded-full shrink-0 bg-[#ef4444]" />
- <span>High risk</span>
- </div>
- </>
- )}
- </div>
+ {colorMode === "risk" && (
+ <>
+ <div className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
+ <span className="w-2 h-2 rounded-full shrink-0 bg-[#22c55e]" />
+ <span>Low risk</span>
+ </div>
+ <div className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
+ <span className="w-2 h-2 rounded-full shrink-0 bg-[#f59520]" />
+ <span>Medium risk</span>
+ </div>
+ <div className="flex items-center gap-2 text-[var(--color-text-tertiary)]">
+ <span className="w-2 h-2 rounded-full shrink-0 bg-[#ef4444]" />
+ <span>High risk</span>
+ </div>
+ </>
+ )}
- {/* View-specific info */}
- {viewMode !== "module" && viewMode !== "full" && (
- <div className="border-t border-[var(--color-border-default)] pt-1.5">
- <p className="text-[9px] text-[var(--color-text-tertiary)]">
- {viewMode === "dead" && "Showing unreachable files"}
- {viewMode === "hotfiles" && "Most-committed files (30d)"}
- {viewMode === "architecture" && "Entry-point reachable (3 hops)"}
- </p>
+ {/* View-specific info */}
+ {viewMode !== "module" && viewMode !== "full" && (
+ <p className="text-[9px] text-[var(--color-text-tertiary)] pt-1 border-t border-[var(--color-border-default)]">
+ {viewMode === "dead" && "Showing unreachable files"}
+ {viewMode === "hotfiles" && "Most-committed files (30d)"}
+ {viewMode === "architecture" && "Entry-point reachable (3 hops)"}
+ </p>
+ )}
</div>
)}
-
- <p className="text-[9px] text-[var(--color-text-tertiary)] pt-1 border-t border-[var(--color-border-default)]">
- Click &middot; Double-click &middot; Right-click
- </p>
</div>
);
}
diff --git a/packages/web/src/components/graph/graph-tooltip.tsx b/packages/web/src/components/graph/graph-tooltip.tsx
index d1dd77a7f..a444b270b 100644
--- a/packages/web/src/components/graph/graph-tooltip.tsx
+++ b/packages/web/src/components/graph/graph-tooltip.tsx
@@ -1,62 +1,254 @@
-import { FileText } from "lucide-react";
+"use client";
+
+import { useEffect, useRef } from "react";
+import { FileText, Folder, ArrowRight, X, Zap, FlaskConical, BookOpen } from "lucide-react";
import { formatNumber } from "@/lib/utils/format";
-import type { GraphNodeResponse } from "@/lib/api/types";
+import { languageColor } from "@/lib/utils/confidence";
+import type { FileNodeData, ModuleNodeData } from "./elk-layout";
interface GraphTooltipProps {
- node: GraphNodeResponse;
+ nodeId: string;
+ nodeType: string;
+ data: Record<string, unknown>;
x: number;
y: number;
- canvasWidth: number;
- canvasHeight: number;
+ onClose: () => void;
+ onViewDocs: () => void;
+ onExplore?: () => void;
+}
+
+function importanceLabel(pagerank: number): { label: string; color: string } {
+ if (pagerank >= 0.01) return { label: "High", color: "#ef4444" };
+ if (pagerank >= 0.003) return { label: "Medium", color: "#f59520" };
+ return { label: "Low", color: "#22c55e" };
}
-export function GraphTooltip({ node, x, y, canvasWidth, canvasHeight }: GraphTooltipProps) {
- const tooltipW = 220;
- const tooltipH = 150;
- const left = x + 16 + tooltipW > canvasWidth ? x - tooltipW - 8 : x + 16;
- const top = y + tooltipH > canvasHeight ? y - tooltipH : y;
+export function GraphTooltip({
+ nodeId,
+ nodeType,
+ data,
+ x,
+ y,
+ onClose,
+ onViewDocs,
+ onExplore,
+}: GraphTooltipProps) {
+ const ref = useRef<HTMLDivElement>(null);
+
+ // Dismiss on Escape
+ useEffect(() => {
+ const handler = (e: KeyboardEvent) => {
+ if (e.key === "Escape") onClose();
+ };
+ window.addEventListener("keydown", handler);
+ return () => window.removeEventListener("keydown", handler);
+ }, [onClose]);
+
+ // Smart positioning: prefer below-right, flip if near edges
+ const tooltipW = 260;
+ const tooltipH = 280;
+ const pad = 12;
+ const vw = typeof window !== "undefined" ? window.innerWidth : 1200;
+ const vh = typeof window !== "undefined" ? window.innerHeight : 800;
+
+ let left = x + pad;
+ let top = y + pad;
+ if (left + tooltipW > vw - pad) left = x - tooltipW - pad;
+ if (top + tooltipH > vh - pad) top = y - tooltipH - pad;
+ if (left < pad) left = pad;
+ if (top < pad) top = pad;
+
+ const isFile = nodeType === "fileNode";
+ const isModule = nodeType === "moduleGroup";
return (
<div
- className="absolute pointer-events-none z-10 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] p-3 shadow-lg text-xs"
+ ref={ref}
+ className="fixed z-50 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-2xl shadow-black/30 backdrop-blur-md text-xs animate-in fade-in slide-in-from-bottom-1 duration-150"
style={{ left, top, width: tooltipW }}
>
- <p className="font-mono font-semibold text-[var(--color-text-primary)] mb-2 truncate">
- {node.node_id}
- </p>
- <div className="space-y-1 text-[var(--color-text-secondary)]">
- <div className="flex justify-between">
- <span>Language</span>
- <span className="font-medium text-[var(--color-text-primary)]">{node.language}</span>
- </div>
- <div className="flex justify-between">
- <span>Symbols</span>
- <span className="font-medium text-[var(--color-text-primary)] tabular-nums">
- {formatNumber(node.symbol_count)}
- </span>
- </div>
- <div className="flex justify-between">
- <span>PageRank</span>
- <span className="font-medium text-[var(--color-text-primary)] tabular-nums">
- {node.pagerank.toFixed(4)}
- </span>
+ {/* Header */}
+ <div className="flex items-start gap-2 p-3 pb-2 border-b border-[var(--color-border-default)]/50">
+ <div className="mt-0.5 shrink-0">
+ {isModule ? (
+ <Folder className="w-4 h-4 text-[var(--color-accent-graph)]" />
+ ) : (
+ <FileText className="w-4 h-4 text-[var(--color-text-secondary)]" />
+ )}
</div>
- <div className="flex justify-between">
- <span>Community</span>
- <span className="font-medium text-[var(--color-text-primary)] tabular-nums">
- {node.community_id}
- </span>
+ <div className="min-w-0 flex-1">
+ <p className="font-mono font-semibold text-[var(--color-text-primary)] text-[11px] leading-tight break-all">
+ {nodeId.split("/").pop()}
+ </p>
+ <p className="text-[10px] text-[var(--color-text-tertiary)] mt-0.5 truncate">
+ {nodeId}
+ </p>
</div>
- {node.is_entry_point && (
- <span className="inline-block mt-1 rounded border border-[var(--color-accent-primary)] bg-[var(--color-accent-muted)] px-1.5 py-0.5 text-xs text-[var(--color-accent-primary)]">
- Entry Point
- </span>
- )}
+ <button
+ onClick={onClose}
+ className="shrink-0 p-0.5 rounded hover:bg-[var(--color-bg-inset)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] transition-colors"
+ >
+ <X className="w-3.5 h-3.5" />
+ </button>
+ </div>
+
+ {/* Details */}
+ <div className="p-3 space-y-2">
+ {isFile && (() => {
+ const d = data as unknown as FileNodeData;
+ const imp = importanceLabel(d.pagerank);
+ return (
+ <>
+ {/* Language */}
+ <div className="flex items-center justify-between">
+ <span className="text-[var(--color-text-tertiary)]">Language</span>
+ <span className="flex items-center gap-1.5">
+ <span
+ className="w-2 h-2 rounded-full"
+ style={{ background: languageColor(d.language) }}
+ />
+ <span className="font-medium text-[var(--color-text-primary)] capitalize">
+ {d.language}
+ </span>
+ </span>
+ </div>
+
+ {/* Symbols */}
+ <div className="flex items-center justify-between">
+ <span className="text-[var(--color-text-tertiary)]">Symbols</span>
+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">
+ {formatNumber(d.symbolCount)}
+ </span>
+ </div>
+
+ {/* Importance */}
+ <div className="flex items-center justify-between">
+ <span className="text-[var(--color-text-tertiary)]">Importance</span>
+ <span className="font-medium tabular-nums" style={{ color: imp.color }}>
+ {imp.label}
+ </span>
+ </div>
+
+ {/* Community */}
+ <div className="flex items-center justify-between">
+ <span className="text-[var(--color-text-tertiary)]">Community</span>
+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">
+ #{d.communityId}
+ </span>
+ </div>
+
+ {/* Betweenness centrality */}
+ <div className="flex items-center justify-between">
+ <span className="text-[var(--color-text-tertiary)]">Betweenness</span>
+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">
+ {d.betweenness < 0.001 ? "<0.1%" : `${(d.betweenness * 100).toFixed(1)}%`}
+ </span>
+ </div>
+
+ {/* Dead code view: confidence group */}
+ {typeof d.confidenceGroup === "string" && (
+ <div className="flex items-center justify-between">
+ <span className="text-[var(--color-text-tertiary)]">Confidence</span>
+ <span className="font-medium text-[var(--color-text-primary)] capitalize">
+ {(d.confidenceGroup as string)}
+ </span>
+ </div>
+ )}
+
+ {/* Hot files view: commit count */}
+ {typeof d.commitCount === "number" && (
+ <div className="flex items-center justify-between">
+ <span className="text-[var(--color-text-tertiary)]">Commits (30d)</span>
+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">
+ {formatNumber(d.commitCount as number)}
+ </span>
+ </div>
+ )}
+
+ {/* Badges row */}
+ <div className="flex items-center gap-1.5 pt-1 flex-wrap">
+ {d.isEntryPoint && (
+ <span className="inline-flex items-center gap-1 rounded-md bg-[var(--color-accent-graph)]/10 text-[var(--color-accent-graph)] px-1.5 py-0.5 text-[10px] font-medium">
+ <Zap className="w-2.5 h-2.5" /> Entry Point
+ </span>
+ )}
+ {d.isTest && (
+ <span className="inline-flex items-center gap-1 rounded-md bg-purple-500/10 text-purple-400 px-1.5 py-0.5 text-[10px] font-medium">
+ <FlaskConical className="w-2.5 h-2.5" /> Test
+ </span>
+ )}
+ {d.hasDoc ? (
+ <span className="inline-flex items-center gap-1 rounded-md bg-green-500/10 text-green-400 px-1.5 py-0.5 text-[10px] font-medium">
+ <BookOpen className="w-2.5 h-2.5" /> Documented
+ </span>
+ ) : (
+ <span className="inline-flex items-center gap-1 rounded-md bg-slate-500/10 text-slate-400 px-1.5 py-0.5 text-[10px] font-medium">
+ <BookOpen className="w-2.5 h-2.5" /> No docs
+ </span>
+ )}
+ </div>
+ </>
+ );
+ })()}
+
+ {isModule && (() => {
+ const d = data as unknown as ModuleNodeData;
+ const docPct = d.docCoveragePct ?? 0;
+ return (
+ <>
+ <div className="flex items-center justify-between">
+ <span className="text-[var(--color-text-tertiary)]">Files</span>
+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">
+ {formatNumber(d.fileCount ?? 0)}
+ </span>
+ </div>
+ {d.symbolCount != null && d.symbolCount > 0 && (
+ <div className="flex items-center justify-between">
+ <span className="text-[var(--color-text-tertiary)]">Symbols</span>
+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">
+ {formatNumber(d.symbolCount)}
+ </span>
+ </div>
+ )}
+ <div className="flex items-center justify-between">
+ <span className="text-[var(--color-text-tertiary)]">Doc coverage</span>
+ <span className="font-medium text-[var(--color-text-primary)] tabular-nums">
+ {Math.round(docPct * 100)}%
+ </span>
+ </div>
+ {/* Mini doc coverage bar */}
+ <div className="h-1.5 w-full rounded-full bg-[var(--color-bg-inset)] overflow-hidden">
+ <div
+ className="h-full rounded-full transition-all duration-300"
+ style={{
+ width: `${Math.max(2, Math.round(docPct * 100))}%`,
+ background: docPct >= 0.7 ? "#22c55e" : docPct >= 0.3 ? "#f59520" : "#ef4444",
+ }}
+ />
+ </div>
+ </>
+ );
+ })()}
</div>
- {/* Hint for clicking */}
- <div className="mt-2 pt-2 border-t border-[var(--color-border-default)]/50 flex items-center gap-1.5 text-[10px] text-[var(--color-text-tertiary)]">
- <FileText className="h-3 w-3" />
- <span>Click to view docs</span>
+
+ {/* Actions */}
+ <div className="flex items-center gap-2 p-3 pt-0">
+ <button
+ onClick={onViewDocs}
+ className="flex-1 flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-bg-inset)] hover:bg-[var(--color-bg-surface)] border border-[var(--color-border-default)] px-2.5 py-1.5 text-[11px] font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] transition-colors"
+ >
+ <BookOpen className="w-3 h-3" />
+ View Docs
+ </button>
+ {onExplore && (
+ <button
+ onClick={onExplore}
+ className="flex-1 flex items-center justify-center gap-1.5 rounded-lg bg-[var(--color-accent-graph)]/10 hover:bg-[var(--color-accent-graph)]/20 border border-[var(--color-accent-graph)]/30 px-2.5 py-1.5 text-[11px] font-medium text-[var(--color-accent-graph)] transition-colors"
+ >
+ <ArrowRight className="w-3 h-3" />
+ Explore
+ </button>
+ )}
</div>
</div>
);
diff --git a/packages/web/src/components/graph/nodes/file-node.tsx b/packages/web/src/components/graph/nodes/file-node.tsx
index 4c2c73b91..c79105b6c 100644
--- a/packages/web/src/components/graph/nodes/file-node.tsx
+++ b/packages/web/src/components/graph/nodes/file-node.tsx
@@ -2,6 +2,7 @@
import { memo, useContext } from "react";
import { Handle, Position, type NodeProps } from "@xyflow/react";
+import { FileText } from "lucide-react";
import { GraphContext } from "../graph-flow";
import { languageColor } from "@/lib/utils/confidence";
import type { FileNodeData } from "../elk-layout";
@@ -26,12 +27,17 @@ function FileNodeInner({ id, data }: NodeProps) {
const isOnPath = ctx.highlightedPath.has(id);
const hasActivePath = ctx.highlightedPath.size > 0;
const isDimmed = hasActivePath && !isOnPath;
+ const isSelected = ctx.selectedNodeId === id;
+ const isHovered = ctx.hoveredNodeId === id;
+ const hasHover = ctx.hoveredNodeId !== null;
+ const isConnected = ctx.connectedNodeIds.has(id);
+ const isHoverDimmed = hasHover && !isConnected && !hasActivePath;
// Determine node accent color based on color mode
let accentColor: string;
switch (ctx.colorMode) {
case "risk": {
- const score = ctx.riskScores.get(d.fullPath) ?? (d.pagerank * 3); // use pagerank as fallback proxy
+ const score = ctx.riskScores.get(d.fullPath) ?? (d.pagerank * 3);
accentColor = riskColor(Math.min(1, score));
break;
}
@@ -44,52 +50,45 @@ function FileNodeInner({ id, data }: NodeProps) {
break;
}
+ // Compute opacity
+ let opacity = 1;
+ if (isDimmed) opacity = 0.15;
+ else if (isHoverDimmed) opacity = 0.35;
+
return (
<div
- className="group relative rounded-lg border transition-all duration-200 cursor-pointer"
+ className="rounded-lg px-2 py-1.5 transition-all duration-200 cursor-pointer"
style={{
- borderColor: isOnPath ? "var(--color-accent-graph)" : `${accentColor}60`,
- background: `linear-gradient(135deg, ${accentColor}12 0%, var(--color-bg-surface) 70%)`,
- opacity: isDimmed ? 0.15 : 1,
- animation: isOnPath ? "graph-path-pulse 2s ease-in-out infinite" : undefined,
- borderStyle: d.isTest ? "dashed" : "solid",
+ border: `2px solid ${accentColor}`,
+ background: `linear-gradient(135deg, ${accentColor}50 0%, #1e293b 100%)`,
+ opacity,
+ transform: isHovered || isSelected ? "scale(1.05)" : "scale(1)",
boxShadow: isOnPath
- ? `0 0 16px ${accentColor}40`
- : `0 2px 8px rgba(0,0,0,0.2)`,
+ ? `0 0 24px ${accentColor}80`
+ : isSelected
+ ? `0 4px 20px rgba(0,0,0,0.5), 0 0 0 3px ${accentColor}`
+ : isHovered
+ ? `0 4px 16px rgba(0,0,0,0.4), 0 0 16px ${accentColor}40`
+ : `0 2px 8px rgba(0,0,0,0.4)`,
+ animation: isOnPath ? "graph-path-pulse 2s ease-in-out infinite" : undefined,
+ borderStyle: d.isTest ? "dashed" : undefined,
}}
+ aria-label={d.fullPath}
>
<Handle
type="target"
position={Position.Top}
- className="!w-1.5 !h-1.5 !bg-[var(--color-border-subtle)] !border-none"
+ className="!w-2 !h-2 !bg-[var(--color-border-subtle)] !border-none"
/>
- {/* Left accent bar */}
- <div
- className="absolute left-0 top-0 bottom-0 w-[3px] rounded-l-lg"
- style={{ background: accentColor }}
- />
-
- <div className="flex items-center gap-2 px-3 py-2 pl-3.5">
- {/* Doc status dot */}
- <div
- className="w-2 h-2 rounded-full shrink-0 ring-1 ring-black/10"
- style={{
- background: d.hasDoc
- ? "var(--color-node-documented)"
- : "var(--color-node-undocumented)",
- }}
- title={d.hasDoc ? "Has documentation" : "No documentation"}
- />
-
- {/* Label */}
- <span className="text-xs font-mono text-[var(--color-text-primary)] truncate max-w-[110px]">
+ {/* Same layout as module node: icon + label + badge */}
+ <div className="flex items-center gap-2">
+ <FileText className="w-3 h-3 shrink-0" style={{ color: accentColor }} />
+ <span className="text-[11px] font-medium text-[var(--color-text-primary)] truncate">
{d.label}
</span>
-
- {/* Entry point badge */}
{d.isEntryPoint && (
- <span className="shrink-0 text-[8px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-[var(--color-accent-graph)]/15 text-[var(--color-accent-graph)]">
+ <span className="ml-auto shrink-0 text-[8px] font-bold uppercase px-1 py-0.5 rounded" style={{ background: `${accentColor}30`, color: accentColor }}>
EP
</span>
)}
@@ -98,7 +97,7 @@ function FileNodeInner({ id, data }: NodeProps) {
<Handle
type="source"
position={Position.Bottom}
- className="!w-1.5 !h-1.5 !bg-[var(--color-border-subtle)] !border-none"
+ className="!w-2 !h-2 !bg-[var(--color-border-subtle)] !border-none"
/>
</div>
);
diff --git a/packages/web/src/components/graph/nodes/module-group-node.tsx b/packages/web/src/components/graph/nodes/module-group-node.tsx
index dfc658b4c..c057dd3d5 100644
--- a/packages/web/src/components/graph/nodes/module-group-node.tsx
+++ b/packages/web/src/components/graph/nodes/module-group-node.tsx
@@ -2,7 +2,7 @@
import { memo, useContext } from "react";
import { Handle, Position, type NodeProps } from "@xyflow/react";
-import { Folder, FileText } from "lucide-react";
+import { Folder } from "lucide-react";
import { GraphContext } from "../graph-flow";
import type { ModuleNodeData } from "../elk-layout";
@@ -13,12 +13,6 @@ const COMMUNITY_COLORS = [
"#64748b", "#0891b2", "#059669", "#b45309", "#7c3aed", "#db2777",
];
-function docCoverageColor(pct: number): string {
- if (pct >= 0.7) return "var(--color-node-documented)";
- if (pct >= 0.3) return "var(--color-risk-medium)";
- return "var(--color-risk-high)";
-}
-
function ModuleGroupNodeInner({ id, data }: NodeProps) {
const d = data as ModuleNodeData;
const ctx = useContext(GraphContext);
@@ -27,11 +21,13 @@ function ModuleGroupNodeInner({ id, data }: NodeProps) {
// Color mode determines the accent/border color
let accentColor: string;
switch (ctx.colorMode) {
- case "risk":
- accentColor = docCoverageColor(docPct); // use doc coverage as proxy for module risk
+ case "risk": {
+ if (docPct >= 0.7) accentColor = "var(--color-node-documented)";
+ else if (docPct >= 0.3) accentColor = "var(--color-risk-medium)";
+ else accentColor = "var(--color-risk-high)";
break;
+ }
case "community": {
- // Use a hash of the module name to pick a community color
let hash = 0;
for (let i = 0; i < id.length; i++) hash = (hash * 31 + id.charCodeAt(i)) | 0;
accentColor = COMMUNITY_COLORS[Math.abs(hash) % COMMUNITY_COLORS.length];
@@ -46,14 +42,31 @@ function ModuleGroupNodeInner({ id, data }: NodeProps) {
const isOnPath = ctx.highlightedPath.has(id);
const hasActivePath = ctx.highlightedPath.size > 0;
const isDimmed = hasActivePath && !isOnPath;
+ const isSelected = ctx.selectedNodeId === id;
+ const isHovered = ctx.hoveredNodeId === id;
+ const hasHover = ctx.hoveredNodeId !== null;
+ const isConnected = ctx.connectedNodeIds.has(id);
+ const isHoverDimmed = hasHover && !isConnected && !hasActivePath;
+
+ let opacity = 1;
+ if (isDimmed) opacity = 0.15;
+ else if (isHoverDimmed) opacity = 0.35;
return (
<div
- className="rounded-xl border-2 bg-[var(--color-bg-elevated)]/80 backdrop-blur-sm px-4 py-3 min-w-[180px] shadow-lg shadow-black/20 transition-all duration-200 cursor-pointer hover:shadow-[0_0_20px_rgba(245,149,32,0.12)]"
+ className="rounded-lg px-2 py-1.5 transition-all duration-200 cursor-pointer"
style={{
- borderColor: isOnPath ? "var(--color-accent-graph)" : accentColor,
- borderLeftWidth: 4,
- opacity: isDimmed ? 0.15 : 1,
+ border: `2px solid ${accentColor}`,
+ background: `linear-gradient(135deg, ${accentColor}50 0%, #1e293b 100%)`,
+ opacity,
+ transform: isHovered || isSelected ? "scale(1.05)" : "scale(1)",
+ boxShadow: isOnPath
+ ? `0 0 24px var(--color-accent-graph)`
+ : isSelected
+ ? `0 4px 20px rgba(0,0,0,0.5), 0 0 0 3px ${accentColor}`
+ : isHovered
+ ? `0 4px 16px rgba(0,0,0,0.4), 0 0 16px ${accentColor}40`
+ : `0 2px 8px rgba(0,0,0,0.4)`,
animation: isOnPath ? "graph-path-pulse 2s ease-in-out infinite" : undefined,
}}
>
@@ -63,49 +76,17 @@ function ModuleGroupNodeInner({ id, data }: NodeProps) {
className="!w-2 !h-2 !bg-[var(--color-border-subtle)] !border-none"
/>
- {/* Header */}
- <div className="flex items-center gap-2 mb-2">
- <div
- className="flex items-center justify-center w-6 h-6 rounded-md"
- style={{ background: `${accentColor}22` }}
- >
- <Folder className="w-3.5 h-3.5" style={{ color: accentColor }} />
- </div>
- <span className="text-sm font-semibold text-[var(--color-text-primary)] truncate max-w-[140px]">
+ {/* Header row: icon + label + file count */}
+ <div className="flex items-center gap-2">
+ <Folder className="w-3 h-3 shrink-0" style={{ color: accentColor }} />
+ <span className="text-[11px] font-medium text-[var(--color-text-primary)] truncate">
{d.label}
</span>
- </div>
-
- {/* Stats row */}
- <div className="flex items-center gap-3 text-[10px] text-[var(--color-text-tertiary)]">
- <span className="flex items-center gap-1">
- <FileText className="w-3 h-3" />
- {d.fileCount ?? 0} files
+ <span className="ml-auto text-[9px] text-[var(--color-text-tertiary)] tabular-nums shrink-0">
+ {d.fileCount ?? 0}
</span>
- {d.symbolCount != null && d.symbolCount > 0 && (
- <span>{d.symbolCount} sym</span>
- )}
</div>
- {/* Doc coverage bar */}
- {d.docCoveragePct != null && (
- <div className="mt-2">
- <div className="flex items-center justify-between text-[9px] text-[var(--color-text-tertiary)] mb-0.5">
- <span>Docs</span>
- <span>{Math.round(docPct * 100)}%</span>
- </div>
- <div className="h-1.5 w-full rounded-full bg-[var(--color-bg-inset)] overflow-hidden">
- <div
- className="h-full rounded-full transition-all duration-500"
- style={{
- width: `${Math.max(2, Math.round(docPct * 100))}%`,
- background: docCoverageColor(docPct),
- }}
- />
- </div>
- </div>
- )}
-
<Handle
type="source"
position={Position.Bottom}
diff --git a/packages/web/src/components/graph/use-elk-layout.ts b/packages/web/src/components/graph/use-elk-layout.ts
index eb3c2a986..16f604819 100644
--- a/packages/web/src/components/graph/use-elk-layout.ts
+++ b/packages/web/src/components/graph/use-elk-layout.ts
@@ -62,6 +62,8 @@ export function useFileElkLayout(
isTest: node.is_test,
isEntryPoint: node.is_entry_point,
hasDoc: node.has_doc,
+ ...("confidence_group" in node && { confidenceGroup: (node as Record<string, unknown>).confidence_group }),
+ ...("commit_count" in node && { commitCount: (node as Record<string, unknown>).commit_count }),
},
})),
);
diff --git a/packages/web/src/lib/utils/download.ts b/packages/web/src/lib/utils/download.ts
new file mode 100644
index 000000000..1376f195c
--- /dev/null
+++ b/packages/web/src/lib/utils/download.ts
@@ -0,0 +1,16 @@
+/** Trigger a browser file download from a string. */
+export function downloadTextFile(
+ content: string,
+ filename: string,
+ mimeType = "text/markdown",
+) {
+ const blob = new Blob([content], { type: mimeType });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+}
diff --git a/tests/unit/server/test_mcp.py b/tests/unit/server/test_mcp.py
index 53ce15ca6..a20c3581a 100644
--- a/tests/unit/server/test_mcp.py
+++ b/tests/unit/server/test_mcp.py
@@ -1,6 +1,6 @@
"""Unit tests for repowise MCP server tools.
-Tests all 8 MCP tools using an in-memory SQLite database with pre-populated
+Tests all 9 MCP tools using an in-memory SQLite database with pre-populated
test data, mirroring the conftest pattern from the REST API tests.
"""
@@ -1177,6 +1177,157 @@ async def test_get_dead_code_group_by_owner(setup_mcp):
# ---- MCP config generation ----
+# ---- Tool 9: update_decision_records ----
+
+
+async def test_update_decision_records_create(setup_mcp):
+ from repowise.server.mcp_server import update_decision_records
+
+ result = await update_decision_records(
+ action="create",
+ title="Use Redis for caching",
+ context="Need distributed caching",
+ decision="Use Redis as the caching layer",
+ rationale="Mature, fast, supports pub/sub",
+ alternatives=["Memcached", "In-memory only"],
+ consequences=["Requires Redis infrastructure"],
+ affected_files=["src/cache/client.py"],
+ affected_modules=["src/cache"],
+ tags=["performance", "infra"],
+ )
+ assert result["action"] == "created"
+ dec = result["decision"]
+ assert dec["title"] == "Use Redis for caching"
+ assert dec["source"] == "mcp_tool"
+ assert dec["confidence"] == 1.0
+ assert dec["status"] == "proposed"
+ assert "Memcached" in dec["alternatives"]
+
+
+async def test_update_decision_records_create_missing_title(setup_mcp):
+ from repowise.server.mcp_server import update_decision_records
+
+ result = await update_decision_records(action="create")
+ assert "error" in result
+ assert "title" in result["error"]
+
+
+async def test_update_decision_records_get(setup_mcp):
+ from repowise.server.mcp_server import update_decision_records
+
+ result = await update_decision_records(action="get", decision_id="dec1")
+ assert result["action"] == "get"
+ assert result["decision"]["title"] == "Use JWT for authentication"
+
+
+async def test_update_decision_records_get_not_found(setup_mcp):
+ from repowise.server.mcp_server import update_decision_records
+
+ result = await update_decision_records(action="get", decision_id="nonexistent")
+ assert "error" in result
+ assert "not found" in result["error"]
+
+
+async def test_update_decision_records_list(setup_mcp):
+ from repowise.server.mcp_server import update_decision_records
+
+ result = await update_decision_records(action="list")
+ assert result["action"] == "list"
+ assert result["count"] >= 2
+ titles = {d["title"] for d in result["decisions"]}
+ assert "Use JWT for authentication" in titles
+ assert "SQLAlchemy as ORM" in titles
+
+
+async def test_update_decision_records_list_with_filter(setup_mcp):
+ from repowise.server.mcp_server import update_decision_records
+
+ result = await update_decision_records(action="list", filter_source="readme_mining")
+ assert result["action"] == "list"
+ assert all(d["source"] == "readme_mining" for d in result["decisions"])
+
+
+async def test_update_decision_records_update(setup_mcp):
+ from repowise.server.mcp_server import update_decision_records
+
+ result = await update_decision_records(
+ action="update",
+ decision_id="dec1",
+ rationale="Updated: stateless and JWT is industry standard",
+ tags=["auth", "security", "api"],
+ )
+ assert result["action"] == "updated"
+ dec = result["decision"]
+ assert "industry standard" in dec["rationale"]
+ assert "api" in dec["tags"]
+ # Other fields should remain unchanged
+ assert dec["title"] == "Use JWT for authentication"
+
+
+async def test_update_decision_records_update_no_fields(setup_mcp):
+ from repowise.server.mcp_server import update_decision_records
+
+ result = await update_decision_records(action="update", decision_id="dec1")
+ assert "error" in result
+ assert "at least one field" in result["error"]
+
+
+async def test_update_decision_records_update_status(setup_mcp):
+ from repowise.server.mcp_server import update_decision_records
+
+ result = await update_decision_records(
+ action="update_status", decision_id="dec1", status="active"
+ )
+ assert result["action"] == "status_updated"
+ assert result["decision"]["status"] == "active"
+
+
+async def test_update_decision_records_update_status_deprecate(setup_mcp):
+ from repowise.server.mcp_server import update_decision_records
+
+ result = await update_decision_records(
+ action="update_status",
+ decision_id="dec1",
+ status="superseded",
+ superseded_by="dec2",
+ )
+ assert result["action"] == "status_updated"
+ assert result["decision"]["status"] == "superseded"
+ assert result["decision"]["superseded_by"] == "dec2"
+
+
+async def test_update_decision_records_delete(setup_mcp):
+ from repowise.server.mcp_server import update_decision_records
+
+ result = await update_decision_records(action="delete", decision_id="dec2")
+ assert result["action"] == "deleted"
+ assert result["decision_id"] == "dec2"
+
+ # Verify it's gone
+ get_result = await update_decision_records(action="get", decision_id="dec2")
+ assert "error" in get_result
+
+
+async def test_update_decision_records_invalid_action(setup_mcp):
+ from repowise.server.mcp_server import update_decision_records
+
+ result = await update_decision_records(action="foo")
+ assert "error" in result
+ assert "Unknown action" in result["error"]
+
+
def test_generate_mcp_config():
from pathlib import Path