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.

Web UX overhaul: consolidated IA, entity pages, unified architecture, and provenance surfacing (#466)

Swati Ahuja2b3f20d7d6b0
diff --git a/package-lock.json b/package-lock.json
index c6892b80d..0a00abeaf 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1293,6 +1293,7 @@
"os": [
"darwin"
],
+ "peer": true,
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
@@ -1315,6 +1316,7 @@
"os": [
"darwin"
],
+ "peer": true,
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
@@ -1337,6 +1339,7 @@
"os": [
"darwin"
],
+ "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -1353,6 +1356,7 @@
"os": [
"darwin"
],
+ "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -1369,6 +1373,7 @@
"os": [
"linux"
],
+ "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -1385,6 +1390,7 @@
"os": [
"linux"
],
+ "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -1401,6 +1407,7 @@
"os": [
"linux"
],
+ "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -1417,6 +1424,7 @@
"os": [
"linux"
],
+ "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -1433,6 +1441,7 @@
"os": [
"linux"
],
+ "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -1449,6 +1458,7 @@
"os": [
"linux"
],
+ "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -1465,6 +1475,7 @@
"os": [
"linux"
],
+ "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -1481,6 +1492,7 @@
"os": [
"linux"
],
+ "peer": true,
"funding": {
"url": "https://opencollective.com/libvips"
}
@@ -1497,6 +1509,7 @@
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
@@ -1519,6 +1532,7 @@
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
@@ -1541,6 +1555,7 @@
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
@@ -1563,6 +1578,7 @@
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
@@ -1585,6 +1601,7 @@
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
@@ -1607,6 +1624,7 @@
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
@@ -1629,6 +1647,7 @@
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
@@ -1651,6 +1670,7 @@
"os": [
"linux"
],
+ "peer": true,
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
@@ -1670,6 +1690,7 @@
],
"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
"optional": true,
+ "peer": true,
"dependencies": {
"@emnapi/runtime": "^1.7.0"
},
@@ -1692,6 +1713,7 @@
"os": [
"win32"
],
+ "peer": true,
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
@@ -1711,6 +1733,7 @@
"os": [
"win32"
],
+ "peer": true,
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
@@ -1730,6 +1753,7 @@
"os": [
"win32"
],
+ "peer": true,
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
@@ -14473,9 +14497,15 @@
"remark-gfm": "^4.0.1",
"shiki": "^4.0.0",
"sigma": "^3.0.3",
+ "sonner": "^2.0.7",
"tailwind-merge": "^3.5.0",
"zustand": "^4.4.0"
},
+ "bin": {
+ "repowise-ui-contrast-check": "scripts/contrast-check.py",
+ "repowise-ui-gates": "scripts/ui-gates.sh",
+ "repowise-ui-no-raw-hex": "scripts/no-raw-hex-check.sh"
+ },
"devDependencies": {
"@testing-library/jest-dom": "^6.5.0",
"@testing-library/react": "^16.0.0",
diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.py
index 94da588c5..620de3f8a 100644
--- a/packages/core/src/repowise/core/persistence/crud/git.py
+++ b/packages/core/src/repowise/core/persistence/crud/git.py
@@ -261,11 +261,29 @@ async def delete_git_commits(session: AsyncSession, repository_id: str) -> None:
await session.flush()
-async def count_git_commits(session: AsyncSession, repository_id: str) -> int:
+def _commit_authorship_clause(authorship: str | None):
+ """Optional authorship predicate: ``agent`` keeps agent-attributed commits,
+ ``human`` keeps the rest. ``None`` / ``"all"`` means no filtering."""
+ if authorship == "agent":
+ return GitCommit.agent_name.is_not(None)
+ if authorship == "human":
+ return GitCommit.agent_name.is_(None)
+ return None
+
+
+async def count_git_commits(
+ session: AsyncSession, repository_id: str, *, authorship: str | None = None
+) -> int:
"""Count persisted commits for a repository."""
- result = await session.execute(
- select(func.count()).select_from(GitCommit).where(GitCommit.repository_id == repository_id)
+ stmt = (
+ select(func.count())
+ .select_from(GitCommit)
+ .where(GitCommit.repository_id == repository_id)
)
+ clause = _commit_authorship_clause(authorship)
+ if clause is not None:
+ stmt = stmt.where(clause)
+ result = await session.execute(stmt)
return int(result.scalar_one() or 0)
@@ -316,20 +334,20 @@ async def get_git_commits(
limit: int = 50,
offset: int = 0,
sort: str = "risk",
+ authorship: str | None = None,
) -> list[GitCommit]:
"""Return a page of commits, sorted by change-risk (default) or recency.
``sort="risk"`` ranks by ``change_risk_score`` descending (the review-
priority order); ``sort="date"`` ranks by ``committed_at`` descending.
+ ``authorship`` optionally narrows to ``agent`` / ``human`` commits.
"""
order = GitCommit.committed_at.desc() if sort == "date" else GitCommit.change_risk_score.desc()
- result = await session.execute(
- select(GitCommit)
- .where(GitCommit.repository_id == repository_id)
- .order_by(order)
- .limit(limit)
- .offset(offset)
- )
+ stmt = select(GitCommit).where(GitCommit.repository_id == repository_id)
+ clause = _commit_authorship_clause(authorship)
+ if clause is not None:
+ stmt = stmt.where(clause)
+ result = await session.execute(stmt.order_by(order).limit(limit).offset(offset))
return list(result.scalars().all())
diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.py
index 9e539fffd..e47197ece 100644
--- a/packages/server/src/repowise/server/app.py
+++ b/packages/server/src/repowise/server/app.py
@@ -36,12 +36,15 @@ from repowise.server.routers import (
costs,
dead_code,
decisions,
+ external_systems,
+ files,
git,
graph,
health,
jobs,
knowledge_map,
modules,
+ overview,
owners,
pages,
providers,
@@ -364,5 +367,8 @@ def create_app() -> FastAPI:
app.include_router(workspace.router)
app.include_router(owners.router)
app.include_router(modules.router)
+ app.include_router(overview.router)
+ app.include_router(files.router)
+ app.include_router(external_systems.router)
return app
diff --git a/packages/server/src/repowise/server/routers/code_health.py b/packages/server/src/repowise/server/routers/code_health.py
index 1d1b11808..110e77956 100644
--- a/packages/server/src/repowise/server/routers/code_health.py
+++ b/packages/server/src/repowise/server/routers/code_health.py
@@ -13,6 +13,7 @@ from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
+from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracy
@@ -26,6 +27,7 @@ from repowise.core.analysis.health.scoring import (
from repowise.core.analysis.health.suggestions import suggestion_for as _suggestion_for
from repowise.core.analysis.health.trends import diff_snapshots, recent_kpis
from repowise.core.persistence import crud
+from repowise.core.persistence.models import WikiSymbol
from repowise.server.deps import get_db_session, verify_api_key
router = APIRouter(
@@ -71,6 +73,64 @@ def _metric_to_dict(m: Any) -> dict:
}
+async def _attach_symbol_ids(
+ session: AsyncSession, repo_id: str, finding_dicts: list[dict]
+) -> list[dict]:
+ """Attach the matching ``WikiSymbol.symbol_id`` to function-level findings.
+
+ Matched by exact (file_path, function_name), falling back to the symbol
+ whose line span contains the finding's ``line_start`` (covers methods
+ recorded as ``Class.method`` vs the bare symbol name). One query for the
+ whole batch; findings with no match keep ``symbol_id = None`` so the UI
+ can degrade to the file page.
+ """
+ paths = {d["file_path"] for d in finding_dicts if d.get("function_name")}
+ if not paths:
+ return finding_dicts
+ rows = (
+ (
+ await session.execute(
+ select(
+ WikiSymbol.symbol_id,
+ WikiSymbol.file_path,
+ WikiSymbol.name,
+ WikiSymbol.start_line,
+ WikiSymbol.end_line,
+ ).where(
+ WikiSymbol.repository_id == repo_id,
+ WikiSymbol.file_path.in_(paths),
+ )
+ )
+ )
+ .all()
+ )
+ by_name: dict[tuple[str, str], str] = {}
+ by_file: dict[str, list[tuple[int, int, str]]] = {}
+ for symbol_id, file_path, name, start_line, end_line in rows:
+ by_name.setdefault((file_path, name), symbol_id)
+ if name and "." in name:
+ by_name.setdefault((file_path, name.rsplit(".", 1)[-1]), symbol_id)
+ if start_line is not None and end_line is not None:
+ by_file.setdefault(file_path, []).append((start_line, end_line, symbol_id))
+ for d in finding_dicts:
+ fn = d.get("function_name")
+ if not fn:
+ d["symbol_id"] = None
+ continue
+ sid = by_name.get((d["file_path"], fn))
+ if sid is None and d.get("line_start") is not None:
+ line = d["line_start"]
+ spans = by_file.get(d["file_path"], [])
+ # Narrowest enclosing span wins (a method, not its class).
+ best: tuple[int, str] | None = None
+ for start, end, symbol_id in spans:
+ if start <= line <= end and (best is None or end - start < best[0]):
+ best = (end - start, symbol_id)
+ sid = best[1] if best else None
+ d["symbol_id"] = sid
+ return finding_dicts
+
+
# Strip the trailing " (N)" suffix that community detection appends to
# disambiguate same-named modules. The leak is harmless in the DB but
# noisy in the dashboard.
@@ -170,11 +230,15 @@ async def health_overview(
[_finding_to_dict(f) for f in findings],
)
+ top_findings = await _attach_symbol_ids(
+ session, repo_id, [_finding_to_dict(f) for f in findings[:limit]]
+ )
+
return {
"summary": summary,
"defect_accuracy": defect_accuracy,
"files": [_metric_to_dict(m) for m in metrics[:limit]],
- "top_findings": [_finding_to_dict(f) for f in findings[:limit]],
+ "top_findings": top_findings,
"modules": _module_rollups(metrics),
"biomarkers": _biomarker_breakdown(findings),
"meta": {
@@ -214,7 +278,7 @@ async def list_health_findings(
file_path=file_path,
min_severity=min_severity,
)
- return [_finding_to_dict(f) for f in findings[:limit]]
+ return await _attach_symbol_ids(session, repo_id, [_finding_to_dict(f) for f in findings[:limit]])
_SORT_FIELDS = {
@@ -393,11 +457,14 @@ async def file_score_breakdown(
metric = metrics[0] if metrics else None
findings = await crud.get_health_findings(session, repo_id, file_path=file_path)
breakdown = _score_breakdown_from_findings(findings)
+ finding_dicts = await _attach_symbol_ids(
+ session, repo_id, [_finding_to_dict(f) for f in findings]
+ )
return {
"file_path": file_path,
"metric": _metric_to_dict(metric) if metric else None,
"breakdown": breakdown,
- "findings": [_finding_to_dict(f) for f in findings],
+ "findings": finding_dicts,
"suggestions": {b: _suggestion_for(b) for b in {f.biomarker_type for f in findings}},
}
diff --git a/packages/server/src/repowise/server/routers/decisions.py b/packages/server/src/repowise/server/routers/decisions.py
index d8c9ededa..5d7e830b6 100644
--- a/packages/server/src/repowise/server/routers/decisions.py
+++ b/packages/server/src/repowise/server/routers/decisions.py
@@ -3,9 +3,11 @@
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, Query
+from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.persistence import crud, decision_graph
+from repowise.core.persistence.models import DecisionEvidence
from repowise.server.deps import get_db_session, verify_api_key
from repowise.server.schemas import (
DecisionCodeEdge,
@@ -18,6 +20,7 @@ from repowise.server.schemas import (
DecisionRecordResponse,
DecisionStatusUpdate,
)
+from repowise.server.schemas.decisions import EvidencePreview
router = APIRouter(
tags=["decisions"],
@@ -40,7 +43,12 @@ async def list_decisions(
offset: int = Query(0, ge=0),
session: AsyncSession = Depends(get_db_session), # noqa: B008
) -> list[DecisionRecordResponse]:
- """List architectural decision records for a repository."""
+ """List architectural decision records for a repository.
+
+ Each row carries an ``evidence_preview`` (the top-ranked evidence row's
+ verbatim quote) plus the total ``evidence_count``, so the table can show
+ provenance without N+1 calls to the per-decision /evidence endpoint.
+ """
decisions = await crud.list_decisions(
session,
repo_id,
@@ -52,7 +60,38 @@ async def list_decisions(
limit=limit,
offset=offset,
)
- return [DecisionRecordResponse.from_orm(d) for d in decisions]
+ items = [DecisionRecordResponse.from_orm(d) for d in decisions]
+
+ ids = [d.id for d in decisions]
+ if ids:
+ rows = (
+ await session.execute(
+ select(DecisionEvidence)
+ .where(DecisionEvidence.decision_id.in_(ids))
+ .order_by(
+ DecisionEvidence.source_rank.desc(),
+ DecisionEvidence.confidence.desc(),
+ )
+ )
+ ).scalars()
+ counts: dict[str, int] = {}
+ best: dict[str, DecisionEvidence] = {}
+ for ev in rows:
+ counts[ev.decision_id] = counts.get(ev.decision_id, 0) + 1
+ # Rows arrive best-first, so the first row per decision wins.
+ best.setdefault(ev.decision_id, ev)
+ for item in items:
+ item.evidence_count = counts.get(item.id, 0)
+ top = best.get(item.id)
+ if top is not None and top.source_quote:
+ item.evidence_preview = EvidencePreview(
+ source=top.source,
+ source_quote=top.source_quote,
+ verification=top.verification,
+ evidence_file=top.evidence_file,
+ evidence_line=top.evidence_line,
+ )
+ return items
@router.get(
diff --git a/packages/server/src/repowise/server/routers/external_systems.py b/packages/server/src/repowise/server/routers/external_systems.py
new file mode 100644
index 000000000..0ea82d4f0
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/external_systems.py
@@ -0,0 +1,74 @@
+"""/api/repos/{repo_id}/external-systems — the dependency registry.
+
+The ``external_systems`` table (populated by the manifest parsers during
+ingestion) previously only fed the C4 L1 boundary. This endpoint exposes the
+full registry — category, ecosystem, version, dev/prod split and the manifest
+each dependency was declared in — for the Architecture Dependencies view.
+"""
+
+from __future__ import annotations
+
+from fastapi import APIRouter, Depends
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.persistence.models import ExternalSystem
+from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.schemas.external_systems import (
+ ExternalSystemEntry,
+ ExternalSystemsResponse,
+)
+
+router = APIRouter(
+ prefix="/api/repos",
+ tags=["external-systems"],
+ dependencies=[Depends(verify_api_key)],
+)
+
+
[email protected]("/{repo_id}/external-systems", response_model=ExternalSystemsResponse)
+async def list_external_systems(
+ repo_id: str,
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> ExternalSystemsResponse:
+ """Every declared third-party dependency, unfiltered and undeduplicated.
+
+ Unlike the C4 L1 view (which dedupes by name for the diagram boundary),
+ this returns one row per (name, declared_in) so a monorepo's per-package
+ manifests stay distinguishable. Sorted by category prominence, then name.
+ """
+ rows = (
+ (
+ await session.execute(
+ select(ExternalSystem).where(ExternalSystem.repository_id == repo_id)
+ )
+ )
+ .scalars()
+ .all()
+ )
+ category_order = {"framework": 0, "service": 1, "tool": 2, "library": 3}
+ items = sorted(
+ (
+ ExternalSystemEntry(
+ name=r.name,
+ display_name=r.display_name or r.name,
+ ecosystem=r.ecosystem,
+ category=r.category,
+ version=r.version,
+ declared_in=r.declared_in,
+ is_dev_dep=bool(r.is_dev_dep),
+ )
+ for r in rows
+ ),
+ key=lambda e: (category_order.get(e.category, 9), e.name.lower(), e.declared_in),
+ )
+ ecosystems = sorted({e.ecosystem for e in items})
+ manifests = sorted({e.declared_in for e in items})
+ return ExternalSystemsResponse(
+ items=items,
+ total=len(items),
+ prod_count=sum(1 for e in items if not e.is_dev_dep),
+ dev_count=sum(1 for e in items if e.is_dev_dep),
+ ecosystems=ecosystems,
+ manifests=manifests,
+ )
diff --git a/packages/server/src/repowise/server/routers/files.py b/packages/server/src/repowise/server/routers/files.py
new file mode 100644
index 000000000..a54ff7a85
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/files.py
@@ -0,0 +1,260 @@
+"""/api/repos/{repo_id}/files/{path} — canonical file-detail aggregate.
+
+One call returning everything the file entity page renders: wiki page ref,
+health metric + findings + score breakdown, git metadata (significant
+commits, commit categories, agent share, co-change partners), coverage
+summary + covered lines, owners, graph metrics (pagerank percentile,
+in/out degree, dependents/dependencies), per-function blame, governing
+decisions, and dead-code findings for the file.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from fastapi import APIRouter, Depends, HTTPException
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.persistence import crud
+from repowise.core.persistence.decision_graph import get_governing_decisions
+from repowise.core.persistence.models import DeadCodeFinding, Page, WikiSymbol
+from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.mcp_server._graph_utils import parse_community_meta, percentile_rank
+from repowise.server.routers.code_health import (
+ _finding_to_dict,
+ _metric_to_dict,
+ _score_breakdown_from_findings,
+)
+from repowise.server.routers.git import _hotspot_from_row
+
+router = APIRouter(
+ prefix="/api/repos",
+ tags=["files"],
+ dependencies=[Depends(verify_api_key)],
+)
+
+
+def _json_or(raw: str | None, default: Any) -> Any:
+ try:
+ parsed = json.loads(raw) if raw else default
+ except Exception:
+ return default
+ return parsed if isinstance(parsed, type(default)) else default
+
+
+def _blame_to_dict(b: Any) -> dict:
+ return {
+ "symbol_id": b.symbol_id,
+ "function_name": b.function_name,
+ "start_line": b.start_line,
+ "end_line": b.end_line,
+ "line_count": b.line_count,
+ "mod_count": b.mod_count,
+ "recent_mod_count": b.recent_mod_count,
+ "median_author_time": b.median_author_time,
+ "owner_name": b.owner_name,
+ "owner_email": b.owner_email,
+ "owner_line_pct": b.owner_line_pct,
+ }
+
+
+def _symbol_slim(s: WikiSymbol) -> dict:
+ return {
+ "symbol_id": s.symbol_id,
+ "name": s.name,
+ "kind": s.kind,
+ "signature": s.signature,
+ "start_line": s.start_line,
+ "end_line": s.end_line,
+ "visibility": s.visibility,
+ "complexity_estimate": s.complexity_estimate,
+ "is_async": s.is_async,
+ }
+
+
[email protected]("/{repo_id}/files/{file_path:path}")
+async def file_detail(
+ repo_id: str,
+ file_path: str,
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> dict:
+ """Aggregate join over every per-file data source we persist."""
+ repo = await crud.get_repository(session, repo_id)
+ if repo is None:
+ raise HTTPException(status_code=404, detail="Repository not found")
+
+ node = await crud.get_graph_node(session, repo_id, file_path)
+ git_meta = await crud.get_git_metadata(session, repo_id, file_path)
+ metrics = await crud.get_health_metrics(session, repo_id, file_paths=[file_path])
+ metric = metrics[0] if metrics else None
+
+ if node is None and git_meta is None and metric is None:
+ raise HTTPException(status_code=404, detail=f"File not indexed: {file_path}")
+
+ # --- Wiki page ref ----------------------------------------------------
+ page_row = (
+ await session.execute(
+ select(Page).where(
+ Page.repository_id == repo_id,
+ Page.page_type == "file_page",
+ Page.target_path == file_path,
+ )
+ )
+ ).scalar_one_or_none()
+ wiki_page = (
+ {
+ "id": page_row.id,
+ "title": page_row.title,
+ "summary": page_row.summary,
+ "content": page_row.content,
+ "freshness_status": page_row.freshness_status,
+ "confidence": page_row.confidence,
+ "human_notes": page_row.human_notes,
+ "updated_at": page_row.updated_at.isoformat() if page_row.updated_at else None,
+ }
+ if page_row
+ else None
+ )
+
+ # --- Health -----------------------------------------------------------
+ findings = await crud.get_health_findings(session, repo_id, file_path=file_path)
+ health = {
+ "metric": _metric_to_dict(metric) if metric else None,
+ "breakdown": _score_breakdown_from_findings(findings) if findings else None,
+ "findings": [_finding_to_dict(f) for f in findings],
+ }
+
+ # --- Git history ------------------------------------------------------
+ git: dict | None = None
+ if git_meta is not None:
+ git = _hotspot_from_row(git_meta).model_dump(mode="json")
+ git["significant_commits"] = _json_or(git_meta.significant_commits_json, [])
+ git["top_authors"] = _json_or(git_meta.top_authors_json, [])
+ git["co_change_partners"] = _json_or(git_meta.co_change_partners_json, [])
+ git["agent"] = {
+ "agent_commit_count": git_meta.agent_commit_count or 0,
+ "agent_authored_pct": git_meta.agent_authored_pct,
+ "tier_counts": _json_or(git_meta.agent_tier_counts_json, {}),
+ }
+ git["first_commit_at"] = (
+ git_meta.first_commit_at.isoformat() if git_meta.first_commit_at else None
+ )
+
+ # --- Coverage (incl. line-level set for the heatmap) --------------------
+ coverage_rows = await crud.load_coverage_for_repo(session, repo_id, file_paths=[file_path])
+ coverage: dict | None = None
+ if coverage_rows:
+ c = coverage_rows[0]
+ coverage = {
+ "line_coverage_pct": c.line_coverage_pct,
+ "branch_coverage_pct": c.branch_coverage_pct,
+ "total_coverable_lines": c.total_coverable_lines,
+ "covered_lines": _json_or(c.covered_lines_json, []),
+ "source_format": c.source_format,
+ "ingested_at": c.ingested_at.isoformat() if c.ingested_at else None,
+ "ingested_commit_sha": c.ingested_commit_sha,
+ }
+
+ # --- Graph context ------------------------------------------------------
+ graph: dict | None = None
+ if node is not None:
+ all_files = await crud.get_all_file_metrics(session, repo_id)
+ degrees = await crud.get_node_degree_counts(session, repo_id, file_path)
+ meta = parse_community_meta(node)
+ edges = await crud.get_graph_edges_for_node(
+ session, repo_id, file_path, direction="both", limit=40
+ )
+ neighbor_ids = {
+ e.source_node_id if e.source_node_id != file_path else e.target_node_id for e in edges
+ }
+ node_map = await crud.get_graph_nodes_by_ids(session, repo_id, list(neighbor_ids))
+ dependents: list[dict] = []
+ dependencies: list[dict] = []
+ for e in edges:
+ inbound = e.target_node_id == file_path
+ other_id = e.source_node_id if inbound else e.target_node_id
+ other = node_map.get(other_id)
+ entry = {
+ "node_id": other_id,
+ "node_type": other.node_type if other else "file",
+ "language": other.language if other else None,
+ "edge_type": e.edge_type,
+ "imported_names": _json_or(e.imported_names_json, []),
+ }
+ (dependents if inbound else dependencies).append(entry)
+ graph = {
+ "language": node.language,
+ "is_entry_point": node.is_entry_point,
+ "is_test": node.is_test,
+ "symbol_count": node.symbol_count,
+ "pagerank": round(node.pagerank or 0.0, 6),
+ "pagerank_percentile": percentile_rank(
+ node.pagerank or 0.0, [n.pagerank or 0.0 for n in all_files]
+ ),
+ "in_degree": degrees["in_degree"],
+ "out_degree": degrees["out_degree"],
+ "community_id": node.community_id,
+ "community_label": meta.get("label") or None,
+ "dependents": dependents[:20],
+ "dependencies": dependencies[:20],
+ }
+
+ # --- Symbols + per-function blame ---------------------------------------
+ symbol_rows = (
+ (
+ await session.execute(
+ select(WikiSymbol)
+ .where(WikiSymbol.repository_id == repo_id, WikiSymbol.file_path == file_path)
+ .order_by(WikiSymbol.start_line)
+ )
+ )
+ .scalars()
+ .all()
+ )
+ blame_rows = await crud.get_git_function_blames(session, repo_id, file_path=file_path)
+
+ # --- Governing decisions + dead code -------------------------------------
+ governing = [
+ {"id": d.id, "title": d.title, "status": d.status}
+ for d in await get_governing_decisions(session, repo_id, file_path)
+ ]
+ dead_rows = (
+ (
+ await session.execute(
+ select(DeadCodeFinding).where(
+ DeadCodeFinding.repository_id == repo_id,
+ DeadCodeFinding.file_path == file_path,
+ DeadCodeFinding.status == "open",
+ )
+ )
+ )
+ .scalars()
+ .all()
+ )
+ dead_code = [
+ {
+ "id": f.id,
+ "kind": f.kind,
+ "symbol_name": f.symbol_name,
+ "confidence": f.confidence,
+ "reason": f.reason,
+ "lines": f.lines,
+ "safe_to_delete": f.safe_to_delete,
+ }
+ for f in dead_rows
+ ]
+
+ return {
+ "file_path": file_path,
+ "wiki_page": wiki_page,
+ "health": health,
+ "git": git,
+ "coverage": coverage,
+ "graph": graph,
+ "symbols": [_symbol_slim(s) for s in symbol_rows],
+ "function_blame": [_blame_to_dict(b) for b in blame_rows],
+ "governing_decisions": governing,
+ "dead_code": dead_code,
+ }
diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.py
index edcfc9d02..b89712ac4 100644
--- a/packages/server/src/repowise/server/routers/git.py
+++ b/packages/server/src/repowise/server/routers/git.py
@@ -18,6 +18,8 @@ from repowise.core.persistence.models import GitCommit, GitMetadata
from repowise.server.deps import get_db_session, verify_api_key
from repowise.server.mcp_server.tool_risk import _check_test_gap
from repowise.server.schemas import (
+ AgentTrendBucket,
+ AgentTrendResponse,
CommitDetailResponse,
CommitResponse,
GitMetadataResponse,
@@ -80,8 +82,31 @@ def _hotspot_from_row(r: GitMetadata) -> HotspotResponse:
)
+def _commit_risk(r: GitCommit):
+ """Re-score the persisted Kamei features; deterministic, reproduces the
+ stored ``change_risk_score`` exactly. Returns None for unscored rows."""
+ if r.change_risk_score is None:
+ return None
+ feats = ChangeFeatures(
+ la=r.lines_added or 0,
+ ld=r.lines_deleted or 0,
+ nf=r.files_changed or 0,
+ nd=r.dirs_changed or 0,
+ ns=r.subsystems_changed or 0,
+ entropy=r.entropy or 0.0,
+ exp=r.author_experience,
+ is_fix=bool(r.is_fix),
+ author=r.author_name or "",
+ subject=r.subject or "",
+ ref=r.sha,
+ )
+ return score_change(feats)
+
+
def _commit_fields(r: GitCommit, normalizer: RiskNormalizer) -> dict:
"""Shared CommitResponse field map (raw row + repo-relative normalization)."""
+ risk = _commit_risk(r)
+ top_driver = risk.top_drivers[0].label if risk and risk.top_drivers else None
return {
"sha": r.sha,
"short_sha": r.sha[:8],
@@ -100,6 +125,11 @@ def _commit_fields(r: GitCommit, normalizer: RiskNormalizer) -> dict:
"change_risk_level": r.change_risk_level,
"risk_percentile": normalizer.percentile(r.change_risk_score),
"review_priority": normalizer.priority(r.change_risk_score),
+ "top_driver": top_driver,
+ "author_experience": r.author_experience,
+ "agent_name": r.agent_name,
+ "agent_autonomy_tier": r.agent_autonomy_tier,
+ "agent_confidence": r.agent_confidence,
}
@@ -115,20 +145,7 @@ def _commit_detail_from_row(r: GitCommit, normalizer: RiskNormalizer) -> CommitD
stored features reproduces the persisted ``change_risk_score`` exactly —
no need to persist the per-driver breakdown.
"""
- feats = ChangeFeatures(
- la=r.lines_added or 0,
- ld=r.lines_deleted or 0,
- nf=r.files_changed or 0,
- nd=r.dirs_changed or 0,
- ns=r.subsystems_changed or 0,
- entropy=r.entropy or 0.0,
- exp=r.author_experience,
- is_fix=bool(r.is_fix),
- author=r.author_name or "",
- subject=r.subject or "",
- ref=r.sha,
- )
- risk = score_change(feats)
+ risk = _commit_risk(r)
drivers = [
RiskDriverResponse(
feature=d.feature,
@@ -136,12 +153,12 @@ def _commit_detail_from_row(r: GitCommit, normalizer: RiskNormalizer) -> CommitD
contribution=d.contribution,
label=d.label,
)
- for d in risk.top_drivers
+ for d in (risk.top_drivers if risk else [])
]
return CommitDetailResponse(
**_commit_fields(r, normalizer),
- author_experience=r.author_experience,
drivers=drivers,
+ agent_channel=r.agent_channel,
)
@@ -149,6 +166,7 @@ def _commit_detail_from_row(r: GitCommit, normalizer: RiskNormalizer) -> CommitD
async def get_commits(
repo_id: str,
sort: str = Query("risk", pattern="^(risk|date)$"),
+ authorship: str = Query("all", pattern="^(all|agent|human)$"),
limit: int = Query(50, ge=1, le=200),
offset: int = Query(0, ge=0),
session: AsyncSession = Depends(get_db_session), # noqa: B008
@@ -156,12 +174,15 @@ async def get_commits(
"""Per-commit change-risk feed — the review-priority queue.
``sort=risk`` (default) orders by raw change-risk score descending (the
- review-priority order); ``sort=date`` orders by recency. Each commit also
+ review-priority order); ``sort=date`` orders by recency. ``authorship``
+ narrows the feed to agent-attributed or human commits. Each commit also
carries a **repo-relative** ``risk_percentile`` + ``review_priority`` so the
ranking is portable across repos (the absolute calibration band is not).
"""
- total = await crud.count_git_commits(session, repo_id)
- rows = await crud.get_git_commits(session, repo_id, limit=limit, offset=offset, sort=sort)
+ total = await crud.count_git_commits(session, repo_id, authorship=authorship)
+ rows = await crud.get_git_commits(
+ session, repo_id, limit=limit, offset=offset, sort=sort, authorship=authorship
+ )
normalizer = RiskNormalizer.from_scores(await crud.get_commit_risk_scores(session, repo_id))
items = [_commit_from_row(r, normalizer) for r in rows]
next_offset = offset + limit if offset + limit < total else None
@@ -173,6 +194,63 @@ async def get_commits(
)
[email protected]("/{repo_id}/commits/agent-trend", response_model=AgentTrendResponse)
+async def get_agent_trend(
+ repo_id: str,
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> AgentTrendResponse:
+ """Monthly agent-vs-human commit volume across the indexed window.
+
+ Buckets the bounded ``git_commits`` table in Python (portable across
+ SQLite/Postgres date functions). Months with zero commits are omitted.
+ """
+ result = await session.execute(
+ select(
+ GitCommit.committed_at,
+ GitCommit.agent_name,
+ GitCommit.agent_autonomy_tier,
+ ).where(GitCommit.repository_id == repo_id)
+ )
+ buckets: dict[str, dict] = {}
+ total = 0
+ agent_total = 0
+ names: dict[str, int] = {}
+ for committed_at, agent_name, tier in result.all():
+ if committed_at is None:
+ continue
+ month = committed_at.strftime("%Y-%m")
+ b = buckets.setdefault(month, {"total": 0, "agent": 0, "tiers": {}})
+ b["total"] += 1
+ total += 1
+ if agent_name:
+ b["agent"] += 1
+ agent_total += 1
+ names[agent_name] = names.get(agent_name, 0) + 1
+ if tier is not None:
+ key = str(tier)
+ b["tiers"][key] = b["tiers"].get(key, 0) + 1
+ return AgentTrendResponse(
+ buckets=[
+ AgentTrendBucket(
+ month=m,
+ total_commits=b["total"],
+ agent_commits=b["agent"],
+ agent_pct=(b["agent"] / b["total"] * 100.0) if b["total"] else 0.0,
+ tier_counts=b["tiers"],
+ )
+ for m, b in sorted(buckets.items())
+ ],
+ total_commits=total,
+ agent_commits=agent_total,
+ agent_pct=(agent_total / total * 100.0) if total else 0.0,
+ agent_names=sorted(
+ [{"name": k, "count": v} for k, v in names.items()],
+ key=lambda x: x["count"],
+ reverse=True,
+ ),
+ )
+
+
@router.get("/{repo_id}/commits/{sha}", response_model=CommitDetailResponse)
async def get_commit(
repo_id: str,
diff --git a/packages/server/src/repowise/server/routers/modules.py b/packages/server/src/repowise/server/routers/modules.py
index 271941f43..68e696586 100644
--- a/packages/server/src/repowise/server/routers/modules.py
+++ b/packages/server/src/repowise/server/routers/modules.py
@@ -8,11 +8,14 @@ from __future__ import annotations
from urllib.parse import unquote
+from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi import APIRouter, Depends, HTTPException, Query
+from repowise.core.persistence.models import DecisionRecord
from repowise.server.deps import get_db_session, verify_api_key
from repowise.server.schemas import (
+ GoverningDecisionRef,
ModuleHealthDetail,
ModuleHealthOwner,
ModuleHealthSummary,
@@ -38,7 +41,9 @@ router = APIRouter(
)
async def list_module_health(
repo_id: str,
- sort: str = Query("health_score", description="health_score | hotspot_count | dead_code_lines | file_count"),
+ sort: str = Query(
+ "health_score", description="health_score | hotspot_count | dead_code_lines | file_count"
+ ),
limit: int = Query(100, ge=1, le=500),
offset: int = Query(0, ge=0),
session: AsyncSession = Depends(get_db_session), # noqa: B008
@@ -67,6 +72,38 @@ async def list_module_health(
)
+async def _decision_refs(
+ session: AsyncSession, repo_id: str, decision_ids: list[str]
+) -> list[GoverningDecisionRef]:
+ """Hydrate decision ids into title-bearing refs (UUIDs are unreadable)."""
+ if not decision_ids:
+ return []
+ rows = (
+ (
+ await session.execute(
+ select(DecisionRecord).where(
+ DecisionRecord.repository_id == repo_id,
+ DecisionRecord.id.in_(decision_ids),
+ )
+ )
+ )
+ .scalars()
+ .all()
+ )
+ by_id = {d.id: d for d in rows}
+ refs: list[GoverningDecisionRef] = []
+ for did in decision_ids:
+ d = by_id.get(did)
+ refs.append(
+ GoverningDecisionRef(
+ id=did,
+ title=d.title if d else did,
+ status=d.status if d else "unknown",
+ )
+ )
+ return refs
+
+
@router.get(
"/{repo_id}/modules/health/{module_path:path}",
response_model=ModuleHealthDetail,
@@ -90,7 +127,9 @@ async def get_module_health(
**base,
owners=[ModuleHealthOwner(**o) for o in extras["owners"]],
top_hotspots=extras["top_hotspots"],
- governing_decisions=extras["governing_decisions"],
+ governing_decisions=await _decision_refs(
+ session, repo_id, extras["governing_decisions"]
+ ),
contributor_count=extras["contributor_count"],
)
@@ -105,7 +144,7 @@ async def get_module_health(
**single,
owners=[ModuleHealthOwner(**o) for o in owners],
top_hotspots=top_hotspots,
- governing_decisions=governing_decisions,
+ governing_decisions=await _decision_refs(session, repo_id, governing_decisions),
contributor_count=contributor_count,
)
@@ -118,7 +157,9 @@ async def get_module_health(
**base,
owners=[ModuleHealthOwner(**o) for o in extras["owners"]],
top_hotspots=extras["top_hotspots"],
- governing_decisions=extras["governing_decisions"],
+ governing_decisions=await _decision_refs(
+ session, repo_id, extras["governing_decisions"]
+ ),
contributor_count=extras["contributor_count"],
)
diff --git a/packages/server/src/repowise/server/routers/overview.py b/packages/server/src/repowise/server/routers/overview.py
new file mode 100644
index 000000000..e185e47e2
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/overview.py
@@ -0,0 +1,418 @@
+"""/api/repos/{repo_id}/overview-summary — one-call repo overview payload.
+
+Replaces the dashboard's N-call waterfall with a single lightweight
+aggregate: repo meta, stat strip (+ deltas vs the previous health
+snapshot), server-built attention items, language distribution (from
+graph_nodes, NOT a full graph export), top-hotspots slice, recent
+decisions slice, savings headline, and health KPIs.
+"""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+from pathlib import Path
+from typing import Any
+
+from fastapi import APIRouter, Depends, HTTPException
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.persistence import crud
+from repowise.core.persistence.models import (
+ DeadCodeFinding,
+ GenerationJob,
+ GitMetadata,
+ GraphNode,
+ Page,
+)
+from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.routers.git import _hotspot_from_row
+from repowise.server.services.knowledge_map import compute_knowledge_map
+
+router = APIRouter(
+ prefix="/api/repos",
+ tags=["overview"],
+ dependencies=[Depends(verify_api_key)],
+)
+
+
+def _decision_slim(d: Any) -> dict:
+ return {
+ "id": d.id,
+ "title": d.title,
+ "status": d.status,
+ "source": d.source,
+ "created_at": d.created_at.isoformat() if d.created_at else None,
+ "staleness_score": round(float(d.staleness_score or 0.0), 3),
+ }
+
+
+async def _savings_headline(repo_local_path: str | None) -> dict:
+ """Distill + MCP savings totals from the omission-store sidecar.
+
+ Headline numbers only — no per-day rollups, no transcript scan (the
+ missed-savings scan reads agent transcripts and is too slow for an
+ overview payload). Mirrors /distill-savings semantics otherwise.
+ """
+ if not repo_local_path:
+ return {"available": False}
+ db_path = Path(repo_local_path) / ".repowise" / "omissions" / "omissions.db"
+ if not db_path.is_file():
+ return {"available": False}
+
+ from repowise.core.distill import tracking
+ from repowise.core.distill.session_model import resolve_session_model
+ from repowise.core.generation.cost_tracker import get_model_pricing
+
+ try:
+ conn = sqlite3.connect(f"file:{db_path.as_posix()}?mode=ro", uri=True, timeout=1)
+ except sqlite3.Error:
+ return {"available": False}
+ try:
+ summary = tracking.distill_summary(conn, since=None)
+ mcp = tracking.mcp_savings_summary(conn, since=None)
+ except sqlite3.Error:
+ return {"available": False}
+ finally:
+ conn.close()
+
+ resolved = resolve_session_model(Path(repo_local_path))
+ rate = get_model_pricing(resolved.model)["input"]
+ total_saved = summary["saved_tokens"] + mcp["tokens"]
+ return {
+ "available": True,
+ "saved_tokens": summary["saved_tokens"],
+ "mcp_tokens": mcp["tokens"],
+ "total_saved_tokens": total_saved,
+ "estimated_usd_saved": total_saved * rate / 1_000_000,
+ "pricing_model": resolved.model,
+ }
+
+
+def _build_attention_items(
+ decision_health: dict,
+ knowledge_silos: list[dict],
+ dead_safe: list[Any],
+) -> list[dict]:
+ """Flat, severity-tagged attention list — the server-side twin of the
+ AttentionPanel item builder that used to live in the overview page."""
+ items: list[dict] = []
+ for d in decision_health.get("stale_decisions", []):
+ items.append(
+ {
+ "id": f"stale-{d.id}",
+ "type": "stale_decision",
+ "title": d.title,
+ "description": "Active decision drifting from the code it governs",
+ "severity": "high",
+ "target_id": d.id,
+ }
+ )
+ for d in decision_health.get("proposed_awaiting_review", []):
+ items.append(
+ {
+ "id": f"proposed-{d.id}",
+ "type": "proposed_decision",
+ "title": d.title,
+ "description": "Auto-proposed decision awaiting review",
+ "severity": "medium",
+ "target_id": d.id,
+ }
+ )
+ for fp in decision_health.get("ungoverned_hotspots", [])[:10]:
+ items.append(
+ {
+ "id": f"ungoverned-{fp}",
+ "type": "ungoverned_hotspot",
+ "title": fp,
+ "description": "High-churn file with no governing decision",
+ "severity": "medium",
+ "target_id": fp,
+ }
+ )
+ for s in knowledge_silos[:10]:
+ items.append(
+ {
+ "id": f"silo-{s['file_path']}",
+ "type": "knowledge_silo",
+ "title": s["file_path"],
+ "description": (f"{round(s['owner_pct'] * 100)}% single-owner concentration"),
+ "severity": "medium",
+ "target_id": s["file_path"],
+ }
+ )
+ for f in dead_safe[:10]:
+ label = f.symbol_name or f.file_path
+ items.append(
+ {
+ "id": f"dead-{f.id}",
+ "type": "dead_code",
+ "title": label,
+ "description": f"Safe to delete ({f.lines} lines)",
+ "severity": "low",
+ "target_id": f.file_path,
+ }
+ )
+ severity_rank = {"high": 0, "medium": 1, "low": 2}
+ items.sort(key=lambda i: severity_rank.get(i["severity"], 3))
+ return items
+
+
[email protected]("/{repo_id}/overview-summary")
+async def overview_summary(
+ repo_id: str,
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> dict:
+ """Everything the Overview page needs above the fold, in one call."""
+ repo = await crud.get_repository(session, repo_id)
+ if repo is None:
+ raise HTTPException(status_code=404, detail="Repository not found")
+
+ # --- Stat strip ------------------------------------------------------
+ file_count = (
+ await session.scalar(
+ select(func.count(GraphNode.id)).where(
+ GraphNode.repository_id == repo_id, GraphNode.node_type == "file"
+ )
+ )
+ or 0
+ )
+ symbol_count = int(
+ await session.scalar(
+ select(func.sum(GraphNode.symbol_count)).where(GraphNode.repository_id == repo_id)
+ )
+ or 0
+ )
+ entry_point_count = (
+ await session.scalar(
+ select(func.count(GraphNode.id)).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.is_entry_point.is_(True),
+ )
+ )
+ or 0
+ )
+ avg_confidence = float(
+ await session.scalar(select(func.avg(Page.confidence)).where(Page.repository_id == repo_id))
+ or 0.0
+ )
+ doc_coverage_pct = avg_confidence * 100
+ total_pages = (
+ await session.scalar(select(func.count(Page.id)).where(Page.repository_id == repo_id)) or 0
+ )
+ fresh_pages = (
+ await session.scalar(
+ select(func.count(Page.id)).where(
+ Page.repository_id == repo_id, Page.freshness_status == "fresh"
+ )
+ )
+ or 0
+ )
+ freshness_score = (fresh_pages / total_pages * 100) if total_pages > 0 else doc_coverage_pct
+ dead_export_count = (
+ await session.scalar(
+ select(func.count(DeadCodeFinding.id)).where(
+ DeadCodeFinding.repository_id == repo_id,
+ DeadCodeFinding.kind == "unused_export",
+ DeadCodeFinding.status == "open",
+ )
+ )
+ or 0
+ )
+ hotspot_count = (
+ await session.scalar(
+ select(func.count(GitMetadata.id)).where(
+ GitMetadata.repository_id == repo_id,
+ GitMetadata.is_hotspot.is_(True),
+ )
+ )
+ or 0
+ )
+
+ # Module-level silo counts (top-level-directory grouping — mirrors the
+ # /ownership?granularity=module aggregation the page used to fetch).
+ owner_rows = await session.execute(
+ select(GitMetadata.file_path, GitMetadata.primary_owner_name).where(
+ GitMetadata.repository_id == repo_id
+ )
+ )
+ module_owner_files: dict[str, dict[str, int]] = {}
+ module_file_totals: dict[str, int] = {}
+ for fp, owner in owner_rows:
+ parts = fp.split("/")
+ module = parts[0] if len(parts) > 1 else "root"
+ module_file_totals[module] = module_file_totals.get(module, 0) + 1
+ if owner:
+ bucket = module_owner_files.setdefault(module, {})
+ bucket[owner] = bucket.get(owner, 0) + 1
+ module_count = len(module_file_totals)
+ silo_count = 0
+ for module, owners in module_owner_files.items():
+ top = max(owners.values(), default=0)
+ if module_file_totals.get(module) and top / module_file_totals[module] > 0.8:
+ silo_count += 1
+
+ # --- Language distribution (server-side; replaces the full graph export)
+ lang_rows = await session.execute(
+ select(GraphNode.language, func.count(GraphNode.id))
+ .where(GraphNode.repository_id == repo_id, GraphNode.node_type == "file")
+ .group_by(GraphNode.language)
+ )
+ languages = sorted(
+ ({"language": lang or "other", "file_count": n} for lang, n in lang_rows),
+ key=lambda r: -r["file_count"],
+ )
+
+ # --- Health KPIs + deltas vs previous snapshot ------------------------
+ health_summary = await crud.get_health_summary(session, repo_id)
+ snapshots = await crud.list_health_snapshots(session, repo_id)
+ hotspot_health: float | None = None
+ last_indexed_at: str | None = None
+ deltas: dict[str, float | None] = {
+ "average_health": None,
+ "hotspot_health": None,
+ "file_count": None,
+ }
+ if snapshots:
+ latest = snapshots[-1]
+ hotspot_health = round(float(latest.hotspot_health), 2)
+ last_indexed_at = latest.taken_at.isoformat() if latest.taken_at else None
+ if len(snapshots) >= 2:
+ prev, cur = snapshots[-2], snapshots[-1]
+ deltas["average_health"] = round(float(cur.average_health) - float(prev.average_health), 2)
+ deltas["hotspot_health"] = round(float(cur.hotspot_health) - float(prev.hotspot_health), 2)
+ try:
+ prev_files = len(json.loads(prev.per_file_scores_json or "{}"))
+ cur_files = len(json.loads(cur.per_file_scores_json or "{}"))
+ if prev_files and cur_files:
+ deltas["file_count"] = cur_files - prev_files
+ except Exception:
+ pass
+
+ findings = await crud.get_health_findings(session, repo_id)
+ severity_breakdown = {"critical": 0, "high": 0, "medium": 0, "low": 0}
+ for f in findings:
+ s = (f.severity or "").lower()
+ if s in severity_breakdown:
+ severity_breakdown[s] += 1
+
+ # --- Attention items + onboarding targets -----------------------------
+ decision_health = await crud.get_decision_health_summary(session, repo_id)
+ knowledge = await compute_knowledge_map(session, repo_id)
+ dead_safe = [
+ f
+ for f in await crud.get_dead_code_findings(session, repo_id, status="open")
+ if f.safe_to_delete
+ ]
+ attention = _build_attention_items(
+ decision_health, knowledge.get("knowledge_silos", []), dead_safe
+ )
+
+ # --- Top hotspots + recent decisions slices ---------------------------
+ hotspot_rows = (
+ (
+ await session.execute(
+ select(GitMetadata)
+ .where(GitMetadata.repository_id == repo_id, GitMetadata.is_hotspot.is_(True))
+ .order_by(
+ GitMetadata.temporal_hotspot_score.desc().nulls_last(),
+ GitMetadata.churn_percentile.desc(),
+ )
+ .limit(8)
+ )
+ )
+ .scalars()
+ .all()
+ )
+ top_hotspots = [_hotspot_from_row(r).model_dump(mode="json") for r in hotspot_rows]
+
+ decisions = await crud.list_decisions(session, repo_id, limit=8)
+ recent_decisions = [_decision_slim(d) for d in decisions]
+
+ # --- Sync status (last completed jobs + any active one) ---------------
+ job_rows = (
+ (
+ await session.execute(
+ select(GenerationJob)
+ .where(GenerationJob.repository_id == repo_id)
+ .order_by(GenerationJob.created_at.desc())
+ .limit(30)
+ )
+ )
+ .scalars()
+ .all()
+ )
+ last_sync_at: str | None = None
+ last_resync_at: str | None = None
+ last_sync_model: str | None = None
+ active_job_id: str | None = None
+ for j in job_rows:
+ try:
+ mode = json.loads(j.config_json or "{}").get("mode")
+ except Exception:
+ mode = None
+ if j.status in ("pending", "running") and active_job_id is None:
+ active_job_id = j.id
+ if j.status == "completed" and j.finished_at:
+ if mode == "full_resync" and last_resync_at is None:
+ last_resync_at = j.finished_at.isoformat()
+ elif mode != "full_resync" and last_sync_at is None:
+ last_sync_at = j.finished_at.isoformat()
+ last_sync_model = j.model_name or None
+
+ savings = await _savings_headline(repo.local_path)
+
+ return {
+ "repo": {
+ "id": repo.id,
+ "name": repo.name,
+ "local_path": repo.local_path,
+ "default_branch": repo.default_branch,
+ "head_commit": repo.head_commit,
+ "updated_at": repo.updated_at.isoformat() if repo.updated_at else None,
+ },
+ "stats": {
+ "file_count": file_count,
+ "symbol_count": symbol_count,
+ "entry_point_count": entry_point_count,
+ "doc_coverage_pct": doc_coverage_pct,
+ "freshness_score": freshness_score,
+ "dead_export_count": dead_export_count,
+ "hotspot_count": hotspot_count,
+ "silo_count": silo_count,
+ "module_count": module_count,
+ "deltas": deltas,
+ },
+ "health": {
+ "average_health": health_summary.get("average_health"),
+ "hotspot_health": hotspot_health,
+ "worst_performer_path": health_summary.get("worst_performer_path"),
+ "worst_performer_score": health_summary.get("worst_performer_score"),
+ "open_findings": health_summary.get("open_findings", 0),
+ "severity_breakdown": severity_breakdown,
+ "last_indexed_at": last_indexed_at,
+ "snapshot_count": len(snapshots),
+ "history": [
+ {
+ "taken_at": s.taken_at.isoformat() if s.taken_at else None,
+ "average_health": round(float(s.average_health), 2),
+ "hotspot_health": round(float(s.hotspot_health), 2),
+ }
+ for s in snapshots[-12:]
+ ],
+ },
+ "languages": languages,
+ "attention": attention,
+ "onboarding_targets": knowledge.get("onboarding_targets", []),
+ "top_hotspots": top_hotspots,
+ "recent_decisions": recent_decisions,
+ "savings": savings,
+ "sync": {
+ "last_sync_at": last_sync_at,
+ "last_resync_at": last_resync_at,
+ "last_sync_model": last_sync_model,
+ "active_job_id": active_job_id,
+ "page_count": total_pages,
+ },
+ }
diff --git a/packages/server/src/repowise/server/routers/owners.py b/packages/server/src/repowise/server/routers/owners.py
index 57c02455e..3b211c0ca 100644
--- a/packages/server/src/repowise/server/routers/owners.py
+++ b/packages/server/src/repowise/server/routers/owners.py
@@ -21,6 +21,7 @@ from repowise.server.schemas import (
OwnerProfileResponse,
Paginated,
)
+from repowise.server.schemas.ownership import OwnerAgentCollab
from repowise.server.services.owner_profile import (
_OwnerAccumulator,
aggregate_owners,
@@ -110,6 +111,19 @@ def _to_profile(acc: _OwnerAccumulator, module_totals: dict[str, int]) -> OwnerP
)
)
+ agent_collab: OwnerAgentCollab | None = None
+ if acc.owned_attributed_commits > 0 or acc.owned_agent_commits > 0:
+ agent_collab = OwnerAgentCollab(
+ files_with_agent_commits=acc.owned_files_with_agents,
+ agent_commit_count=acc.owned_agent_commits,
+ agent_share_pct=(
+ acc.owned_agent_commits / acc.owned_attributed_commits * 100.0
+ if acc.owned_attributed_commits
+ else None
+ ),
+ tier_counts=dict(acc.owned_agent_tier_counts),
+ )
+
return OwnerProfileResponse(
key=acc.key,
name=acc.name,
@@ -127,8 +141,11 @@ def _to_profile(acc: _OwnerAccumulator, module_totals: dict[str, int]) -> OwnerP
lines_deleted_90d_est=int(acc.lines_deleted_90d_est),
modules=modules,
top_files=top_files,
+ files_touched_total=len(acc.files_touched),
co_authors=co_authors,
+ co_authors_total=len(acc.coauthor_shared),
commit_categories=dict(acc.commit_categories),
+ agent_collab=agent_collab,
)
diff --git a/packages/server/src/repowise/server/routers/pages.py b/packages/server/src/repowise/server/routers/pages.py
index 23323eca9..261837354 100644
--- a/packages/server/src/repowise/server/routers/pages.py
+++ b/packages/server/src/repowise/server/routers/pages.py
@@ -7,10 +7,12 @@ parameter greedily matches the suffix as part of the page_id.
from __future__ import annotations
+from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi import APIRouter, Depends, HTTPException, Query
from repowise.core.persistence import crud
+from repowise.core.persistence.models import _now_utc
from repowise.server.deps import get_db_session, verify_api_key
from repowise.server.schemas import PageResponse, PageVersionResponse
@@ -73,6 +75,30 @@ async def get_page_versions_by_query(
return [PageVersionResponse.from_orm(v) for v in versions]
+class PageNotesUpdate(BaseModel):
+ """PATCH body for /lookup/notes. ``None`` clears the note."""
+
+ human_notes: str | None = None
+
+
[email protected]("/lookup/notes", response_model=PageResponse)
+async def update_page_notes(
+ body: PageNotesUpdate,
+ page_id: str = Query(..., description="Page ID"),
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> PageResponse:
+ """Set or clear the human-curated note pinned above a page's generated
+ content. Notes survive regeneration, so this never touches versions."""
+ page = await crud.get_page(session, page_id)
+ if page is None:
+ raise HTTPException(status_code=404, detail="Page not found")
+ note = (body.human_notes or "").strip()
+ page.human_notes = note or None
+ page.updated_at = _now_utc()
+ await session.flush()
+ return PageResponse.from_orm(page)
+
+
@router.post("/lookup/regenerate", status_code=202)
async def regenerate_page_by_query(
page_id: str = Query(..., description="Page ID"),
diff --git a/packages/server/src/repowise/server/routers/symbols.py b/packages/server/src/repowise/server/routers/symbols.py
index 30c12bd06..e8485a62a 100644
--- a/packages/server/src/repowise/server/routers/symbols.py
+++ b/packages/server/src/repowise/server/routers/symbols.py
@@ -4,11 +4,18 @@ from __future__ import annotations
from typing import Literal
+from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
-from fastapi import APIRouter, Depends, HTTPException, Query
-from repowise.core.persistence.models import GitMetadata, GraphNode, WikiSymbol
+from repowise.core.persistence import crud
+from repowise.core.persistence.decision_graph import get_governing_decisions
+from repowise.core.persistence.models import (
+ GitFunctionBlame,
+ GitMetadata,
+ GraphNode,
+ WikiSymbol,
+)
from repowise.server.deps import get_db_session, verify_api_key
from repowise.server.schemas import Paginated, SymbolImportanceComponents, SymbolResponse
from repowise.server.services.symbol_ranking import (
@@ -51,6 +58,32 @@ def _attach_signals(
return response
+async def _attach_blame(
+ session: AsyncSession, repo_id: str, items: list[SymbolResponse]
+) -> list[SymbolResponse]:
+ """Join the page's symbols against git_function_blame in one query."""
+ ids = [s.symbol_id for s in items]
+ if not ids:
+ return items
+ rows = await session.execute(
+ select(GitFunctionBlame).where(
+ GitFunctionBlame.repository_id == repo_id,
+ GitFunctionBlame.symbol_id.in_(ids),
+ )
+ )
+ by_id = {b.symbol_id: b for b in rows.scalars().all()}
+ for s in items:
+ b = by_id.get(s.symbol_id)
+ if b is None:
+ continue
+ s.blame_mod_count = b.mod_count
+ s.blame_recent_mod_count = b.recent_mod_count
+ s.blame_median_author_time = b.median_author_time
+ s.blame_owner_name = b.owner_name
+ s.blame_owner_line_pct = b.owner_line_pct
+ return items
+
+
async def _file_signals(
session: AsyncSession, repo_id: str, paths: set[str]
) -> tuple[dict[str, tuple[float, bool]], dict[str, tuple[float | None, bool | None]]]:
@@ -68,8 +101,7 @@ async def _file_signals(
)
)
pagerank_map: dict[str, tuple[float, bool]] = {
- row.node_id: (float(row.pagerank or 0.0), bool(row.is_entry_point))
- for row in pagerank_rows
+ row.node_id: (float(row.pagerank or 0.0), bool(row.is_entry_point)) for row in pagerank_rows
}
churn_rows = await session.execute(
@@ -187,9 +219,7 @@ async def search_symbols(
base = base.order_by(WikiSymbol.complexity_estimate.desc(), WikiSymbol.name)
elif sort == "kind":
base = base.order_by(WikiSymbol.kind, WikiSymbol.name)
- rows = (
- await session.execute(base.limit(limit).offset(offset))
- ).scalars().all()
+ rows = (await session.execute(base.limit(limit).offset(offset))).scalars().all()
paths = {s.file_path for s in rows}
pagerank_map, churn_map = await _file_signals(session, repo_id, paths)
items = []
@@ -216,6 +246,7 @@ async def search_symbols(
)
)
+ items = await _attach_blame(session, repo_id, items)
next_offset = offset + limit if offset + limit < total else None
return Paginated[SymbolResponse](
items=items,
@@ -225,6 +256,118 @@ async def search_symbols(
)
+async def symbol_detail(
+ repo_id: str = Query(..., description="Repository ID"),
+ symbol_id: str = Query(..., description="Symbol ID ({path}::{name})"),
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+) -> dict:
+ """Everything the symbol entity page renders, in one call.
+
+ Symbol row + function blame + callers/callees + graph metrics +
+ governing decisions + parent-file context.
+ """
+ result = await session.execute(
+ select(WikiSymbol).where(
+ WikiSymbol.repository_id == repo_id,
+ WikiSymbol.symbol_id == symbol_id,
+ )
+ )
+ sym = result.scalar_one_or_none()
+ if sym is None:
+ raise HTTPException(status_code=404, detail=f"Symbol not found: {symbol_id}")
+
+ symbol = SymbolResponse.from_orm(sym)
+ pagerank_map, churn_map = await _file_signals(session, repo_id, {sym.file_path})
+ pr, ep = pagerank_map.get(sym.file_path, (0.0, False))
+ components = compute_components(
+ file_pagerank=pr,
+ visibility=sym.visibility,
+ complexity=sym.complexity_estimate,
+ kind=sym.kind,
+ is_entry_point=ep,
+ )
+ churn, hot = churn_map.get(sym.file_path, (None, None))
+ symbol = _attach_signals(
+ symbol,
+ pagerank=pr,
+ is_entry_point=ep,
+ churn_percentile=churn,
+ is_hotspot=hot,
+ components=components,
+ score=components.score(),
+ )
+ [symbol] = await _attach_blame(session, repo_id, [symbol])
+
+ # Callers/callees from the symbol graph (call + heritage edges).
+ callers: list[dict] = []
+ callees: list[dict] = []
+ node = await crud.get_graph_node(session, repo_id, symbol_id)
+ if node is not None:
+ edges = await crud.get_graph_edges_for_node(
+ session, repo_id, symbol_id, direction="both", limit=40
+ )
+ other_ids = {
+ e.source_node_id if e.source_node_id != symbol_id else e.target_node_id for e in edges
+ }
+ node_map = await crud.get_graph_nodes_by_ids(session, repo_id, list(other_ids))
+ for e in edges:
+ inbound = e.target_node_id == symbol_id
+ other_id = e.source_node_id if inbound else e.target_node_id
+ other = node_map.get(other_id)
+ entry = {
+ "symbol_id": other_id,
+ "name": other.name
+ if other and other.name
+ else (other_id.split("::")[-1] if "::" in other_id else other_id),
+ "kind": other.kind if other else "unknown",
+ "file": other.file_path
+ if other and other.file_path
+ else (other_id.split("::")[0] if "::" in other_id else other_id),
+ "start_line": other.start_line if other else None,
+ "edge_type": e.edge_type or "calls",
+ "confidence": round(e.confidence or 0.0, 3),
+ }
+ (callers if inbound else callees).append(entry)
+ callers.sort(key=lambda x: (-x["confidence"], x["name"]))
+ callees.sort(key=lambda x: (-x["confidence"], x["name"]))
+
+ degrees = (
+ await crud.get_node_degree_counts(session, repo_id, symbol_id)
+ if node is not None
+ else {"in_degree": 0, "out_degree": 0}
+ )
+
+ governing = [
+ {"id": d.id, "title": d.title, "status": d.status}
+ for d in await get_governing_decisions(session, repo_id, symbol_id)
+ ]
+
+ # Parent-file context for the "open file page" affordance.
+ file_metrics = await crud.get_health_metrics(session, repo_id, file_paths=[sym.file_path])
+ git_meta = await crud.get_git_metadata(session, repo_id, sym.file_path)
+ file_context = {
+ "file_path": sym.file_path,
+ "health_score": round(file_metrics[0].score, 2) if file_metrics else None,
+ "is_hotspot": bool(git_meta.is_hotspot) if git_meta else None,
+ "primary_owner": git_meta.primary_owner_name if git_meta else None,
+ "language": sym.language,
+ }
+
+ return {
+ "symbol": symbol.model_dump(mode="json"),
+ "graph": {
+ "pagerank": round((node.pagerank if node else 0.0) or 0.0, 6),
+ "in_degree": degrees["in_degree"],
+ "out_degree": degrees["out_degree"],
+ "callers": callers,
+ "callees": callees,
+ },
+ "governing_decisions": governing,
+ "file_context": file_context,
+ }
+
+
@router.get("/by-name/{name}", response_model=list[SymbolResponse])
async def lookup_by_name(
name: str,
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index 0a30d4085..4b79029d7 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -57,7 +57,13 @@ from .decisions import (
DecisionRecordResponse,
DecisionStatusUpdate,
)
+from .external_systems import (
+ ExternalSystemEntry,
+ ExternalSystemsResponse,
+)
from .git import (
+ AgentTrendBucket,
+ AgentTrendResponse,
CommitDetailResponse,
CommitResponse,
GitMetadataResponse,
@@ -102,6 +108,8 @@ from .intelligence import (
SymbolNodeSummary,
)
from .ownership import (
+ GoverningDecisionRef,
+ OwnerAgentCollab,
KnowledgeMapOwner,
KnowledgeMapResponse,
KnowledgeMapSilo,
@@ -164,6 +172,8 @@ from .workspace import (
)
__all__ = [
+ "AgentTrendBucket",
+ "AgentTrendResponse",
"ArchEdgeResponse",
"ArchLayerResponse",
"ArchNodeResponse",
@@ -221,6 +231,8 @@ __all__ = [
"EgoGraphResponse",
"ExecutionFlowEntry",
"ExecutionFlowsResponse",
+ "ExternalSystemEntry",
+ "ExternalSystemsResponse",
"GitMetadataResponse",
"GitSummaryResponse",
"GraphEdgeResponse",
@@ -238,12 +250,14 @@ __all__ = [
"KnowledgeMapTarget",
"ModuleEdgeResponse",
"ModuleGraphResponse",
+ "GoverningDecisionRef",
"ModuleHealthDetail",
"ModuleHealthOwner",
"ModuleHealthSummary",
"ModuleNodeResponse",
"NeighboringCommunity",
"NodeSearchResult",
+ "OwnerAgentCollab",
"OwnerCoAuthor",
"OwnerFileEntry",
"OwnerListEntry",
diff --git a/packages/server/src/repowise/server/schemas/decisions.py b/packages/server/src/repowise/server/schemas/decisions.py
index d4b5b3f2b..bc6941fce 100644
--- a/packages/server/src/repowise/server/schemas/decisions.py
+++ b/packages/server/src/repowise/server/schemas/decisions.py
@@ -8,6 +8,16 @@ from datetime import datetime
from pydantic import BaseModel
+class EvidencePreview(BaseModel):
+ """The top-ranked evidence row, slimmed for list rows."""
+
+ source: str
+ source_quote: str
+ verification: str
+ evidence_file: str | None = None
+ evidence_line: int | None = None
+
+
class DecisionRecordResponse(BaseModel):
id: str
repository_id: str
@@ -32,6 +42,12 @@ class DecisionRecordResponse(BaseModel):
last_code_change: datetime | None
created_at: datetime
updated_at: datetime
+ # List-row evidence preview: the top-ranked evidence row's verbatim quote
+ # plus how many evidence rows back the record. Populated by the list
+ # endpoint only (None on detail/graph responses, which have the full
+ # /evidence endpoint instead).
+ evidence_count: int | None = None
+ evidence_preview: EvidencePreview | None = None
@classmethod
def from_orm(cls, obj: object) -> DecisionRecordResponse:
diff --git a/packages/server/src/repowise/server/schemas/external_systems.py b/packages/server/src/repowise/server/schemas/external_systems.py
new file mode 100644
index 000000000..a40754d67
--- /dev/null
+++ b/packages/server/src/repowise/server/schemas/external_systems.py
@@ -0,0 +1,28 @@
+"""Dependency-registry response models (``external_systems`` table)."""
+
+from __future__ import annotations
+
+from pydantic import BaseModel
+
+
+class ExternalSystemEntry(BaseModel):
+ """One declared third-party dependency."""
+
+ name: str
+ display_name: str
+ ecosystem: str # npm | pypi | cargo | gomod | nuget | ...
+ category: str # framework | service | tool | library
+ version: str | None = None
+ declared_in: str # manifest path, e.g. "packages/web/package.json"
+ is_dev_dep: bool = False
+
+
+class ExternalSystemsResponse(BaseModel):
+ """The full dependency registry for a repository."""
+
+ items: list[ExternalSystemEntry]
+ total: int
+ prod_count: int
+ dev_count: int
+ ecosystems: list[str]
+ manifests: list[str]
diff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.py
index 9fe96eabb..b0495d5fe 100644
--- a/packages/server/src/repowise/server/schemas/git.py
+++ b/packages/server/src/repowise/server/schemas/git.py
@@ -170,6 +170,18 @@ class CommitResponse(BaseModel):
# Repo-relative normalization (the portable signal).
risk_percentile: float
review_priority: str
+ # The dominant risk driver, surfaced on rows so reviewers don't have to
+ # open every detail sheet. Recomputed deterministically from the stored
+ # Kamei features; None when the commit was never risk-scored.
+ top_driver: str | None = None
+ # Cumulative prior-commit count at commit time. Low values flag a
+ # new-to-this-repo contributor.
+ author_experience: int | None = None
+ # Agent provenance (deterministic local-git attribution channels).
+ # agent_name is None for human-authored commits.
+ agent_name: str | None = None
+ agent_autonomy_tier: int | None = None
+ agent_confidence: str | None = None
class RiskDriverResponse(BaseModel):
@@ -184,5 +196,25 @@ class RiskDriverResponse(BaseModel):
class CommitDetailResponse(CommitResponse):
"""A single commit with its full, attributable risk-driver breakdown."""
- author_experience: int | None = None
drivers: list[RiskDriverResponse] = []
+ agent_channel: str | None = None
+
+
+class AgentTrendBucket(BaseModel):
+ """One month of agent-vs-human commit volume."""
+
+ month: str # "YYYY-MM"
+ total_commits: int
+ agent_commits: int
+ agent_pct: float # 0-100
+ tier_counts: dict = {}
+
+
+class AgentTrendResponse(BaseModel):
+ """Monthly agent-share trend across the indexed commit window."""
+
+ buckets: list[AgentTrendBucket]
+ total_commits: int
+ agent_commits: int
+ agent_pct: float # 0-100 across the whole window
+ agent_names: list[dict] = [] # [{name, count}] descending
diff --git a/packages/server/src/repowise/server/schemas/ownership.py b/packages/server/src/repowise/server/schemas/ownership.py
index 8fb8ecab7..a11ebcce5 100644
--- a/packages/server/src/repowise/server/schemas/ownership.py
+++ b/packages/server/src/repowise/server/schemas/ownership.py
@@ -72,6 +72,22 @@ class OwnerCoAuthor(BaseModel):
co_change_strength: float # 0-1 fraction
+class OwnerAgentCollab(BaseModel):
+ """How much coding-agent activity lands on the files this person owns.
+
+ Aggregated from the per-file agent-provenance rollup (GitMetadata) over
+ the owner's primary-owned files — agent identity per commit lives on the
+ commits surface, the per-file rollup only carries counts and tiers.
+ """
+
+ files_with_agent_commits: int
+ agent_commit_count: int
+ # Commit-weighted share of agent-attributed commits across owned files,
+ # 0-100. None when no owned file has a provenance-aware rollup yet.
+ agent_share_pct: float | None
+ tier_counts: dict = {}
+
+
class OwnerProfileResponse(BaseModel):
key: str
name: str
@@ -94,14 +110,21 @@ class OwnerProfileResponse(BaseModel):
lines_added_90d_est: int
lines_deleted_90d_est: int
- # Breakdowns
+ # Breakdowns. top_files / co_authors are capped server-side; the
+ # *_total fields carry the uncapped counts so the UI can render honest
+ # "+N more" indicators instead of implying the list is complete.
modules: list[OwnerModuleRollup]
top_files: list[OwnerFileEntry]
+ files_touched_total: int = 0
co_authors: list[OwnerCoAuthor]
+ co_authors_total: int = 0
# Commit-category mix across files they touch (sum of categories).
commit_categories: dict
+ # Agent collaboration on owned files (None when nothing is attributed).
+ agent_collab: OwnerAgentCollab | None = None
+
class ModuleHealthOwner(BaseModel):
name: str
@@ -132,12 +155,20 @@ class ModuleHealthSummary(BaseModel):
health_score: float
+class GoverningDecisionRef(BaseModel):
+ """Slim decision reference so lists can render titles, not UUIDs."""
+
+ id: str
+ title: str
+ status: str
+
+
class ModuleHealthDetail(ModuleHealthSummary):
"""Single-module deep view with breakdowns."""
owners: list[ModuleHealthOwner]
top_hotspots: list[str]
- governing_decisions: list[str] # decision ids
+ governing_decisions: list[GoverningDecisionRef]
contributor_count: int
diff --git a/packages/server/src/repowise/server/schemas/symbols.py b/packages/server/src/repowise/server/schemas/symbols.py
index 6e918719a..89e19f478 100644
--- a/packages/server/src/repowise/server/schemas/symbols.py
+++ b/packages/server/src/repowise/server/schemas/symbols.py
@@ -42,6 +42,13 @@ class SymbolResponse(BaseModel):
is_entry_point: bool | None = None
file_churn_percentile: float | None = None
file_is_hotspot: bool | None = None
+ # Function-blame join (populated by the list endpoint from
+ # git_function_blame when a row exists for the symbol; null otherwise).
+ blame_mod_count: int | None = None
+ blame_recent_mod_count: int | None = None
+ blame_median_author_time: int | None = None
+ blame_owner_name: str | None = None
+ blame_owner_line_pct: float | None = None
@classmethod
def from_orm(cls, obj: object) -> SymbolResponse:
diff --git a/packages/server/src/repowise/server/services/owner_profile.py b/packages/server/src/repowise/server/services/owner_profile.py
index 929118277..66925a9aa 100644
--- a/packages/server/src/repowise/server/services/owner_profile.py
+++ b/packages/server/src/repowise/server/services/owner_profile.py
@@ -99,6 +99,12 @@ class _OwnerAccumulator:
dead_code_files: set[str] = field(default_factory=set)
dead_code_lines: int = 0
+ # Agent-provenance rollup across primary-owned files.
+ owned_files_with_agents: int = 0
+ owned_agent_commits: int = 0
+ owned_attributed_commits: int = 0 # total commits on owned files with a rollup
+ owned_agent_tier_counts: Counter[str] = field(default_factory=Counter)
+
# co-author tally: other_key -> shared file count
coauthor_shared: Counter[str] = field(default_factory=Counter)
coauthor_meta: dict[str, tuple[str, str | None]] = field(default_factory=dict)
@@ -217,6 +223,21 @@ async def aggregate_owners(
primary.module_hotspots[module] += 1
if (m.bus_factor or 0) <= 1:
primary.bus_factor_risk_files += 1
+ # Agent collaboration: how much agent activity lands on the
+ # files this person owns. agent_authored_pct is None for rows
+ # persisted before the provenance-aware index ran — skip those
+ # so the share stays honest.
+ if m.agent_authored_pct is not None:
+ primary.owned_attributed_commits += m.commit_count_total or 0
+ if (m.agent_commit_count or 0) > 0:
+ primary.owned_files_with_agents += 1
+ primary.owned_agent_commits += m.agent_commit_count or 0
+ try:
+ tiers = json.loads(m.agent_tier_counts_json or "{}")
+ except json.JSONDecodeError:
+ tiers = {}
+ for tier, n in tiers.items():
+ primary.owned_agent_tier_counts[str(tier)] += int(n)
# Co-author tally — each pair of distinct touchers shares this file.
for i, a in enumerate(touchers):
diff --git a/packages/types/package.json b/packages/types/package.json
index 9a4803beb..4684bd510 100644
--- a/packages/types/package.json
+++ b/packages/types/package.json
@@ -22,7 +22,10 @@
"./settings": "./src/settings.ts",
"./security": "./src/security.ts",
"./owners": "./src/owners.ts",
- "./modules": "./src/modules.ts"
+ "./modules": "./src/modules.ts",
+ "./overview": "./src/overview.ts",
+ "./files": "./src/files.ts",
+ "./external-systems": "./src/external-systems.ts"
},
"publishConfig": {
"registry": "https://npm.pkg.github.com",
diff --git a/packages/types/src/decisions.ts b/packages/types/src/decisions.ts
index 63abb9e1a..2af5ec983 100644
--- a/packages/types/src/decisions.ts
+++ b/packages/types/src/decisions.ts
@@ -44,6 +44,19 @@ export interface DecisionRecord {
verification?: DecisionVerification;
created_at: string;
updated_at: string;
+ /** Number of evidence rows backing the record. List endpoint only. */
+ evidence_count?: number | null;
+ /** Top-ranked evidence row, slimmed for list rows. List endpoint only. */
+ evidence_preview?: EvidencePreview | null;
+}
+
+/** The top-ranked evidence row, slimmed for decision list rows. */
+export interface EvidencePreview {
+ source: string;
+ source_quote: string;
+ verification: DecisionVerification;
+ evidence_file?: string | null;
+ evidence_line?: number | null;
}
export interface DecisionCreateInput {
diff --git a/packages/types/src/external-systems.ts b/packages/types/src/external-systems.ts
new file mode 100644
index 000000000..abc865afc
--- /dev/null
+++ b/packages/types/src/external-systems.ts
@@ -0,0 +1,29 @@
+/**
+ * Dependency-registry types — the `external_systems` table populated by the
+ * manifest parsers during ingestion. Mirrors the Pydantic models served by
+ * `/api/repos/{id}/external-systems`.
+ */
+
+/** One declared third-party dependency. */
+export interface ExternalSystemEntry {
+ name: string;
+ display_name: string;
+ /** npm | pypi | cargo | gomod | nuget | ... */
+ ecosystem: string;
+ /** framework | service | tool | library */
+ category: string;
+ version: string | null;
+ /** Manifest path the dependency was declared in, e.g. "packages/web/package.json". */
+ declared_in: string;
+ is_dev_dep: boolean;
+}
+
+/** The full dependency registry for a repository. */
+export interface ExternalSystemsRegistry {
+ items: ExternalSystemEntry[];
+ total: number;
+ prod_count: number;
+ dev_count: number;
+ ecosystems: string[];
+ manifests: string[];
+}
diff --git a/packages/types/src/files.ts b/packages/types/src/files.ts
new file mode 100644
index 000000000..449d19158
--- /dev/null
+++ b/packages/types/src/files.ts
@@ -0,0 +1,179 @@
+/**
+ * File-detail contract — the aggregate behind the canonical file entity
+ * page (`GET /api/repos/{id}/files/{path}`). Mirrors the server's
+ * `routers/files.py` response shape.
+ */
+
+import type { CoChangePartner, FileAuthor, Hotspot, SignificantCommit } from "./git.js";
+
+export interface FileWikiPageRef {
+ id: string;
+ title: string;
+ summary: string;
+ content: string;
+ freshness_status: string;
+ confidence: number;
+ human_notes: string | null;
+ updated_at: string | null;
+}
+
+export interface FileHealthFinding {
+ id: string;
+ file_path: string;
+ biomarker_type: string;
+ severity: string;
+ function_name: string | null;
+ line_start: number | null;
+ line_end: number | null;
+ health_impact: number;
+ reason: string;
+ details: Record<string, unknown>;
+ status: string;
+}
+
+export interface FileHealthMetric {
+ file_path: string;
+ score: number;
+ max_ccn: number;
+ max_nesting: number;
+ nloc: number;
+ has_test_file: boolean;
+ line_coverage_pct: number | null;
+ module: string | null;
+ duplication_pct: number | null;
+}
+
+export interface FileScoreBreakdownFinding {
+ id: string;
+ biomarker_type: string;
+ severity: string;
+ raw_impact: number;
+ applied_impact: number;
+ function_name: string | null;
+ reason: string;
+}
+
+export interface FileScoreBreakdownCategory {
+ category: string;
+ cap: number;
+ raw_deduction: number;
+ applied_deduction: number;
+ capped: boolean;
+ finding_count: number;
+ findings: FileScoreBreakdownFinding[];
+}
+
+export interface FileScoreBreakdown {
+ score: number;
+ total_deduction: number;
+ categories: FileScoreBreakdownCategory[];
+}
+
+export interface FileDetailHealth {
+ metric: FileHealthMetric | null;
+ breakdown: FileScoreBreakdown | null;
+ findings: FileHealthFinding[];
+}
+
+export interface FileAgentProvenance {
+ agent_commit_count: number;
+ agent_authored_pct: number | null;
+ tier_counts: Record<string, number>;
+}
+
+/** Hotspot row + history extras the detail endpoint joins in. */
+export interface FileDetailGit extends Hotspot {
+ significant_commits: SignificantCommit[];
+ top_authors: FileAuthor[];
+ co_change_partners: CoChangePartner[];
+ agent: FileAgentProvenance;
+ first_commit_at: string | null;
+}
+
+export interface FileDetailCoverage {
+ line_coverage_pct: number;
+ branch_coverage_pct: number | null;
+ total_coverable_lines: number;
+ covered_lines: number[];
+ source_format: string;
+ ingested_at: string | null;
+ ingested_commit_sha: string | null;
+}
+
+export interface FileGraphNeighbor {
+ node_id: string;
+ node_type: string;
+ language: string | null;
+ edge_type: string;
+ imported_names: string[];
+}
+
+export interface FileDetailGraph {
+ language: string;
+ is_entry_point: boolean;
+ is_test: boolean;
+ symbol_count: number;
+ pagerank: number;
+ pagerank_percentile: number;
+ in_degree: number;
+ out_degree: number;
+ community_id: number;
+ community_label: string | null;
+ dependents: FileGraphNeighbor[];
+ dependencies: FileGraphNeighbor[];
+}
+
+export interface FileSymbolSlim {
+ symbol_id: string;
+ name: string;
+ kind: string;
+ signature: string;
+ start_line: number;
+ end_line: number;
+ visibility: string;
+ complexity_estimate: number;
+ is_async: boolean;
+}
+
+export interface FunctionBlameRow {
+ symbol_id: string;
+ function_name: string;
+ start_line: number;
+ end_line: number;
+ line_count: number;
+ mod_count: number;
+ recent_mod_count: number;
+ median_author_time: number | null;
+ owner_name: string | null;
+ owner_email: string | null;
+ owner_line_pct: number | null;
+}
+
+export interface GoverningDecisionRef {
+ id: string;
+ title: string;
+ status: string;
+}
+
+export interface FileDeadCodeFinding {
+ id: string;
+ kind: string;
+ symbol_name: string | null;
+ confidence: number;
+ reason: string;
+ lines: number;
+ safe_to_delete: boolean;
+}
+
+export interface FileDetailResponse {
+ file_path: string;
+ wiki_page: FileWikiPageRef | null;
+ health: FileDetailHealth;
+ git: FileDetailGit | null;
+ coverage: FileDetailCoverage | null;
+ graph: FileDetailGraph | null;
+ symbols: FileSymbolSlim[];
+ function_blame: FunctionBlameRow[];
+ governing_decisions: GoverningDecisionRef[];
+ dead_code: FileDeadCodeFinding[];
+}
diff --git a/packages/types/src/git.ts b/packages/types/src/git.ts
index 37176b602..0833e78a5 100644
--- a/packages/types/src/git.ts
+++ b/packages/types/src/git.ts
@@ -130,6 +130,18 @@ export interface Commit {
risk_percentile: number;
/** Repo-relative review priority (the portable ranking signal). */
review_priority: ReviewPriority;
+ /** Label of the dominant risk driver, so rows explain themselves without
+ * opening the detail sheet. Null when the commit was never risk-scored. */
+ top_driver?: string | null;
+ /** Author's cumulative prior-commit count at the time of the commit.
+ * Low values flag a new-to-this-repo contributor. */
+ author_experience?: number | null;
+ /** Coding-agent attribution (deterministic local-git channels).
+ * Null/undefined for human-authored commits. */
+ agent_name?: string | null;
+ /** 1 = near-autonomous bot, 2 = human-driven agent, 3 = assisted/co-authored. */
+ agent_autonomy_tier?: number | null;
+ agent_confidence?: string | null;
}
/** One feature's signed contribution to a commit's change-risk logit. */
@@ -142,10 +154,28 @@ export interface RiskDriver {
}
export interface CommitDetail extends Commit {
- /** Author's cumulative prior-commit count at the time of the commit. */
- author_experience?: number | null;
/** Per-feature breakdown, strongest contribution first. */
drivers: RiskDriver[];
+ /** Which attribution channel identified the agent (e.g. git footer). */
+ agent_channel?: string | null;
+}
+
+/** One month of agent-vs-human commit volume. */
+export interface AgentTrendBucket {
+ month: string; // "YYYY-MM"
+ total_commits: number;
+ agent_commits: number;
+ agent_pct: number; // 0-100
+ tier_counts: Record<string, number>;
+}
+
+/** Monthly agent-share trend across the indexed commit window. */
+export interface AgentTrend {
+ buckets: AgentTrendBucket[];
+ total_commits: number;
+ agent_commits: number;
+ agent_pct: number; // 0-100
+ agent_names: { name: string; count: number }[];
}
export interface OwnershipEntry {
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 6d586c35d..7befaeb20 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -22,3 +22,6 @@ export * from "./settings.js";
export * from "./security.js";
export * from "./owners.js";
export * from "./modules.js";
+export * from "./overview.js";
+export * from "./files.js";
+export * from "./external-systems.js";
diff --git a/packages/types/src/modules.ts b/packages/types/src/modules.ts
index 3b13e3bfd..4dcab0898 100644
--- a/packages/types/src/modules.ts
+++ b/packages/types/src/modules.ts
@@ -31,10 +31,17 @@ export interface ModuleHealthSummary {
health_score: number;
}
+export interface ModuleGoverningDecision {
+ id: string;
+ title: string;
+ status: string;
+}
+
export interface ModuleHealthDetail extends ModuleHealthSummary {
owners: ModuleHealthOwner[];
top_hotspots: string[];
- governing_decisions: string[];
+ /** Title-bearing refs from current backends; bare ids from older ones. */
+ governing_decisions: (ModuleGoverningDecision | string)[];
contributor_count: number;
}
diff --git a/packages/types/src/overview.ts b/packages/types/src/overview.ts
new file mode 100644
index 000000000..5d041876c
--- /dev/null
+++ b/packages/types/src/overview.ts
@@ -0,0 +1,120 @@
+/**
+ * Overview-summary contract — the one-call payload behind the repo
+ * Overview page (`GET /api/repos/{id}/overview-summary`). Mirrors the
+ * server's `routers/overview.py` response shape.
+ */
+
+import type { Hotspot } from "./git.js";
+
+export interface OverviewRepoMeta {
+ id: string;
+ name: string;
+ local_path: string;
+ default_branch: string;
+ head_commit: string | null;
+ updated_at: string | null;
+}
+
+export interface OverviewStatDeltas {
+ average_health: number | null;
+ hotspot_health: number | null;
+ file_count: number | null;
+}
+
+export interface OverviewStats {
+ file_count: number;
+ symbol_count: number;
+ entry_point_count: number;
+ doc_coverage_pct: number;
+ freshness_score: number;
+ dead_export_count: number;
+ hotspot_count: number;
+ silo_count: number;
+ module_count: number;
+ deltas: OverviewStatDeltas;
+}
+
+export interface OverviewHealthHistoryPoint {
+ taken_at: string | null;
+ average_health: number;
+ hotspot_health: number;
+}
+
+export interface OverviewHealth {
+ average_health: number | null;
+ hotspot_health: number | null;
+ worst_performer_path: string | null;
+ worst_performer_score: number | null;
+ open_findings: number;
+ severity_breakdown: Record<string, number>;
+ last_indexed_at: string | null;
+ snapshot_count: number;
+ history: OverviewHealthHistoryPoint[];
+}
+
+export interface OverviewLanguage {
+ language: string;
+ file_count: number;
+}
+
+export type OverviewAttentionType =
+ | "stale_decision"
+ | "proposed_decision"
+ | "ungoverned_hotspot"
+ | "knowledge_silo"
+ | "dead_code";
+
+export interface OverviewAttentionItem {
+ id: string;
+ type: OverviewAttentionType;
+ title: string;
+ description: string;
+ severity: "high" | "medium" | "low";
+ /** Decision id, file path, … — what the item points at. */
+ target_id: string;
+}
+
+export interface OverviewOnboardingTarget {
+ path: string;
+ pagerank: number;
+ doc_words: number;
+}
+
+export interface OverviewDecisionSlim {
+ id: string;
+ title: string;
+ status: string;
+ source: string | null;
+ created_at: string | null;
+ staleness_score: number;
+}
+
+export interface OverviewSavings {
+ available: boolean;
+ saved_tokens?: number;
+ mcp_tokens?: number;
+ total_saved_tokens?: number;
+ estimated_usd_saved?: number;
+ pricing_model?: string;
+}
+
+export interface OverviewSyncStatus {
+ last_sync_at: string | null;
+ last_resync_at: string | null;
+ last_sync_model: string | null;
+ active_job_id: string | null;
+ page_count: number;
+}
+
+export interface OverviewSummaryResponse {
+ repo: OverviewRepoMeta;
+ stats: OverviewStats;
+ health: OverviewHealth;
+ languages: OverviewLanguage[];
+ attention: OverviewAttentionItem[];
+ onboarding_targets: OverviewOnboardingTarget[];
+ top_hotspots: Hotspot[];
+ recent_decisions: OverviewDecisionSlim[];
+ savings: OverviewSavings;
+ sync: OverviewSyncStatus;
+}
diff --git a/packages/types/src/owners.ts b/packages/types/src/owners.ts
index 6d5fb7299..dc8568c12 100644
--- a/packages/types/src/owners.ts
+++ b/packages/types/src/owners.ts
@@ -63,6 +63,22 @@ export interface OwnerProfile {
lines_deleted_90d_est: number;
modules: OwnerModuleRollup[];
top_files: OwnerFileEntry[];
+ /** Uncapped count behind the top_files slice (for "+N more"). */
+ files_touched_total?: number;
co_authors: OwnerCoAuthor[];
+ /** Uncapped count behind the co_authors slice (for "+N more"). */
+ co_authors_total?: number;
commit_categories: Record<string, number>;
+ /** Agent activity on this person's owned files; null when none attributed. */
+ agent_collab?: OwnerAgentCollab | null;
+}
+
+/** How much coding-agent activity lands on the files this person owns. */
+export interface OwnerAgentCollab {
+ files_with_agent_commits: number;
+ agent_commit_count: number;
+ /** Commit-weighted agent share across owned files, 0–100; null when no
+ * owned file has a provenance-aware rollup yet. */
+ agent_share_pct: number | null;
+ tier_counts: Record<string, number>;
}
diff --git a/packages/types/src/symbols.ts b/packages/types/src/symbols.ts
index 6ccf121db..f505e7cb2 100644
--- a/packages/types/src/symbols.ts
+++ b/packages/types/src/symbols.ts
@@ -60,6 +60,50 @@ export interface CodeSymbol {
is_entry_point?: boolean | null;
file_churn_percentile?: number | null;
file_is_hotspot?: boolean | null;
+ /** Function-blame join — populated by the list/detail endpoints when a
+ * git_function_blame row exists for the symbol. */
+ blame_mod_count?: number | null;
+ blame_recent_mod_count?: number | null;
+ blame_median_author_time?: number | null;
+ blame_owner_name?: string | null;
+ blame_owner_line_pct?: number | null;
+}
+
+// ---------------------------------------------------------------------------
+// Symbol detail (the symbol entity page aggregate)
+// ---------------------------------------------------------------------------
+
+export interface SymbolCallEntry {
+ symbol_id: string;
+ name: string;
+ kind: string;
+ file: string;
+ start_line: number | null;
+ edge_type: string;
+ confidence: number;
+}
+
+export interface SymbolDetailGraph {
+ pagerank: number;
+ in_degree: number;
+ out_degree: number;
+ callers: SymbolCallEntry[];
+ callees: SymbolCallEntry[];
+}
+
+export interface SymbolFileContext {
+ file_path: string;
+ health_score: number | null;
+ is_hotspot: boolean | null;
+ primary_owner: string | null;
+ language: string;
+}
+
+export interface SymbolDetailResponse {
+ symbol: CodeSymbol;
+ graph: SymbolDetailGraph;
+ governing_decisions: { id: string; title: string; status: string }[];
+ file_context: SymbolFileContext;
}
export interface SymbolList {
diff --git a/packages/ui/COMPONENT_CONTRACTS.md b/packages/ui/COMPONENT_CONTRACTS.md
index 3479bd0fd..60b3e1620 100644
--- a/packages/ui/COMPONENT_CONTRACTS.md
+++ b/packages/ui/COMPONENT_CONTRACTS.md
@@ -29,15 +29,80 @@ component definition.
---
-## `shared/api-error` — `ApiError`
+## `shared/api-error` — `ApiError`
Renders an inline error card with retry affordance.
| Prop | Type | Required | Notes |
|------|------|----------|-------|
-| `error` | `Error \| null \| undefined` | yes | Surfaced in the card; `null` / `undefined` renders nothing. |
+| `title` | `string` | no | Defaults to "Failed to load". |
+| `message` | `string` | no | Defaults to a generic fetch-error line. |
| `onRetry` | `() => void` | no | When provided, a "Retry" button is rendered. |
-| `className` | `string` | no | Forwarded to the outer container. |
+
+---
+
+## `shared/responsive-table` — `ResponsiveTable<T>`
+
+The shared table primitive with a column-priority API. Priority 1
+columns are always visible, priority 2 hide below `md`, priority 3
+hide below `lg`; the wrapper always provides `overflow-x-auto`, and
+`stacked` additionally collapses to a card list below `sm`/`md`.
+
+| Prop | Type | Required | Notes |
+|------|------|----------|-------|
+| `columns` | `ResponsiveColumn<T>[]` | yes | `{ key, header, render, priority?, align?, sortable?, mobileLabel?, mobileRender?, hideInCard?, headerClassName?, cellClassName? }`. |
+| `rows` | `T[]` | yes | |
+| `rowKey` | `(row: T) => string` | yes | |
+| `onRowClick` | `(row: T) => void` | no | Rows get pointer affordance when set. |
+| `selectedKey` | `string \| null` | no | Highlights the matching row. |
+| `sortField` / `sortOrder` / `onSort` | `string` / `"asc" \| "desc"` / `(key) => void` | no | Controlled sorting; header arrows render on the active column. |
+| `empty` | `ReactNode` | no | Rendered instead of the table when `rows` is empty (pass `EmptyState`). |
+| `stacked` | `"sm" \| "md"` | no | Collapse to stacked cards below the breakpoint. |
+| `bare` | `boolean` | no | Omit the rounded border + surface background (for card-embedded tables). |
+
+---
+
+## `shared/adaptive-panel` — `AdaptivePanel`
+
+One overlay surface: right-side slide-in panel on `md+`, bottom sheet
+with drag-handle swipe-dismiss on mobile. Radix Dialog under the hood.
+
+| Prop | Type | Required | Notes |
+|------|------|----------|-------|
+| `open` / `onOpenChange` | `boolean` / `(open) => void` | yes | Controlled. |
+| `title` | `ReactNode` | yes | Accessible name; rendered in the header unless `hideHeader`. |
+| `eyebrow` | `ReactNode` | no | Small uppercase label above the title. |
+| `widthClassName` | `string` | no | Desktop width; default `md:max-w-[520px]`. |
+| `sheetHeightClassName` | `string` | no | Mobile max height; default `max-h-[85dvh]`. |
+| `hideHeader` | `boolean` | no | Title goes `sr-only`; render your own header. |
+| `modal` | `boolean` | no | Default `true`. `false` keeps the page interactive behind the panel on desktop (chat artifact panel). |
+
+---
+
+## `shared/toast` — `Toaster`, `toast`
+
+Token-themed sonner toaster (`--z-toast`, surface/border/text tokens).
+Mount `Toaster` once at the app shell; fire toasts via the re-exported
+`toast`. Framework-neutral: the host passes the resolved theme.
+
+| Prop | Type | Required | Notes |
+|------|------|----------|-------|
+| `theme` | `"light" \| "dark"` | no | Default `dark`. |
+| `position` | sonner position union | no | Default `bottom-right`. |
+
+---
+
+## `shared/error-boundary` — `ErrorBoundary`
+
+Class-component boundary; default fallback renders `ApiError` with a
+retry that re-mounts the subtree.
+
+| Prop | Type | Required | Notes |
+|------|------|----------|-------|
+| `children` | `ReactNode` | yes | |
+| `fallback` | `(error, reset) => ReactNode` | no | Replaces the default ApiError fallback. |
+| `title` | `string` | no | Forwarded to the default fallback. |
+| `onError` | `(error, info) => void` | no | Reporting hook. |
---
@@ -67,7 +132,7 @@ Single-stat display tile.
| `trend` | `{ value: string; positive: boolean }` | no | Renders an up/down arrow next to the value. |
| `icon` | `React.ReactNode` | no | Right-aligned glyph. |
| `className` | `string` | no | Forwarded to the outer Card. |
-| `href` | `string` | no | Reserved for a follow-up routing prop; currently inert. |
+| `href` | `string` | no | Wraps the card in an `<a>`; hover affordance follows. |
---
@@ -107,6 +172,8 @@ Filterable table of `DecisionRecord` rows with status + source dropdowns.
| `filters` | `DecisionsTableFilters` | yes | Controlled. Caller mirrors these into fetch keys so filter changes drive a re-fetch. |
| `onFiltersChange` | `(filters: DecisionsTableFilters) => void` | yes | Fires on every dropdown change. |
| `repoId` | `string` | yes | Used to build the `/repos/{repoId}/decisions/{id}` link target for each row. |
+| `linkPrefix` | `string` | no | Overrides the `/repos/{repoId}` URL prefix. |
+| `LinkComponent` | `ElementType<{ href; className?; children }>` | no | Plug a router `<Link>`; defaults to `<a>`. |
| `error` | `unknown` | no | Truthy on a failed fetch; renders an inline retry message. |
| `isLoading` | `boolean` | no | Suppresses the "no decisions found" empty-state during the first fetch. |
| `onRetry` | `() => void` | no | Wired to the inline retry button when `error` is truthy. |
@@ -388,7 +455,20 @@ with `staleSince`, wraps in a tooltip exposing the date and confidence.
| `staleSince` | `string \| null` | no |
| `className` | `string` | no |
-## `wiki/git-history-panel` — `GitHistoryPanel`
+## `wiki/backlinks-panel` — `BacklinksPanel`
+
+Sidebar panel listing pages that link into the current page. Renders
+nothing when the backlink list is empty.
+
+| Prop | Type | Required | Notes |
+|------|------|----------|-------|
+| `backlinks` | `Backlink[]` (`wiki/wiki-links-types`) | yes | From `page.metadata.backlinks`. |
+| `repoId` | `string` | yes | |
+| `limit` | `number` | no | Default 6; remainder collapses to "+N more". |
+| `buildHref` | `(repoId, pageId) => string` | no | Default `/repos/{id}/wiki/{pageId}`. |
+| `renderLink` | `({ href, className, title, children }) => ReactNode` | no | Plug a router link; defaults to `<a>`. |
+
+## `wiki/git-history-panel` — `GitHistoryPanel`
Sidebar panel summarising file lifecycle, commit categories, top
authors with bars, co-change partners, and recent commits.
@@ -425,10 +505,12 @@ floating `GraphTooltip`. The `GraphContext` provider also lives here
so node/edge components can be consumed independently of the
`graph-flow` data-fetching host.
-`graph-flow` itself, plus the data-coupled panels (`graph-doc-panel`,
-`graph-community-panel`, `path-finder-panel`), still live in
-`packages/web` because they orchestrate `useGraph*` SWR hooks. They
-will move under a wrapper-pattern refactor in a follow-up.
+`graph-flow` and the panels (`graph-doc-panel`, `graph-community-panel`,
+`path-finder-panel`) live HERE as presentational shells; `packages/web`
+hosts thin wrappers that orchestrate the `useGraph*` SWR hooks and pass
+the datasets in. The canvas renders via Sigma (`graph/sigma/`), not
+`@xyflow/react` (the xyflow node/edge components remain for the module
+browser and embedded views).
### `graph/context` — `GraphContext`, `GraphProvider`, `useGraphContext`, `GraphContextValue`
@@ -517,19 +599,6 @@ Collapsible legend that picks a key per `colorMode`. Imports the
| `viewMode` | `ViewMode` | yes |
| `communityLabels` | `Map<number, string>` | no |
-### `graph/graph-ego-sidebar` — `GraphEgoSidebar`
-
-Right-edge sidebar showing the centre node's neighborhood — inbound
-/ outbound counts, git metadata (owner, last commit, 30d commits),
-and a list of neighbour nodes. Consumes the canonical `EgoGraph`
-type, which now optionally carries `center_git_meta: GitMetadata`.
-
-| Prop | Type | Required |
-|------|------|----------|
-| `graph` | `EgoGraph` (`@repowise-dev/types/graph`) | yes |
-| `onClose` | `() => void` | yes |
-| `onNavigateToNode` | `(nodeId: string) => void` | no |
-
---
## `workspace/*` — Multi-repo workspace views
@@ -592,11 +661,35 @@ deps, contract links, and contract count.
---
-## `dashboard/*` — Repo overview tiles
-
-Nine presentational tiles that consume canonical engine artifacts.
-The data-coupled trio (`active-job-banner`, `quick-actions`,
-`community-summary-grid`) stays in `packages/web` for now.
+## `dashboard/*` — Repo overview tiles
+
+Presentational tiles that consume canonical engine artifacts. The
+formerly data-coupled trio (`active-job-banner`, `quick-actions`,
+`community-summary-grid`) now lives here as shells (documented under
+"Phase 2C" below); their SWR wrappers live in `packages/web`.
+
+UX-overhaul additions: `dashboard/health-score-badge`
+(`HealthScoreBadge` — compact header twin of `HealthScoreRing`: score
+chip + code-health trend sparkline + click-toggled breakdown),
+`dashboard/where-to-start` (`WhereToStartCard` — onboarding targets,
+rows link to the canonical file pages), and `dashboard/commits-mini`
+(`CommitsMini` — recent-commits feed for the Overview Pulse tab; rows
+link to `/commits?commit=`). `SavingsMini` accepts the structural
+`SavingsMiniData` slice (the overview-summary savings headline fits);
+`DecisionsTimeline` accepts the structural `DecisionsTimelineItem`.
+
+## `files/*` — File entity page
+
+The canonical "everything about this file" page used by
+`/repos/[id]/files/<path>`. `FilePage` (client) assembles the header
+(path, health badge, signal chips, governing decisions) plus Doc /
+Health / History / Coverage / Graph tabs; per-tab components are
+exported individually. Data arrives as one `FileDetailResponse`
+(`@repowise-dev/types/files`); the host supplies `docSlot` (rendered
+markdown), `coverageCodeHtml` (shiki output whose `.line` nodes carry
+`data-covered` attributes), and `onFindingStatusChange` for triage.
+`symbols/symbol-page` (`SymbolPage`) is the symbol-page sibling fed by
+`SymbolDetailResponse`.
### `dashboard/attention-panel` — `AttentionPanel`
@@ -1071,11 +1164,14 @@ the `useDebounce` presentational hook for autocomplete.
## `graph/graph-flow` — `GraphFlow`
-The full graph canvas. Presentational shell over `@xyflow/react` that
-handles view-mode, drill-down, search, hover/selection, context menu,
-execution-flow highlighting, and ELK layout. The consumer supplies
-every dataset (one per view mode) and renders the data-coupled child
-panels (path-finder, community-panel) via slot render props.
+The full graph canvas. Presentational shell over Sigma that handles
+view-mode, drill-down, search, hover/selection, context menu,
+execution-flow highlighting, constellation hubs, and layout. The
+consumer supplies every dataset (one per view mode) and renders the
+data-coupled child panels (path-finder, community-panel) via slot
+render props. The component does NOT read `window.location` — initial
+URL-derived state arrives via `initialViewMode` / `initialColorMode` /
+`initialSelectedNode`.
| Prop | Type | Required | Notes |
|------|------|----------|-------|
@@ -1091,6 +1187,10 @@ panels (path-finder, community-panel) via slot render props.
| `isLoadingHotFilesGraph` | `boolean` | yes | |
| `communities` | `CommunitySummaryItem[]` | no | Used for the legend's community labels. |
| `executionFlows` | `ExecutionFlows` | no | Backs the flows side panel + trace highlighting. |
+| `constellationGraph` / `constellationSlices` / `onExpandedHubsChange` | see types | no | Radial Knowledge-Graph scope: community super-graph, expanded-hub member slices, and the fetch trigger. |
+| `initialViewMode` | `ViewMode` | no | Initial scope (incl. `dead` / `hotfiles` / `unified`, which seed the signal overlays). |
+| `initialColorMode` | `ColorMode` | no | Initial node color mode; hosts derive it from their URL state. |
+| `initialSelectedNode` | `string \| null` | no | Pre-selected node (e.g. `?node=`). |
| `onViewModeChange` | `(mode: ViewMode) => void` | no | Fires when the user changes view; consumer uses this to toggle data fetches. |
| `onModulePathChange` | `(path: string[]) => void` | no | Fires on drill-down navigation. |
| `onNodeClick` | `(nodeId, nodeType) => void \| Promise<void>` | no | File click handler. |
diff --git a/packages/ui/README.md b/packages/ui/README.md
index a08737c17..7f028a12a 100644
--- a/packages/ui/README.md
+++ b/packages/ui/README.md
@@ -8,33 +8,48 @@ same engine artifacts.
```
src/
- graph/ graph-flow, graph-toolbar, ego-sidebar, …
- git/ hotspot-table, ownership-treemap, …
- dead-code/
- decisions/
- docs/
- symbols/
- coverage/
- wiki/
- chat/ artifact-panel, model-selector, source-citations
- dashboard/ health-score-ring, attention-panel, …
- workspace/ repo-card, contracts-table, …
+ blast-radius/ PR impact analysis shells
+ c4/ C4 architecture views (+ mobile/ layout primitives)
+ chat/ chat-interface, artifact-panel, chat-markdown, …
+ commits/ commit explorer table + detail
+ costs/ LLM cost breakdowns
+ coverage/ coverage-donut, freshness-table
+ dashboard/ health-score-ring, attention-panel, overview tiles, …
+ dead-code/ summary-bar, findings shells
+ decisions/ decisions-table, evidence drawer, verification badge
+ docs/ docs-tree, doc-nav, reader-persona
+ files/ file entity page (doc/health/history/coverage/graph tabs)
+ git/ hotspot-table, ownership-table/treemap, churn viz, …
+ graph/ graph-flow (Sigma), toolbar, legend, panels (+ sigma/)
+ graph-primitives/
+ health/ file-table, kpi-cards, biomarkers, score tokens
+ hooks/ use-debounce, …
jobs/ generation-progress, job-log
- shared/ stat-card, empty-state, api-error
- hooks/ use-elk-layout, use-sse, …
+ modules/ module health detail
+ onboarding/ first-run surfaces
+ owners/ owner directory + profile
+ security/ findings table
+ settings/ general-form
+ shared/ primitives: responsive-table, adaptive-panel, toast,
+ error-boundary, empty-state, api-error, stat-card,
+ entity links/hover cards, context-drawer, owl-loader
+ symbols/ symbol-table, symbol-drawer, symbol-page, graph/git panels
ui/ Radix-CVA primitives
+ wiki/ wiki-markdown, code-block, ToC, git-history, backlinks
+ workspace/ multi-repo tables + summary
styles/
globals.css canonical design tokens (Tailwind v4 @theme)
```
## Consuming
-Components are exposed via subpath exports — import the slice you need
+Components are exposed via subpath exports — import the slice you need
rather than the barrel:
```ts
import { HotspotTable } from "@repowise-dev/ui/git";
import { GraphFlow } from "@repowise-dev/ui/graph";
+import { ResponsiveTable, AdaptivePanel, Toaster, toast } from "@repowise-dev/ui/shared";
```
Consumers must add `transpilePackages: ["@repowise-dev/ui", "@repowise-dev/types"]`
@@ -48,9 +63,34 @@ the root of the app:
@import "@repowise-dev/ui/styles.css";
```
+## Shared primitives
+
+- **`ResponsiveTable`** — the table primitive every list surface should
+ build on. Columns declare a `priority` (1 always visible, 2 hidden
+ below `md`, 3 hidden below `lg`); the wrapper always falls back to
+ `overflow-x-auto`, and `stacked` collapses the table into cards on
+ phones.
+- **`AdaptivePanel`** — one overlay surface: right-side panel on
+ desktop, swipe-dismissable bottom sheet on mobile. `ContextDrawer`
+ and the chat `ArtifactPanel` are built on it.
+- **`Toaster` / `toast`** — token-themed sonner toaster (uses
+ `--z-toast`). Mount the `Toaster` once at the app shell; the host
+ passes the resolved theme.
+- **`ErrorBoundary`** — recoverable render-error boundary; default
+ fallback is `ApiError` with a reset retry.
+- **`EmptyState`** — the only sanctioned empty-state rendering. No raw
+ `<p>` placeholders.
+- Score colors come from ONE band helper in `health/tokens.ts`
+ (`scoreBand` / `scoreBadgeClass` / `scoreSoftBadgeClass` /
+ `scoreTextColor`): <4 critical, <6 poor, <8 fair, ≥8 good, mapped to
+ the semantic tokens (`--color-error/warning/caution/success`).
+
## Peer deps
-`react`, `react-dom`. Components stay client-pure or pure-presentational —
-they do not call `next/navigation` or `next/link` directly. Where routing
-is needed, accept it via props or context so consumers can wire their
-own router.
+`react`, `react-dom`, `next-themes` (theme resolution only). Components
+stay client-pure or pure-presentational — they do not call
+`next/navigation` or `next/link` directly. Where routing is needed,
+accept it via props (`renderLink` render props, `LinkComponent`,
+`buildHref`) or context so consumers can wire their own router. New
+components must not read `window.location`; initial state arrives via
+props.
diff --git a/packages/ui/__tests__/c4/flow-domain.test.tsx b/packages/ui/__tests__/c4/flow-domain.test.tsx
index e9a89c907..85721944d 100644
--- a/packages/ui/__tests__/c4/flow-domain.test.tsx
+++ b/packages/ui/__tests__/c4/flow-domain.test.tsx
@@ -45,8 +45,10 @@ describe("PathFinderModal", () => {
});
render(<PathFinderModal />);
expect(screen.getByText("Path Finder")).toBeTruthy();
- const selects = screen.getAllByRole("combobox");
- expect(selects).toHaveLength(2);
+ // Node pickers are typeahead inputs now (the old <select> over every
+ // node didn't scale past small repos).
+ expect(screen.getByLabelText("From node")).toBeTruthy();
+ expect(screen.getByLabelText("To node")).toBeTruthy();
});
it("closes when close button is clicked", () => {
diff --git a/packages/ui/__tests__/docs/docs-tree.test.tsx b/packages/ui/__tests__/docs/docs-tree.test.tsx
index de8fee0fe..8f2ef69a6 100644
--- a/packages/ui/__tests__/docs/docs-tree.test.tsx
+++ b/packages/ui/__tests__/docs/docs-tree.test.tsx
@@ -1,5 +1,11 @@
-import { describe, it, expect, vi } from "vitest";
+import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
+
+// The tree persists its expansion state to localStorage; isolate tests so
+// toggles from one render don't pre-expand (and invert clicks in) the next.
+beforeEach(() => {
+ window.localStorage.clear();
+});
import { DocsTree } from "../../src/docs/docs-tree.js";
import type { DocPage } from "@repowise-dev/types/docs";
diff --git a/packages/ui/package.json b/packages/ui/package.json
index d39e2e0f3..bac243695 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -35,6 +35,8 @@
"./health/*": "./src/health/*.tsx",
"./decisions": "./src/decisions/index.ts",
"./decisions/*": "./src/decisions/*.tsx",
+ "./files": "./src/files/index.ts",
+ "./files/*": "./src/files/*.tsx",
"./docs": "./src/docs/index.ts",
"./docs/doc-nav": "./src/docs/doc-nav.ts",
"./docs/reader-persona": "./src/docs/reader-persona.ts",
@@ -64,6 +66,8 @@
"./c4": "./src/c4/index.ts",
"./c4/export": "./src/c4/export/index.ts",
"./c4/*": "./src/c4/*.tsx",
+ "./dependencies": "./src/dependencies/index.ts",
+ "./dependencies/*": "./src/dependencies/*.tsx",
"./costs": "./src/costs/index.ts",
"./costs/*": "./src/costs/*.tsx",
"./security": "./src/security/index.ts",
@@ -74,6 +78,7 @@
"./settings/*": "./src/settings/*.tsx",
"./shared": "./src/shared/index.ts",
"./shared/entity": "./src/shared/entity/index.ts",
+ "./shared/responsive-table": "./src/shared/responsive-table/index.ts",
"./shared/context-drawer": "./src/shared/context-drawer/index.ts",
"./shared/file-card": "./src/shared/file-card/index.ts",
"./shared/related": "./src/shared/related/index.ts",
@@ -130,6 +135,7 @@
"remark-gfm": "^4.0.1",
"shiki": "^4.0.0",
"sigma": "^3.0.3",
+ "sonner": "^2.0.7",
"tailwind-merge": "^3.5.0",
"zustand": "^4.4.0"
},
diff --git a/packages/ui/src/blast-radius/blast-radius-results.tsx b/packages/ui/src/blast-radius/blast-radius-results.tsx
index 7ebce6328..eb962e911 100644
--- a/packages/ui/src/blast-radius/blast-radius-results.tsx
+++ b/packages/ui/src/blast-radius/blast-radius-results.tsx
@@ -1,3 +1,4 @@
+import type { ReactNode } from "react";
import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";
import { RiskScoreCard } from "./risk-score-card";
import { BlastRadiusSummary } from "./blast-radius-summary";
@@ -10,10 +11,13 @@ import { TestGapsList } from "./test-gaps-list";
interface BlastRadiusResultsProps {
result: BlastRadiusResponse;
+ /** Rich reviewer panel (e.g. `ReviewerSuggestions` fed by the
+ * reviewer-suggestions endpoint). Replaces the thin email table. */
+ reviewersSlot?: ReactNode | undefined;
}
/** Composes the full results stack — score gauge, summary, all five tables. */
-export function BlastRadiusResults({ result }: BlastRadiusResultsProps) {
+export function BlastRadiusResults({ result, reviewersSlot }: BlastRadiusResultsProps) {
return (
<div className="space-y-4">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-4">
@@ -39,12 +43,14 @@ export function BlastRadiusResults({ result }: BlastRadiusResultsProps) {
<CochangeTable rows={result.cochange_warnings} />
</TableSection>
- <TableSection
- title="Recommended Reviewers"
- empty={result.recommended_reviewers.length === 0}
- >
- <ReviewersTable rows={result.recommended_reviewers} />
- </TableSection>
+ {reviewersSlot ?? (
+ <TableSection
+ title="Recommended Reviewers"
+ empty={result.recommended_reviewers.length === 0}
+ >
+ <ReviewersTable rows={result.recommended_reviewers} />
+ </TableSection>
+ )}
<TableSection title="Test Gaps" empty={result.test_gaps.length === 0}>
<TestGapsList gaps={result.test_gaps} />
diff --git a/packages/ui/src/c4/panels/PathFinderModal.tsx b/packages/ui/src/c4/panels/PathFinderModal.tsx
index 391f76b9e..d6955852e 100644
--- a/packages/ui/src/c4/panels/PathFinderModal.tsx
+++ b/packages/ui/src/c4/panels/PathFinderModal.tsx
@@ -1,10 +1,127 @@
"use client";
-import { useState } from "react";
+import { useMemo, useState } from "react";
import { useArchitectureStore } from "../store/use-architecture-store";
import { findShortestPath } from "../utils/graph-algorithms";
import { getTone } from "../../graph-primitives/tone-styles";
import { Badge } from "./panel-atoms";
+import type { ArchNode } from "../types";
+
+/** Typeahead node picker — replaces the unscalable <select> over all nodes. */
+function NodeCombobox({
+ label,
+ nodes,
+ value,
+ onSelect,
+}: {
+ label: string;
+ nodes: ArchNode[];
+ value: string;
+ onSelect: (nodeId: string) => void;
+}) {
+ const selected = useMemo(
+ () => nodes.find((n) => n.id === value) ?? null,
+ [nodes, value],
+ );
+ const [query, setQuery] = useState("");
+ const [open, setOpen] = useState(false);
+
+ const matches = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ if (!q) return nodes.slice(0, 20);
+ return nodes
+ .filter(
+ (n) =>
+ n.name.toLowerCase().includes(q) || n.id.toLowerCase().includes(q),
+ )
+ .slice(0, 20);
+ }, [nodes, query]);
+
+ return (
+ <div style={{ marginBottom: 12, position: "relative" }}>
+ <div style={{ fontSize: 12, opacity: 0.7, marginBottom: 4 }}>{label}</div>
+ <input
+ type="text"
+ value={open ? query : (selected?.name ?? "")}
+ placeholder="Type to search nodes…"
+ aria-label={`${label} node`}
+ onFocus={() => {
+ setOpen(true);
+ setQuery("");
+ }}
+ onBlur={() => setTimeout(() => setOpen(false), 150)}
+ onChange={(e) => setQuery(e.target.value)}
+ style={{
+ width: "100%",
+ padding: "8px 12px",
+ background: "var(--color-bg-surface)",
+ color: "var(--color-text-primary)",
+ border: "1px solid var(--color-border-default)",
+ borderRadius: 6,
+ fontSize: 13,
+ outline: "none",
+ }}
+ />
+ {open && (
+ <div
+ style={{
+ position: "absolute",
+ top: "100%",
+ left: 0,
+ right: 0,
+ marginTop: 4,
+ maxHeight: 200,
+ overflowY: "auto",
+ background: "var(--color-bg-elevated)",
+ border: "1px solid var(--color-border-default)",
+ borderRadius: 6,
+ zIndex: 10,
+ boxShadow: "0 8px 24px rgba(0,0,0,0.25)",
+ }}
+ >
+ {matches.length === 0 ? (
+ <div style={{ padding: "8px 12px", fontSize: 12, opacity: 0.6 }}>
+ No matching nodes
+ </div>
+ ) : (
+ matches.map((n) => {
+ const tone = getTone(n.node_type);
+ return (
+ <button
+ key={n.id}
+ type="button"
+ onMouseDown={(e) => {
+ e.preventDefault();
+ onSelect(n.id);
+ setOpen(false);
+ }}
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: 8,
+ width: "100%",
+ textAlign: "left",
+ padding: "7px 12px",
+ background: "none",
+ border: "none",
+ cursor: "pointer",
+ color: "var(--color-text-primary)",
+ fontSize: 13,
+ }}
+ >
+ <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
+ {n.name}
+ </span>
+ <Badge label={n.node_type} color={tone.text} bg={tone.bg} />
+ </button>
+ );
+ })
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
export function PathFinderModal() {
const view = useArchitectureStore((s) => s.view);
@@ -37,16 +154,6 @@ export function PathFinderModal() {
setPathFinderOpen(false);
};
- const selectStyle: React.CSSProperties = {
- width: "100%",
- padding: "8px 12px",
- background: "var(--color-bg-surface)",
- color: "var(--color-text-primary)",
- border: "1px solid var(--color-border-default)",
- borderRadius: 6,
- fontSize: 13,
- };
-
return (
<div
onClick={handleClose}
@@ -100,43 +207,24 @@ export function PathFinderModal() {
</button>
</div>
- <div style={{ marginBottom: 12 }}>
- <div style={{ fontSize: 12, opacity: 0.7, marginBottom: 4 }}>From</div>
- <select
- value={fromId}
- onChange={(e) => {
- setFromId(e.target.value);
- setResult(undefined);
- }}
- style={selectStyle}
- >
- <option value="">Select a node...</option>
- {nodes.map((n) => (
- <option key={n.id} value={n.id}>
- {n.name}
- </option>
- ))}
- </select>
- </div>
-
- <div style={{ marginBottom: 16 }}>
- <div style={{ fontSize: 12, opacity: 0.7, marginBottom: 4 }}>To</div>
- <select
- value={toId}
- onChange={(e) => {
- setToId(e.target.value);
- setResult(undefined);
- }}
- style={selectStyle}
- >
- <option value="">Select a node...</option>
- {nodes.map((n) => (
- <option key={n.id} value={n.id}>
- {n.name}
- </option>
- ))}
- </select>
- </div>
+ <NodeCombobox
+ label="From"
+ nodes={nodes}
+ value={fromId}
+ onSelect={(id) => {
+ setFromId(id);
+ setResult(undefined);
+ }}
+ />
+ <NodeCombobox
+ label="To"
+ nodes={nodes}
+ value={toId}
+ onSelect={(id) => {
+ setToId(id);
+ setResult(undefined);
+ }}
+ />
<button
type="button"
diff --git a/packages/ui/src/c4/panels/PersonaSelector.tsx b/packages/ui/src/c4/panels/PersonaSelector.tsx
index 858d2fd0b..c0120df2e 100644
--- a/packages/ui/src/c4/panels/PersonaSelector.tsx
+++ b/packages/ui/src/c4/panels/PersonaSelector.tsx
@@ -8,23 +8,42 @@ export function PersonaSelector() {
const setPersona = useArchitectureStore((s) => s.setPersona);
return (
- <select
- value={persona}
- onChange={(e) => setPersona(e.target.value as Persona)}
+ <label
style={{
- background: "transparent",
- border: "1px solid var(--color-border-default)",
- borderRadius: 4,
- padding: "4px 8px",
- fontSize: 11,
- color: "var(--color-text-primary)",
- cursor: "pointer",
- outline: "none",
+ display: "inline-flex",
+ alignItems: "center",
+ gap: 6,
+ fontSize: 10,
+ color: "var(--color-text-tertiary)",
+ textTransform: "uppercase",
+ letterSpacing: "0.05em",
+ fontWeight: 500,
}}
>
- <option value="overview">Overview</option>
- <option value="learn">Learn</option>
- <option value="deep-dive">Deep Dive</option>
- </select>
+ Lens
+ <select
+ value={persona}
+ onChange={(e) => setPersona(e.target.value as Persona)}
+ aria-label="Reading lens: how much detail the view shows"
+ title="How much detail the view shows: a quick overview, a guided learning pass, or everything"
+ style={{
+ background: "transparent",
+ border: "1px solid var(--color-border-default)",
+ borderRadius: 4,
+ padding: "4px 8px",
+ fontSize: 11,
+ color: "var(--color-text-primary)",
+ cursor: "pointer",
+ outline: "none",
+ textTransform: "none",
+ letterSpacing: "normal",
+ fontWeight: 400,
+ }}
+ >
+ <option value="overview">Overview</option>
+ <option value="learn">Learn</option>
+ <option value="deep-dive">Deep Dive</option>
+ </select>
+ </label>
);
}
diff --git a/packages/ui/src/chat/artifact-panel.tsx b/packages/ui/src/chat/artifact-panel.tsx
index 3435f6516..71e3dc011 100644
--- a/packages/ui/src/chat/artifact-panel.tsx
+++ b/packages/ui/src/chat/artifact-panel.tsx
@@ -1,8 +1,8 @@
"use client";
import { useState } from "react";
-import { X } from "lucide-react";
import { cn } from "../lib/cn";
+import { AdaptivePanel } from "../shared/adaptive-panel";
import { ChatMarkdown } from "./chat-markdown";
import {
ContextRenderer,
@@ -42,59 +42,42 @@ interface ArtifactPanelProps {
export function ArtifactPanel({ artifacts, open, onClose }: ArtifactPanelProps) {
const [activeIdx, setActiveIdx] = useState(0);
- if (!open || artifacts.length === 0) return null;
+ if (artifacts.length === 0) return null;
const active = artifacts[Math.min(activeIdx, artifacts.length - 1)];
if (!active) return null;
return (
- <>
- <div className="fixed inset-0 z-[var(--z-modal)] bg-black/50 lg:hidden" onClick={onClose} />
-
- <div
- className={cn(
- "fixed right-0 top-0 z-[var(--z-modal)] h-full bg-[var(--color-bg-surface)] border-l border-[var(--color-border-default)] flex flex-col",
- "w-full sm:w-[480px] lg:w-[420px]",
- "transition-transform duration-300",
- open ? "translate-x-0" : "translate-x-full",
- )}
- >
- <div className="flex items-center justify-between px-4 py-3 border-b border-[var(--color-border-default)] shrink-0">
- <span className="text-xs font-medium text-[var(--color-text-primary)]">
- Artifacts
- </span>
- <button
- onClick={onClose}
- className="p-1 rounded hover:bg-[var(--color-bg-elevated)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] transition-colors"
- >
- <X className="h-4 w-4" />
- </button>
+ <AdaptivePanel
+ open={open}
+ onOpenChange={(o) => (!o ? onClose() : undefined)}
+ title="Artifacts"
+ widthClassName="md:max-w-[480px] lg:max-w-[420px]"
+ modal={false}
+ >
+ {artifacts.length > 1 && (
+ <div className="flex gap-0 border-b border-[var(--color-border-default)] shrink-0 overflow-x-auto px-2">
+ {artifacts.map((art, idx) => (
+ <button
+ key={idx}
+ onClick={() => setActiveIdx(idx)}
+ className={cn(
+ "px-3 py-2 text-xs whitespace-nowrap border-b-2 transition-colors",
+ idx === activeIdx
+ ? "border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"
+ : "border-transparent text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]",
+ )}
+ >
+ {art.title || art.type}
+ </button>
+ ))}
</div>
+ )}
- {artifacts.length > 1 && (
- <div className="flex gap-0 border-b border-[var(--color-border-default)] shrink-0 overflow-x-auto px-2">
- {artifacts.map((art, idx) => (
- <button
- key={idx}
- onClick={() => setActiveIdx(idx)}
- className={cn(
- "px-3 py-2 text-xs whitespace-nowrap border-b-2 transition-colors",
- idx === activeIdx
- ? "border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"
- : "border-transparent text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]",
- )}
- >
- {art.title || art.type}
- </button>
- ))}
- </div>
- )}
-
- <div className="flex-1 overflow-y-auto p-4">
- <ArtifactRenderer artifact={active} />
- </div>
+ <div className="flex-1 overflow-y-auto p-4">
+ <ArtifactRenderer artifact={active} />
</div>
- </>
+ </AdaptivePanel>
);
}
diff --git a/packages/ui/src/chat/chat-interface.tsx b/packages/ui/src/chat/chat-interface.tsx
index f903b24b9..2317a949e 100644
--- a/packages/ui/src/chat/chat-interface.tsx
+++ b/packages/ui/src/chat/chat-interface.tsx
@@ -80,6 +80,13 @@ export interface ChatInterfaceProps {
emptyStateLogoSrc?: string;
/** Override default suggestion chips. */
suggestions?: string[];
+ /** Orientation line under the empty-state subtitle — index status, page
+ * counts, last sync. Keeps the blank page honest about what's loaded. */
+ statusSlot?: ReactNode;
+ /** Disables the composer (e.g. no chat provider configured). */
+ sendDisabled?: boolean;
+ /** Banner shown above the composer when sending is disabled. */
+ sendDisabledReason?: ReactNode;
}
export function ChatInterface({
@@ -97,6 +104,9 @@ export function ChatInterface({
linkPrefix,
emptyStateLogoSrc = "/repowise-logo.png",
suggestions = DEFAULT_SUGGESTIONS,
+ statusSlot,
+ sendDisabled = false,
+ sendDisabledReason,
}: ChatInterfaceProps) {
const [input, setInput] = useState("");
const [artifactPanelOpen, setArtifactPanelOpen] = useState(false);
@@ -134,9 +144,28 @@ export function ChatInterface({
[],
);
+ // Pulse the artifact-panel button when a new artifact lands while the
+ // panel is closed, so streamed diagrams don't arrive silently.
+ const prevArtifactCount = useRef(0);
+ const [artifactPulse, setArtifactPulse] = useState(false);
+ const totalArtifactCount = messages.reduce(
+ (count, m) => count + m.toolCalls.filter((tc) => tc.artifact).length,
+ 0,
+ );
+ useEffect(() => {
+ if (totalArtifactCount > prevArtifactCount.current && !artifactPanelOpen) {
+ setArtifactPulse(true);
+ const t = setTimeout(() => setArtifactPulse(false), 2500);
+ prevArtifactCount.current = totalArtifactCount;
+ return () => clearTimeout(t);
+ }
+ prevArtifactCount.current = totalArtifactCount;
+ return undefined;
+ }, [totalArtifactCount, artifactPanelOpen]);
+
async function handleSubmit() {
const text = input.trim();
- if (!text || isStreaming) return;
+ if (!text || isStreaming || sendDisabled) return;
setInput("");
if (textareaRef.current) {
textareaRef.current.style.height = "auto";
@@ -149,11 +178,6 @@ export function ChatInterface({
textareaRef.current?.focus();
}
- const totalArtifactCount = messages.reduce(
- (count, m) => count + m.toolCalls.filter((tc) => tc.artifact).length,
- 0,
- );
-
return (
<div className="flex h-full flex-col min-h-0">
{/* Header bar (active conversation) */}
@@ -165,7 +189,11 @@ export function ChatInterface({
<Button
variant="ghost"
size="sm"
- className="h-8 text-xs gap-1.5"
+ className={cn(
+ "h-8 text-xs gap-1.5",
+ artifactPulse &&
+ "animate-pulse text-[var(--color-accent-primary)]",
+ )}
onClick={() => setArtifactPanelOpen(true)}
>
<PanelRight className="h-4 w-4" />
@@ -196,6 +224,11 @@ export function ChatInterface({
Explore architecture, assess risk, search code, trace
dependencies, and understand decisions.
</p>
+ {statusSlot && (
+ <div className="text-xs text-[var(--color-text-tertiary)]">
+ {statusSlot}
+ </div>
+ )}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5 max-w-xl w-full">
@@ -253,10 +286,16 @@ export function ChatInterface({
)}
>
<div className="max-w-3xl mx-auto">
+ {sendDisabled && sendDisabledReason && (
+ <div className="mb-2 rounded-lg border border-[var(--color-warning)]/40 bg-[var(--color-warning)]/10 px-3 py-2 text-xs text-[var(--color-text-secondary)]">
+ {sendDisabledReason}
+ </div>
+ )}
<div
className={cn(
"flex items-end gap-2 rounded-2xl border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-4 py-3",
isEmpty && "shadow-lg shadow-black/20",
+ sendDisabled && "opacity-60",
)}
>
<textarea
@@ -271,6 +310,7 @@ export function ChatInterface({
}}
placeholder="Ask anything about this codebase..."
aria-label="Chat message"
+ disabled={sendDisabled}
rows={1}
className="flex-1 resize-none bg-transparent text-sm text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] outline-none leading-6 max-h-36 overflow-y-auto"
style={{ scrollbarWidth: "none" }}
@@ -279,7 +319,7 @@ export function ChatInterface({
size="icon"
className="h-8 w-8 shrink-0 rounded-xl"
onClick={isStreaming ? onCancel : () => void handleSubmit()}
- disabled={!input.trim() && !isStreaming}
+ disabled={(!input.trim() && !isStreaming) || sendDisabled}
aria-label={isStreaming ? "Stop generation" : "Send message"}
title={isStreaming ? "Stop generation" : "Send message"}
>
diff --git a/packages/ui/src/chat/conversation-history.tsx b/packages/ui/src/chat/conversation-history.tsx
index e0335442c..709657d88 100644
--- a/packages/ui/src/chat/conversation-history.tsx
+++ b/packages/ui/src/chat/conversation-history.tsx
@@ -7,8 +7,8 @@
* select / delete / new intents via callbacks.
*/
-import { useState } from "react";
-import { History, Plus, Trash2 } from "lucide-react";
+import { useMemo, useState } from "react";
+import { History, Plus, Search, Trash2 } from "lucide-react";
import { cn } from "../lib/cn";
import { formatRelativeTime } from "../lib/format";
import type { Conversation } from "@repowise-dev/types/chat";
@@ -34,6 +34,13 @@ export function ConversationHistory({
className,
}: ConversationHistoryProps) {
const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+
+ const filtered = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ if (!q) return conversations;
+ return conversations?.filter((c) => c.title.toLowerCase().includes(q));
+ }, [conversations, query]);
return (
<div className={cn("relative", className)}>
@@ -67,6 +74,19 @@ export function ConversationHistory({
New conversation
</button>
+ {(conversations?.length ?? 0) > 5 && (
+ <div className="flex items-center gap-1.5 border-b border-[var(--color-border-default)] px-3 py-1.5">
+ <Search className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />
+ <input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Search conversations…"
+ aria-label="Search conversations"
+ className="w-full bg-transparent text-xs text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-tertiary)]"
+ />
+ </div>
+ )}
+
<div className="max-h-64 overflow-y-auto">
{isLoading && !conversations && (
<div className="px-3 py-4 text-xs text-[var(--color-text-tertiary)] text-center">
@@ -78,7 +98,12 @@ export function ConversationHistory({
No conversations yet
</div>
)}
- {conversations?.map((conv) => (
+ {(conversations?.length ?? 0) > 0 && filtered?.length === 0 && (
+ <div className="px-3 py-4 text-xs text-[var(--color-text-tertiary)] text-center">
+ No conversations match
+ </div>
+ )}
+ {filtered?.map((conv) => (
<div
key={conv.id}
className={cn(
diff --git a/packages/ui/src/commits/agent-badge.tsx b/packages/ui/src/commits/agent-badge.tsx
new file mode 100644
index 000000000..9c0c2050c
--- /dev/null
+++ b/packages/ui/src/commits/agent-badge.tsx
@@ -0,0 +1,52 @@
+"use client";
+
+import { Bot } from "lucide-react";
+import { cn } from "../lib/cn";
+
+/** Human-readable autonomy tier: 1 = bot, 2 = agent driven by a human in the
+ * loop, 3 = assisted/co-authored. */
+export function agentTierLabel(tier: number | null | undefined): string | null {
+ if (tier === 1) return "autonomous";
+ if (tier === 2) return "agent";
+ if (tier === 3) return "assisted";
+ return null;
+}
+
+export interface AgentBadgeProps {
+ agentName: string;
+ tier?: number | null | undefined;
+ confidence?: string | null | undefined;
+ className?: string;
+}
+
+/** Compact provenance chip for agent-attributed commits. */
+export function AgentBadge({ agentName, tier, confidence, className }: AgentBadgeProps) {
+ const tierLabel = agentTierLabel(tier);
+ return (
+ <span
+ className={cn(
+ "inline-flex shrink-0 items-center gap-1 rounded-md bg-[var(--color-accent-muted)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--color-accent-primary)]",
+ className,
+ )}
+ title={`Attributed to ${agentName}${tierLabel ? ` (${tierLabel})` : ""}${
+ confidence ? ` — ${confidence} confidence` : ""
+ }`}
+ >
+ <Bot className="h-2.5 w-2.5" />
+ <span className="max-w-[110px] truncate">{agentName}</span>
+ {tierLabel && <span className="opacity-70">{tierLabel}</span>}
+ </span>
+ );
+}
+
+/** "New contributor" marker — low cumulative prior-commit count at commit time. */
+export function NewContributorBadge({ experience }: { experience: number }) {
+ return (
+ <span
+ className="inline-flex shrink-0 items-center rounded-md bg-[var(--color-caution)]/15 px-1.5 py-0.5 text-[10px] font-medium text-[var(--color-caution)]"
+ title={`Author had ${experience} prior commit${experience === 1 ? "" : "s"} in this repo at the time`}
+ >
+ new contributor
+ </span>
+ );
+}
diff --git a/packages/ui/src/commits/agent-trend-strip.tsx b/packages/ui/src/commits/agent-trend-strip.tsx
new file mode 100644
index 000000000..82750c7d4
--- /dev/null
+++ b/packages/ui/src/commits/agent-trend-strip.tsx
@@ -0,0 +1,64 @@
+"use client";
+
+import { Bot } from "lucide-react";
+import type { AgentTrend } from "@repowise-dev/types/git";
+import { cn } from "../lib/cn";
+
+export interface AgentTrendStripProps {
+ trend: AgentTrend;
+ className?: string;
+}
+
+/**
+ * Compact agent-share trend: headline share plus a monthly bar strip.
+ * Renders nothing when no commit in the window carries agent attribution.
+ */
+export function AgentTrendStrip({ trend, className }: AgentTrendStripProps) {
+ if (trend.agent_commits === 0) return null;
+ // Cap the strip at the last 12 months so it stays a glanceable sparkline.
+ const buckets = trend.buckets.slice(-12);
+ const topAgents = trend.agent_names.slice(0, 3);
+
+ return (
+ <div
+ className={cn(
+ "flex flex-wrap items-center gap-x-4 gap-y-2 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-2",
+ className,
+ )}
+ >
+ <span className="flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">
+ <Bot className="h-3.5 w-3.5 text-[var(--color-accent-primary)]" />
+ <span className="font-semibold tabular-nums text-[var(--color-text-primary)]">
+ {Math.round(trend.agent_pct)}%
+ </span>
+ of indexed commits are agent-attributed
+ <span className="tabular-nums text-[var(--color-text-tertiary)]">
+ ({trend.agent_commits} of {trend.total_commits})
+ </span>
+ </span>
+
+ <div className="flex h-6 items-end gap-0.5" aria-label="Monthly agent share">
+ {buckets.map((b) => (
+ <div
+ key={b.month}
+ className="flex h-full w-2 items-end rounded-sm bg-[var(--color-bg-elevated)]"
+ title={`${b.month}: ${Math.round(b.agent_pct)}% agent (${b.agent_commits}/${b.total_commits})`}
+ >
+ <div
+ className="w-full rounded-sm bg-[var(--color-accent-primary)]/70"
+ style={{
+ height: `${Math.max(b.agent_pct, b.agent_commits > 0 ? 8 : 0)}%`,
+ }}
+ />
+ </div>
+ ))}
+ </div>
+
+ {topAgents.length > 0 && (
+ <span className="text-[10px] text-[var(--color-text-tertiary)]">
+ {topAgents.map((a) => `${a.name} (${a.count})`).join(" · ")}
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/packages/ui/src/commits/commit-detail-card.tsx b/packages/ui/src/commits/commit-detail-card.tsx
index 381311870..3696383db 100644
--- a/packages/ui/src/commits/commit-detail-card.tsx
+++ b/packages/ui/src/commits/commit-detail-card.tsx
@@ -1,4 +1,5 @@
import { Bug, GitCommitHorizontal, User } from "lucide-react";
+import { AgentBadge, NewContributorBadge } from "./agent-badge";
import { PriorityBadge } from "./priority-badge";
import { RiskDriverBreakdown } from "./risk-driver-breakdown";
import { formatDateTime, formatLOC } from "../lib/format";
@@ -45,13 +46,29 @@ export function CommitDetailCard({ commit, className }: CommitDetailCardProps) {
<p className="text-sm font-medium text-[var(--color-text-primary)] break-words">
{c.subject || "(no subject)"}
</p>
- <div className="flex items-center gap-3 text-xs text-[var(--color-text-tertiary)]">
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-[var(--color-text-tertiary)]">
<span className="inline-flex items-center gap-1">
<User className="h-3 w-3" />
{c.author_name || "unknown"}
</span>
+ {c.agent_name && (
+ <AgentBadge
+ agentName={c.agent_name}
+ tier={c.agent_autonomy_tier}
+ confidence={c.agent_confidence}
+ />
+ )}
+ {!c.agent_name && c.author_experience != null && c.author_experience < 3 && (
+ <NewContributorBadge experience={c.author_experience} />
+ )}
{c.committed_at && <span>{formatDateTime(c.committed_at)}</span>}
</div>
+ {c.agent_name && c.agent_channel && (
+ <p className="text-[10px] text-[var(--color-text-tertiary)]">
+ Attribution channel: {c.agent_channel}
+ {c.agent_confidence ? ` · ${c.agent_confidence} confidence` : ""}
+ </p>
+ )}
</div>
{/* Risk summary */}
diff --git a/packages/ui/src/commits/commit-table.tsx b/packages/ui/src/commits/commit-table.tsx
index 96b57e5a4..2132a359e 100644
--- a/packages/ui/src/commits/commit-table.tsx
+++ b/packages/ui/src/commits/commit-table.tsx
@@ -2,6 +2,7 @@
import { useMemo, useState } from "react";
import { Bug, Search } from "lucide-react";
+import { AgentBadge, NewContributorBadge } from "./agent-badge";
import { PriorityBadge } from "./priority-badge";
import { ChurnBar } from "../git/churn-bar";
import { Input } from "../ui/input";
@@ -12,12 +13,20 @@ import { cn } from "../lib/cn";
import type { Commit, ReviewPriority } from "@repowise-dev/types/git";
export type CommitSort = "risk" | "date";
+export type CommitAuthorship = "all" | "human" | "agent";
+
+/** Below this many prior commits the author gets a "new contributor" badge. */
+const NEW_CONTRIBUTOR_THRESHOLD = 3;
export interface CommitTableProps {
commits: Commit[];
/** Server-driven ordering. `risk` = review-priority order, `date` = recency. */
sort: CommitSort;
onSortChange?: (sort: CommitSort) => void;
+ /** Server-driven authorship filter (agent provenance). Control omitted when
+ * no handler is provided. */
+ authorship?: CommitAuthorship;
+ onAuthorshipChange?: (authorship: CommitAuthorship) => void;
onSelect?: (commit: Commit) => void;
total?: number;
hasMore?: boolean;
@@ -37,6 +46,8 @@ export function CommitTable({
commits,
sort,
onSortChange,
+ authorship = "all",
+ onAuthorshipChange,
onSelect,
total,
hasMore,
@@ -62,7 +73,7 @@ export function CommitTable({
return items;
}, [commits, search, filter]);
- if (commits.length === 0) {
+ if (commits.length === 0 && authorship === "all") {
return (
<EmptyState
title="No commits indexed"
@@ -115,6 +126,31 @@ export function CommitTable({
</button>
))}
</div>
+ {onAuthorshipChange && (
+ <div className="flex rounded-md border border-[var(--color-border-default)] overflow-hidden text-xs">
+ {(
+ [
+ { key: "all", label: "Everyone" },
+ { key: "human", label: "Humans" },
+ { key: "agent", label: "Agents" },
+ ] as { key: CommitAuthorship; label: string }[]
+ ).map((a) => (
+ <button
+ key={a.key}
+ onClick={() => onAuthorshipChange(a.key)}
+ aria-pressed={authorship === a.key}
+ className={cn(
+ "px-2.5 py-1.5 font-medium transition-colors",
+ authorship === a.key
+ ? "bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)]"
+ : "bg-transparent text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-elevated)]",
+ )}
+ >
+ {a.label}
+ </button>
+ ))}
+ </div>
+ )}
<div className="ml-auto flex rounded-md border border-[var(--color-border-default)] overflow-hidden text-xs">
{sorts.map((s) => (
<button
@@ -159,6 +195,9 @@ export function CommitTable({
<th className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-40">
Risk
</th>
+ <th className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider hidden xl:table-cell">
+ Top driver
+ </th>
</tr>
</thead>
<tbody>
@@ -188,8 +227,18 @@ export function CommitTable({
</span>
</div>
</td>
- <td className="px-3 py-2.5 text-xs text-[var(--color-text-secondary)] hidden md:table-cell truncate max-w-[140px]">
- {c.author_name || "—"}
+ <td className="px-3 py-2.5 text-xs text-[var(--color-text-secondary)] hidden md:table-cell max-w-[220px]">
+ <div className="flex items-center gap-1.5 min-w-0">
+ <span className="truncate">{c.author_name || "—"}</span>
+ {c.agent_name && (
+ <AgentBadge agentName={c.agent_name} tier={c.agent_autonomy_tier} />
+ )}
+ {!c.agent_name &&
+ c.author_experience != null &&
+ c.author_experience < NEW_CONTRIBUTOR_THRESHOLD && (
+ <NewContributorBadge experience={c.author_experience} />
+ )}
+ </div>
</td>
<td className="px-3 py-2.5 text-xs text-[var(--color-text-tertiary)] tabular-nums hidden lg:table-cell">
{c.committed_at ? formatRelativeTime(c.committed_at) : "—"}
@@ -207,6 +256,12 @@ export function CommitTable({
<PriorityBadge priority={c.review_priority as ReviewPriority} />
</div>
</td>
+ <td
+ className="px-3 py-2.5 text-[11px] text-[var(--color-text-tertiary)] hidden xl:table-cell max-w-[220px] truncate"
+ title={c.top_driver ?? undefined}
+ >
+ {c.top_driver ?? "—"}
+ </td>
</tr>
))}
</tbody>
diff --git a/packages/ui/src/commits/index.ts b/packages/ui/src/commits/index.ts
index 85bb679bd..c44ccc70e 100644
--- a/packages/ui/src/commits/index.ts
+++ b/packages/ui/src/commits/index.ts
@@ -3,3 +3,5 @@ export * from "./commit-detail-card";
export * from "./risk-driver-breakdown";
export * from "./priority-badge";
export * from "./credibility-strip";
+export * from "./agent-badge";
+export * from "./agent-trend-strip";
diff --git a/packages/ui/src/costs/distill-savings-card.tsx b/packages/ui/src/costs/distill-savings-card.tsx
index 912ff6698..3faff79d8 100644
--- a/packages/ui/src/costs/distill-savings-card.tsx
+++ b/packages/ui/src/costs/distill-savings-card.tsx
@@ -143,9 +143,12 @@ export function DistillSavingsCard({ data }: DistillSavingsCardProps) {
{detected ? (
<span className="text-[var(--color-text-tertiary)]"> · {data.pricing_source}</span>
) : (
- <span className="text-[var(--color-text-tertiary)]">
+ <span
+ className="text-[var(--color-text-tertiary)]"
+ title="No agent session was detected, so savings are valued at the standard published rate for this model."
+ >
{" "}
- · no agent session detected, default rate
+ · estimated at the standard model rate
</span>
)}
</p>
diff --git a/packages/ui/src/dashboard/attention-panel.tsx b/packages/ui/src/dashboard/attention-panel.tsx
index 8d20d6a15..ea5862b7b 100644
--- a/packages/ui/src/dashboard/attention-panel.tsx
+++ b/packages/ui/src/dashboard/attention-panel.tsx
@@ -64,11 +64,11 @@ function getDefaultHref(item: AttentionItem, prefix: string): string {
case "proposed_decision":
return `${prefix}/decisions`;
case "knowledge_silo":
- return `${prefix}/ownership`;
+ return `${prefix}/owners`;
case "ungoverned_hotspot":
- return `${prefix}/hotspots`;
+ return `${prefix}/code-health?tab=hotspots`;
case "dead_code":
- return `${prefix}/dead-code`;
+ return `${prefix}/code-health?tab=dead-code`;
default:
return prefix;
}
diff --git a/packages/ui/src/dashboard/commits-mini.tsx b/packages/ui/src/dashboard/commits-mini.tsx
new file mode 100644
index 000000000..17657fcd7
--- /dev/null
+++ b/packages/ui/src/dashboard/commits-mini.tsx
@@ -0,0 +1,97 @@
+import { GitCommit as GitCommitIcon } from "lucide-react";
+import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
+import { EmptyState } from "../shared/empty-state";
+import { formatRelativeTime } from "../lib/format";
+
+export interface CommitsMiniEntry {
+ sha: string;
+ short_sha: string;
+ subject: string;
+ author_name: string;
+ committed_at: string | null;
+ change_risk_level?: string | null;
+ risk_percentile?: number | null;
+}
+
+interface CommitsMiniProps {
+ commits: CommitsMiniEntry[];
+ repoId: string;
+ linkPrefix?: string;
+ previewCount?: number;
+}
+
+const RISK_DOT: Record<string, string> = {
+ high: "bg-[var(--color-error)]",
+ moderate: "bg-[var(--color-caution)]",
+ low: "bg-[var(--color-success)]",
+};
+
+/** Recent-commits feed for the Overview Pulse tab — real activity, linked
+ * through to the commits page (`?commit=` opens the detail sheet). */
+export function CommitsMini({ commits, repoId, linkPrefix, previewCount = 8 }: CommitsMiniProps) {
+ const prefix = linkPrefix ?? `/repos/${repoId}`;
+ const shown = commits.slice(0, previewCount);
+
+ if (shown.length === 0) {
+ return (
+ <Card>
+ <CardContent className="p-0">
+ <EmptyState
+ icon={<GitCommitIcon className="h-8 w-8" />}
+ title="No commit history"
+ description="Commit activity appears once git history is indexed."
+ />
+ </CardContent>
+ </Card>
+ );
+ }
+
+ return (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm flex items-center justify-between">
+ <span className="flex items-center gap-2">
+ <GitCommitIcon className="h-4 w-4 text-[var(--color-text-secondary)]" />
+ Recent Commits
+ </span>
+ <a
+ href={`${prefix}/commits`}
+ className="text-[10px] text-[var(--color-accent-primary)] hover:underline font-normal"
+ >
+ View all
+ </a>
+ </CardTitle>
+ </CardHeader>
+ <CardContent className="pt-0">
+ <div className="space-y-1.5">
+ {shown.map((c) => (
+ <a
+ key={c.sha}
+ href={`${prefix}/commits?commit=${c.sha}`}
+ className="flex items-center gap-2.5 -mx-2 px-2 py-1 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"
+ >
+ <span
+ className={`h-2 w-2 rounded-full shrink-0 ${
+ RISK_DOT[c.change_risk_level ?? ""] ?? "bg-[var(--color-text-tertiary)]"
+ }`}
+ title={c.change_risk_level ? `${c.change_risk_level} change risk` : undefined}
+ />
+ <span className="text-[11px] font-mono text-[var(--color-text-tertiary)] shrink-0">
+ {c.short_sha}
+ </span>
+ <span className="text-xs text-[var(--color-text-primary)] truncate flex-1 min-w-0">
+ {c.subject}
+ </span>
+ <span className="text-[10px] text-[var(--color-text-tertiary)] shrink-0 hidden sm:inline">
+ {c.author_name}
+ </span>
+ <span className="text-[10px] text-[var(--color-text-tertiary)] tabular-nums shrink-0">
+ {c.committed_at ? formatRelativeTime(c.committed_at) : ""}
+ </span>
+ </a>
+ ))}
+ </div>
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/packages/ui/src/dashboard/community-summary-grid.tsx b/packages/ui/src/dashboard/community-summary-grid.tsx
index a9877f2a8..f24e2b51f 100644
--- a/packages/ui/src/dashboard/community-summary-grid.tsx
+++ b/packages/ui/src/dashboard/community-summary-grid.tsx
@@ -7,6 +7,7 @@ import { Badge } from "../ui/badge";
import { ScrollArea } from "../ui/scroll-area";
import { Skeleton } from "../ui/skeleton";
import { truncatePath } from "../lib/format";
+import { fileEntityPath } from "../shared/entity/routes";
import { cn } from "../lib/cn";
import type {
CommunityDetail,
@@ -14,18 +15,29 @@ import type {
} from "@repowise-dev/types/graph";
const COMMUNITY_COLORS = [
- "bg-indigo-400", "bg-pink-400", "bg-emerald-400", "bg-amber-400",
- "bg-blue-400", "bg-purple-400", "bg-rose-400", "bg-teal-400",
- "bg-orange-400", "bg-cyan-400",
+ "bg-[var(--color-community-1)]",
+ "bg-[var(--color-community-2)]",
+ "bg-[var(--color-community-3)]",
+ "bg-[var(--color-community-4)]",
+ "bg-[var(--color-community-5)]",
+ "bg-[var(--color-community-6)]",
+ "bg-[var(--color-community-7)]",
+ "bg-[var(--color-community-8)]",
+ "bg-[var(--color-community-9)]",
+ "bg-[var(--color-community-10)]",
+ "bg-[var(--color-community-11)]",
+ "bg-[var(--color-community-12)]",
];
interface DetailPanelProps {
detail: CommunityDetail | null;
isLoading: boolean;
onClose: () => void;
+ /** Build a member href — defaults to the canonical file page. */
+ memberHref?: ((path: string) => string) | undefined;
}
-function DetailPanel({ detail, isLoading, onClose }: DetailPanelProps) {
+function DetailPanel({ detail, isLoading, onClose, memberHref }: DetailPanelProps) {
if (isLoading) {
return (
<div className="p-4 space-y-2">
@@ -60,12 +72,22 @@ function DetailPanel({ detail, isLoading, onClose }: DetailPanelProps) {
<div className="space-y-1">
{detail.members.slice(0, 20).map((m) => (
<div key={m.path} className="flex items-center justify-between gap-2 py-0.5">
- <span
- className="text-[11px] font-mono text-[var(--color-text-secondary)] truncate"
- title={m.path}
- >
- {truncatePath(m.path)}
- </span>
+ {memberHref ? (
+ <a
+ href={memberHref(m.path)}
+ className="text-[11px] font-mono text-[var(--color-text-secondary)] truncate hover:text-[var(--color-accent-primary)] hover:underline"
+ title={m.path}
+ >
+ {truncatePath(m.path)}
+ </a>
+ ) : (
+ <span
+ className="text-[11px] font-mono text-[var(--color-text-secondary)] truncate"
+ title={m.path}
+ >
+ {truncatePath(m.path)}
+ </span>
+ )}
<div className="flex items-center gap-1 shrink-0">
{m.is_entry_point && (
<Badge variant="accent" className="text-[8px] h-3.5">
@@ -148,7 +170,7 @@ export function CommunitySummaryGrid({
Architecture Communities ({communities.length})
</CardTitle>
{prefix && (
- <a href={`${prefix}/graph?colorMode=community`} className="text-[10px] text-[var(--color-accent-primary)] hover:underline">
+ <a href={`${prefix}/architecture?view=graph&colorMode=community`} className="text-[10px] text-[var(--color-accent-primary)] hover:underline">
View in Graph →
</a>
)}
@@ -201,6 +223,7 @@ export function CommunitySummaryGrid({
detail={details[c.community_id] ?? null}
isLoading={loadingDetailId === c.community_id && !details[c.community_id]}
onClose={() => setExpandedId(null)}
+ memberHref={prefix ? (path) => fileEntityPath(prefix, path) : undefined}
/>
)}
</div>
diff --git a/packages/ui/src/dashboard/decisions-timeline.tsx b/packages/ui/src/dashboard/decisions-timeline.tsx
index 838dc12a8..e3ade8c95 100644
--- a/packages/ui/src/dashboard/decisions-timeline.tsx
+++ b/packages/ui/src/dashboard/decisions-timeline.tsx
@@ -3,10 +3,19 @@ import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { Badge } from "../ui/badge";
import { EmptyState } from "../shared/empty-state";
import { formatRelativeTime, stripMarkdown } from "../lib/format";
-import type { DecisionRecord } from "@repowise-dev/types/decisions";
+
+/** Structural slice of a decision record — anything with these fields renders
+ * (full DecisionRecord rows and the overview-summary slim slice both fit). */
+export interface DecisionsTimelineItem {
+ id: string;
+ title: string;
+ status: string;
+ created_at: string | null;
+ source?: string | null;
+}
interface DecisionsTimelineProps {
- decisions: DecisionRecord[];
+ decisions: DecisionsTimelineItem[];
repoId: string;
linkPrefix?: string;
}
@@ -86,7 +95,7 @@ export function DecisionsTimeline({ decisions, repoId, linkPrefix }: DecisionsTi
</Badge>
</div>
<span className="text-[10px] text-[var(--color-text-tertiary)]">
- {formatRelativeTime(d.created_at)}
+ {d.created_at ? formatRelativeTime(d.created_at) : ""}
{d.source && ` · ${d.source.replace("_", " ")}`}
</span>
</div>
diff --git a/packages/ui/src/dashboard/execution-flows-panel.tsx b/packages/ui/src/dashboard/execution-flows-panel.tsx
index db550fb15..6dde29ce9 100644
--- a/packages/ui/src/dashboard/execution-flows-panel.tsx
+++ b/packages/ui/src/dashboard/execution-flows-panel.tsx
@@ -107,7 +107,7 @@ export function ExecutionFlowsPanel({ flows, repoId, linkPrefix }: ExecutionFlow
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<CardTitle className="text-sm font-medium">Execution Flows</CardTitle>
- <a href={`${prefix}/graph?viewMode=architecture`} className="text-[10px] text-[var(--color-accent-primary)] hover:underline">
+ <a href={`${prefix}/architecture?view=graph&viewMode=architecture`} className="text-[10px] text-[var(--color-accent-primary)] hover:underline">
View in Graph →
</a>
</div>
diff --git a/packages/ui/src/dashboard/health-score-badge.tsx b/packages/ui/src/dashboard/health-score-badge.tsx
new file mode 100644
index 000000000..4acda7833
--- /dev/null
+++ b/packages/ui/src/dashboard/health-score-badge.tsx
@@ -0,0 +1,174 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { HelpCircle } from "lucide-react";
+import type { HealthScoreComponent } from "./health-score-ring";
+
+export interface HealthSparklinePoint {
+ taken_at: string | null;
+ /** Code-health average on the 1–10 scale. */
+ average_health: number;
+}
+
+interface HealthScoreBadgeProps {
+ /** Composite repo score, 0–100. */
+ score: number;
+ components?: HealthScoreComponent[];
+ note?: string;
+ /** Code-health snapshot history rendered as a small trend sparkline. */
+ history?: HealthSparklinePoint[];
+}
+
+function getScoreColor(score: number): string {
+ if (score >= 75) return "var(--color-success)";
+ if (score >= 50) return "var(--color-warning)";
+ return "var(--color-error)";
+}
+
+function getScoreLabel(score: number): string {
+ if (score >= 80) return "Excellent";
+ if (score >= 65) return "Good";
+ if (score >= 50) return "Fair";
+ if (score >= 30) return "Needs Work";
+ return "Critical";
+}
+
+function Sparkline({ points }: { points: HealthSparklinePoint[] }) {
+ const w = 64;
+ const h = 20;
+ const values = points.map((p) => p.average_health);
+ const min = Math.min(...values);
+ const max = Math.max(...values);
+ const span = max - min || 1;
+ const step = values.length > 1 ? w / (values.length - 1) : w;
+ const path = values
+ .map((v, i) => {
+ const x = i * step;
+ const y = h - 2 - ((v - min) / span) * (h - 4);
+ return `${i === 0 ? "M" : "L"}${x.toFixed(1)},${y.toFixed(1)}`;
+ })
+ .join(" ");
+ const latest = values[values.length - 1] ?? 0;
+ return (
+ <svg
+ width={w}
+ height={h}
+ className="shrink-0"
+ role="img"
+ aria-label={`Code health trend, latest ${latest.toFixed(1)}/10`}
+ >
+ <title>{`Code health (avg) trend — latest ${latest.toFixed(1)}/10`}</title>
+ <path
+ d={path}
+ fill="none"
+ stroke="var(--color-accent-primary)"
+ strokeWidth={1.5}
+ strokeLinecap="round"
+ />
+ </svg>
+ );
+}
+
+/**
+ * Compact header twin of `HealthScoreRing`: score chip + label, an optional
+ * code-health trend sparkline, and the same "Why this score?" breakdown in a
+ * click-toggled dropdown. Used where the full ring would dominate the layout.
+ */
+export function HealthScoreBadge({ score, components, note, history }: HealthScoreBadgeProps) {
+ const [open, setOpen] = useState(false);
+ const rootRef = useRef<HTMLDivElement>(null);
+ const color = getScoreColor(score);
+ const hasBreakdown = !!components && components.length > 0;
+
+ useEffect(() => {
+ if (!open) return;
+ const onPointerDown = (e: PointerEvent) => {
+ if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpen(false);
+ };
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") setOpen(false);
+ };
+ document.addEventListener("pointerdown", onPointerDown);
+ document.addEventListener("keydown", onKey);
+ return () => {
+ document.removeEventListener("pointerdown", onPointerDown);
+ document.removeEventListener("keydown", onKey);
+ };
+ }, [open]);
+
+ return (
+ <div ref={rootRef} className="relative inline-flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => hasBreakdown && setOpen((v) => !v)}
+ aria-expanded={open}
+ aria-haspopup={hasBreakdown ? "dialog" : undefined}
+ className={`inline-flex items-center gap-2 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2.5 py-1 ${
+ hasBreakdown ? "hover:border-[var(--color-accent-primary)] transition-colors" : "cursor-default"
+ }`}
+ >
+ <span className="text-sm font-bold tabular-nums" style={{ color }}>
+ {Math.round(score)}
+ </span>
+ <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ {getScoreLabel(score)}
+ </span>
+ {history && history.length >= 2 && <Sparkline points={history} />}
+ {hasBreakdown && (
+ <HelpCircle className="h-3 w-3 text-[var(--color-text-tertiary)]" aria-hidden />
+ )}
+ </button>
+
+ {open && hasBreakdown && (
+ <div
+ role="dialog"
+ aria-label="Score breakdown"
+ className="absolute left-0 top-full z-30 mt-2 w-72 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-3 text-xs space-y-2 shadow-lg"
+ >
+ <p className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ Score = weighted average of {components!.length} components
+ </p>
+ {note && (
+ <p className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1.5 text-[11px] leading-snug text-[var(--color-text-secondary)]">
+ {note}
+ </p>
+ )}
+ <ul className="space-y-2">
+ {components!.map((c) => {
+ const barColor =
+ c.score >= 75
+ ? "var(--color-success)"
+ : c.score >= 50
+ ? "var(--color-warning)"
+ : "var(--color-error)";
+ return (
+ <li key={c.key} className="space-y-1">
+ <div className="flex items-baseline justify-between gap-3">
+ <span className="text-[var(--color-text-primary)]">
+ {c.label}{" "}
+ <span className="text-[var(--color-text-tertiary)]">
+ ({Math.round(c.weight * 100)}%)
+ </span>
+ </span>
+ <span className="tabular-nums text-[var(--color-text-secondary)]">
+ {Math.round(c.score)}/100
+ </span>
+ </div>
+ <div className="h-1 w-full overflow-hidden rounded-full bg-[var(--color-bg-surface)]">
+ <div
+ className="h-full transition-[width] duration-300"
+ style={{ width: `${c.score}%`, background: barColor }}
+ />
+ </div>
+ {c.detail && (
+ <p className="text-[10px] text-[var(--color-text-tertiary)]">{c.detail}</p>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/packages/ui/src/dashboard/hotspots-mini.tsx b/packages/ui/src/dashboard/hotspots-mini.tsx
index 3e2391efc..e654cb11c 100644
--- a/packages/ui/src/dashboard/hotspots-mini.tsx
+++ b/packages/ui/src/dashboard/hotspots-mini.tsx
@@ -2,6 +2,7 @@ import { Flame } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { EmptyState } from "../shared/empty-state";
import { truncatePath } from "../lib/format";
+import { fileEntityPath } from "../shared/entity/routes";
import type { Hotspot } from "@repowise-dev/types/git";
interface HotspotsMiniProps {
@@ -65,7 +66,7 @@ export function HotspotsMini({
</span>
</span>
<a
- href={`${prefix}/hotspots`}
+ href={`${prefix}/code-health?tab=hotspots`}
className="text-[10px] text-[var(--color-accent-primary)] hover:underline font-normal"
>
View all
@@ -77,7 +78,7 @@ export function HotspotsMini({
{top.map((h) => (
<a
key={h.file_path}
- href={`${prefix}/graph?node=${encodeURIComponent(h.file_path)}`}
+ href={fileEntityPath(prefix, h.file_path)}
className="flex items-center gap-3 -mx-2 px-2 py-0.5 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"
>
<div className="w-16 shrink-0">
diff --git a/packages/ui/src/dashboard/index.ts b/packages/ui/src/dashboard/index.ts
index 7561f9cf4..e3d01d342 100644
--- a/packages/ui/src/dashboard/index.ts
+++ b/packages/ui/src/dashboard/index.ts
@@ -1,5 +1,9 @@
export * from "./attention-panel";
+export * from "./commits-mini";
export * from "./decisions-timeline";
+export * from "./health-score-badge";
+export * from "./savings-mini";
+export * from "./where-to-start";
export * from "./dependency-heatmap";
export * from "./execution-flows-panel";
export * from "./health-score-ring";
diff --git a/packages/ui/src/dashboard/module-minimap.tsx b/packages/ui/src/dashboard/module-minimap.tsx
index 1365311b0..23f14104f 100644
--- a/packages/ui/src/dashboard/module-minimap.tsx
+++ b/packages/ui/src/dashboard/module-minimap.tsx
@@ -118,7 +118,7 @@ export function ModuleMinimap({ nodes, edges, repoId, linkPrefix }: ModuleMinima
Architecture
</span>
<a
- href={`${prefix}/graph`}
+ href={`${prefix}/architecture?view=graph`}
className="text-[10px] text-[var(--color-accent-primary)] hover:underline font-normal"
>
Full graph
diff --git a/packages/ui/src/dashboard/module-overview-grid.tsx b/packages/ui/src/dashboard/module-overview-grid.tsx
index c4043832f..1f1061753 100644
--- a/packages/ui/src/dashboard/module-overview-grid.tsx
+++ b/packages/ui/src/dashboard/module-overview-grid.tsx
@@ -52,7 +52,7 @@ export function ModuleOverviewGrid({ nodes, edges, repoId, linkPrefix, initialVi
</span>
</span>
<a
- href={`${prefix}/graph`}
+ href={`${prefix}/architecture?view=graph`}
className="text-[10px] text-[var(--color-accent-primary)] hover:underline font-normal"
>
Full graph →
@@ -72,7 +72,7 @@ export function ModuleOverviewGrid({ nodes, edges, repoId, linkPrefix, initialVi
return (
<a
key={m.module_id}
- href={`${prefix}/graph?node=${encodeURIComponent(m.module_id)}`}
+ href={`${prefix}/architecture?view=graph&node=${encodeURIComponent(m.module_id)}`}
className="group rounded-lg border border-[var(--color-border-default)] p-3 hover:border-[var(--color-border-hover)] hover:bg-[var(--color-bg-elevated)] transition-colors"
>
<p className="text-xs font-medium text-[var(--color-text-primary)] truncate mb-2" title={m.module_id}>
diff --git a/packages/ui/src/dashboard/savings-mini.tsx b/packages/ui/src/dashboard/savings-mini.tsx
index f721e24d1..8096c6963 100644
--- a/packages/ui/src/dashboard/savings-mini.tsx
+++ b/packages/ui/src/dashboard/savings-mini.tsx
@@ -1,7 +1,16 @@
import { Sparkles } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { formatCost, formatTokens } from "../lib/format";
-import type { DistillSavingsData } from "../costs/distill-savings-card";
+
+/** Structural slice of the savings rollup this tile renders — the full
+ * /distill-savings payload and the overview-summary headline both fit. */
+export interface SavingsMiniData {
+ available: boolean;
+ saved_tokens?: number;
+ mcp_tokens?: number;
+ estimated_usd_saved?: number;
+ pricing_model?: string;
+}
const LANG_COLORS: Record<string, string> = {
python: "var(--color-lang-python)",
@@ -20,8 +29,9 @@ function getLangColor(lang: string): string {
}
interface SavingsMiniProps {
- /** Rollup from /distill-savings; null/undefined when unavailable. */
- data?: DistillSavingsData | null;
+ /** Rollup from /distill-savings (or the overview-summary headline);
+ * null/undefined when unavailable. */
+ data?: SavingsMiniData | null;
/** Repo id, for the "View costs →" link. */
repoId: string;
/** Language → file-count map, rendered as a composition strip below savings. */
@@ -79,7 +89,7 @@ export function SavingsMini({ data, repoId, langDistribution, langHref }: Saving
{formatTokens(total)}
</span>
<span className="text-base font-semibold tabular-nums text-green-500">
- {formatCost(data!.estimated_usd_saved)}
+ {formatCost(data!.estimated_usd_saved ?? 0)}
</span>
</div>
<p className="text-[11px] text-[var(--color-text-secondary)] -mt-1">
diff --git a/packages/ui/src/dashboard/where-to-start.tsx b/packages/ui/src/dashboard/where-to-start.tsx
new file mode 100644
index 000000000..ba8585502
--- /dev/null
+++ b/packages/ui/src/dashboard/where-to-start.tsx
@@ -0,0 +1,66 @@
+import { Compass } from "lucide-react";
+import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
+import { formatNumber, truncatePath } from "../lib/format";
+import { fileEntityPath } from "../shared/entity/routes";
+
+export interface WhereToStartTarget {
+ path: string;
+ pagerank: number;
+ doc_words: number;
+}
+
+interface WhereToStartCardProps {
+ /** Onboarding targets: high-centrality files with the least documentation. */
+ targets: WhereToStartTarget[];
+ repoId: string;
+ linkPrefix?: string;
+ previewCount?: number;
+}
+
+/**
+ * "Where do I start reading?" — the onboarding-targets list promoted from
+ * the old Overview Ownership tab. Rows link to the canonical file page.
+ */
+export function WhereToStartCard({
+ targets,
+ repoId,
+ linkPrefix,
+ previewCount = 5,
+}: WhereToStartCardProps) {
+ const prefix = linkPrefix ?? `/repos/${repoId}`;
+ if (targets.length === 0) return null;
+ const shown = targets.slice(0, previewCount);
+
+ return (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm flex items-center gap-2">
+ <Compass className="h-4 w-4 text-[var(--color-accent-primary)]" />
+ Where to start
+ </CardTitle>
+ </CardHeader>
+ <CardContent className="pt-0">
+ <p className="text-[11px] text-[var(--color-text-tertiary)] mb-2">
+ Central files with the least documentation — high-leverage reading.
+ </p>
+ <ul className="space-y-1">
+ {shown.map((t) => (
+ <li key={t.path}>
+ <a
+ href={fileEntityPath(prefix, t.path)}
+ className="block -mx-2 px-2 py-1 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"
+ >
+ <p className="text-[11px] font-mono text-[var(--color-text-primary)] truncate">
+ {truncatePath(t.path, 44)}
+ </p>
+ <p className="text-[10px] text-[var(--color-text-tertiary)]">
+ pagerank {t.pagerank.toFixed(4)} · {formatNumber(t.doc_words)} doc words
+ </p>
+ </a>
+ </li>
+ ))}
+ </ul>
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/packages/ui/src/decisions/decision-evidence-drawer.tsx b/packages/ui/src/decisions/decision-evidence-drawer.tsx
index 67343532f..8d42a6d3c 100644
--- a/packages/ui/src/decisions/decision-evidence-drawer.tsx
+++ b/packages/ui/src/decisions/decision-evidence-drawer.tsx
@@ -91,8 +91,8 @@ export function DecisionEvidenceDrawer({
)}
{!isLoading && !error && sorted && sorted.length > 0 && (
<ul className="space-y-3">
- {sorted.map((row) => (
- <EvidenceRow key={row.id} row={row} />
+ {sorted.map((row, i) => (
+ <EvidenceRow key={row.id} row={row} isPrimary={i === 0} />
))}
</ul>
)}
@@ -103,7 +103,7 @@ export function DecisionEvidenceDrawer({
);
}
-function EvidenceRow({ row }: { row: DecisionEvidence }) {
+function EvidenceRow({ row, isPrimary }: { row: DecisionEvidence; isPrimary?: boolean }) {
return (
<li className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/40 p-3">
<div className="mb-2 flex flex-wrap items-center gap-2">
@@ -111,9 +111,21 @@ function EvidenceRow({ row }: { row: DecisionEvidence }) {
<span className="text-xs text-[var(--color-text-secondary)]">
{SOURCE_LABEL[row.source] ?? row.source}
</span>
- <span className="text-[10px] text-[var(--color-text-tertiary)]">
- rank {row.source_rank}
- </span>
+ {isPrimary ? (
+ <span
+ className="rounded bg-[var(--color-accent-muted)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--color-accent-primary)]"
+ title="The most-trusted source backing this decision — its quote provides the headline fields. Higher rank = more trusted source type."
+ >
+ primary source
+ </span>
+ ) : (
+ <span
+ className="text-[10px] text-[var(--color-text-tertiary)]"
+ title="Source-type trust rank. Higher ranks are more trusted; the top-ranked row is the primary source."
+ >
+ rank {row.source_rank}
+ </span>
+ )}
<span className="ml-auto text-[10px] tabular-nums text-[var(--color-text-tertiary)]">
{Math.round(row.confidence * 100)}% confidence
</span>
diff --git a/packages/ui/src/decisions/decisions-table.tsx b/packages/ui/src/decisions/decisions-table.tsx
index 9f6811e09..9f27a15bf 100644
--- a/packages/ui/src/decisions/decisions-table.tsx
+++ b/packages/ui/src/decisions/decisions-table.tsx
@@ -2,6 +2,12 @@
import * as React from "react";
import { Badge } from "../ui/badge";
+import { ApiError } from "../shared/api-error";
+import { EmptyState } from "../shared/empty-state";
+import {
+ ResponsiveTable,
+ type ResponsiveColumn,
+} from "../shared/responsive-table";
import { VerificationBadge } from "./verification-badge";
import { stripMarkdown } from "../lib/format";
import type {
@@ -64,6 +70,138 @@ export function DecisionsTable({
}: DecisionsTableProps) {
const prefix = linkPrefix ?? `/repos/${repoId}`;
const Link = LinkComponent;
+
+ const columns: ResponsiveColumn<DecisionRecord>[] = [
+ {
+ key: "title",
+ header: "Title",
+ priority: 1,
+ cellClassName: "min-w-[200px] max-w-[520px]",
+ render: (d) => (
+ <div className="min-w-0">
+ <Link
+ href={`${prefix}/decisions/${d.id}`}
+ className="font-medium text-[var(--color-text-primary)] hover:text-[var(--color-accent-primary)] hover:underline block truncate"
+ title={stripMarkdown(d.title)}
+ >
+ {stripMarkdown(d.title)}
+ </Link>
+ {d.evidence_preview?.source_quote && (
+ <p
+ className="mt-0.5 truncate text-[11px] italic text-[var(--color-text-tertiary)]"
+ title={`${d.evidence_preview.source_quote}${
+ d.evidence_preview.evidence_file
+ ? ` — ${d.evidence_preview.evidence_file}${
+ d.evidence_preview.evidence_line != null
+ ? `:${d.evidence_preview.evidence_line}`
+ : ""
+ }`
+ : ""
+ }`}
+ >
+ “{d.evidence_preview.source_quote}”
+ {(d.evidence_count ?? 0) > 1 && (
+ <span className="ml-1 not-italic">
+ +{(d.evidence_count ?? 0) - 1} more
+ </span>
+ )}
+ </p>
+ )}
+ </div>
+ ),
+ },
+ {
+ key: "status",
+ header: "Status",
+ priority: 1,
+ render: (d) => <Badge variant={STATUS_VARIANT[d.status] ?? "outline"}>{d.status}</Badge>,
+ },
+ {
+ key: "source",
+ header: "Source",
+ priority: 3,
+ cellClassName: "text-[var(--color-text-secondary)]",
+ render: (d) => SOURCE_LABEL[d.source] ?? d.source,
+ },
+ {
+ key: "trust",
+ header: "Trust",
+ priority: 3,
+ render: (d) =>
+ d.verification ? (
+ <VerificationBadge verification={d.verification} iconOnly />
+ ) : (
+ <span className="text-[var(--color-text-tertiary)]">—</span>
+ ),
+ },
+ {
+ key: "confidence",
+ header: "Confidence",
+ mobileLabel: "Conf",
+ align: "right",
+ priority: 2,
+ cellClassName: "tabular-nums text-[var(--color-text-secondary)]",
+ render: (d) => `${Math.round(d.confidence * 100)}%`,
+ },
+ {
+ key: "tags",
+ header: "Tags",
+ priority: 3,
+ render: (d) => (
+ <div className="flex flex-wrap gap-1">
+ {d.tags.slice(0, 3).map((tag) => (
+ <span
+ key={tag}
+ className="inline-block rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-xs text-[var(--color-text-tertiary)]"
+ >
+ {tag}
+ </span>
+ ))}
+ {d.tags.length > 3 && (
+ <span
+ className="inline-block rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-xs text-[var(--color-text-tertiary)]"
+ title={d.tags.slice(3).join(", ")}
+ >
+ +{d.tags.length - 3}
+ </span>
+ )}
+ </div>
+ ),
+ },
+ {
+ key: "staleness",
+ header: "Staleness",
+ mobileLabel: "Stale",
+ align: "right",
+ priority: 2,
+ render: (d) => (
+ <span className="tabular-nums" title="0 = fresh, 1 = fully stale">
+ {d.staleness_score > 0.5 ? (
+ <span className="text-[var(--color-error)]">{Math.round(d.staleness_score * 100)}%</span>
+ ) : d.staleness_score > 0 ? (
+ <span className="text-[var(--color-text-tertiary)]">{Math.round(d.staleness_score * 100)}%</span>
+ ) : (
+ <span className="text-[var(--color-text-tertiary)]">—</span>
+ )}
+ </span>
+ ),
+ },
+ ];
+
+ const empty =
+ isLoading ? undefined : error ? (
+ <ApiError
+ title="Couldn't load decisions"
+ message="An error occurred while fetching decisions."
+ {...(onRetry ? { onRetry } : {})}
+ />
+ ) : (
+ <EmptyState
+ title="No decisions found"
+ description="No architectural decisions match the current filters."
+ />
+ );
+
return (
<div className="space-y-4">
{/* Filters */}
@@ -98,108 +236,12 @@ export function DecisionsTable({
</select>
</div>
- {/* Table */}
- <div className="overflow-x-auto rounded-lg border border-[var(--color-border-default)]">
- <table className="w-full text-sm">
- <caption className="sr-only">Architectural decisions</caption>
- <thead className="sticky top-0 z-10 bg-[var(--color-bg-elevated)]">
- <tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">
- <th scope="col" className="px-4 py-2.5 text-left font-medium text-[var(--color-text-secondary)]">Title</th>
- <th scope="col" className="px-4 py-2.5 text-left font-medium text-[var(--color-text-secondary)]">Status</th>
- <th scope="col" className="px-4 py-2.5 text-left font-medium text-[var(--color-text-secondary)]">Source</th>
- <th scope="col" className="px-4 py-2.5 text-left font-medium text-[var(--color-text-secondary)]">Trust</th>
- <th scope="col" className="px-4 py-2.5 text-right font-medium text-[var(--color-text-secondary)]">Confidence</th>
- <th scope="col" className="px-4 py-2.5 text-left font-medium text-[var(--color-text-secondary)]">Tags</th>
- <th scope="col" className="px-4 py-2.5 text-right font-medium text-[var(--color-text-secondary)]">Staleness</th>
- </tr>
- </thead>
- <tbody>
- {decisions?.map((d) => (
- <tr
- key={d.id}
- className="border-b border-[var(--color-border-default)] transition-colors hover:bg-[var(--color-bg-elevated)]"
- >
- <td className="px-4 py-2.5 min-w-[240px] max-w-[520px]">
- <Link
- href={`${prefix}/decisions/${d.id}`}
- className="font-medium text-[var(--color-text-primary)] hover:text-[var(--color-accent-primary)] hover:underline block truncate"
- title={stripMarkdown(d.title)}
- >
- {stripMarkdown(d.title)}
- </Link>
- </td>
- <td className="px-4 py-2.5">
- <Badge variant={STATUS_VARIANT[d.status] ?? "outline"}>{d.status}</Badge>
- </td>
- <td className="px-4 py-2.5 text-[var(--color-text-secondary)]">
- {SOURCE_LABEL[d.source] ?? d.source}
- </td>
- <td className="px-4 py-2.5">
- {d.verification ? (
- <VerificationBadge verification={d.verification} iconOnly />
- ) : (
- <span className="text-[var(--color-text-tertiary)]">—</span>
- )}
- </td>
- <td className="px-4 py-2.5 text-right tabular-nums text-[var(--color-text-secondary)]">
- {Math.round(d.confidence * 100)}%
- </td>
- <td className="px-4 py-2.5">
- <div className="flex flex-wrap gap-1">
- {d.tags.slice(0, 3).map((tag) => (
- <span
- key={tag}
- className="inline-block rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-xs text-[var(--color-text-tertiary)]"
- >
- {tag}
- </span>
- ))}
- {d.tags.length > 3 && (
- <span
- className="inline-block rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-xs text-[var(--color-text-tertiary)]"
- title={d.tags.slice(3).join(", ")}
- >
- +{d.tags.length - 3}
- </span>
- )}
- </div>
- </td>
- <td className="px-4 py-2.5 text-right tabular-nums" title="0 = fresh, 1 = fully stale">
- {d.staleness_score > 0.5 ? (
- <span className="text-red-500">{Math.round(d.staleness_score * 100)}%</span>
- ) : d.staleness_score > 0 ? (
- <span className="text-[var(--color-text-tertiary)]">{Math.round(d.staleness_score * 100)}%</span>
- ) : (
- <span className="text-[var(--color-text-tertiary)]">—</span>
- )}
- </td>
- </tr>
- ))}
- {!decisions?.length && Boolean(error) && !isLoading && (
- <tr>
- <td colSpan={7} className="px-4 py-8 text-center text-[var(--color-outdated)]">
- Couldn&apos;t load decisions.{" "}
- {onRetry && (
- <button
- onClick={onRetry}
- className="underline text-[var(--color-accent-primary)] hover:text-[var(--color-text-primary)]"
- >
- Retry
- </button>
- )}
- </td>
- </tr>
- )}
- {!decisions?.length && !error && !isLoading && (
- <tr>
- <td colSpan={7} className="px-4 py-8 text-center text-[var(--color-text-tertiary)]">
- No decisions found
- </td>
- </tr>
- )}
- </tbody>
- </table>
- </div>
+ <ResponsiveTable
+ columns={columns}
+ rows={decisions ?? []}
+ rowKey={(d) => d.id}
+ empty={empty}
+ />
</div>
);
}
diff --git a/packages/ui/src/dependencies/dependency-registry.tsx b/packages/ui/src/dependencies/dependency-registry.tsx
new file mode 100644
index 000000000..56668244a
--- /dev/null
+++ b/packages/ui/src/dependencies/dependency-registry.tsx
@@ -0,0 +1,227 @@
+"use client";
+
+/**
+ * Dependency registry — the full `external_systems` table as a browsable
+ * inventory: grouped by category, filterable by ecosystem / manifest /
+ * dev-prod split, searchable by name. Presentational: data via props,
+ * manifest links via render prop.
+ */
+
+import { useMemo, useState, type ReactNode } from "react";
+import { Boxes, Cloud, Library, Search, Wrench, X } from "lucide-react";
+import type {
+ ExternalSystemEntry,
+ ExternalSystemsRegistry,
+} from "@repowise-dev/types/external-systems";
+import { EmptyState } from "../shared/empty-state";
+import { Badge } from "../ui/badge";
+import { cn } from "../lib/cn";
+
+const CATEGORY_ORDER = ["framework", "service", "tool", "library"] as const;
+
+const CATEGORY_META: Record<string, { label: string; icon: typeof Boxes }> = {
+ framework: { label: "Frameworks", icon: Boxes },
+ service: { label: "Services", icon: Cloud },
+ tool: { label: "Tools", icon: Wrench },
+ library: { label: "Libraries", icon: Library },
+};
+
+export interface DependencyRegistryProps {
+ data: ExternalSystemsRegistry;
+ /** Renders a manifest path as a link (e.g. to the file page). Falls back
+ * to plain text. */
+ renderManifestLink?: (declaredIn: string, children: ReactNode) => ReactNode;
+}
+
+type DepFilter = "all" | "prod" | "dev";
+
+export function DependencyRegistry({
+ data,
+ renderManifestLink,
+}: DependencyRegistryProps) {
+ const [query, setQuery] = useState("");
+ const [depFilter, setDepFilter] = useState<DepFilter>("all");
+ const [ecosystem, setEcosystem] = useState<string | null>(null);
+ const [manifest, setManifest] = useState<string | null>(null);
+
+ const filtered = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ return data.items.filter((e) => {
+ if (depFilter === "prod" && e.is_dev_dep) return false;
+ if (depFilter === "dev" && !e.is_dev_dep) return false;
+ if (ecosystem && e.ecosystem !== ecosystem) return false;
+ if (manifest && e.declared_in !== manifest) return false;
+ if (q && !e.name.toLowerCase().includes(q) && !e.display_name.toLowerCase().includes(q))
+ return false;
+ return true;
+ });
+ }, [data.items, query, depFilter, ecosystem, manifest]);
+
+ const grouped = useMemo(() => {
+ const groups = new Map<string, ExternalSystemEntry[]>();
+ for (const e of filtered) {
+ const key = CATEGORY_META[e.category] ? e.category : "library";
+ const list = groups.get(key);
+ if (list) list.push(e);
+ else groups.set(key, [e]);
+ }
+ return groups;
+ }, [filtered]);
+
+ if (data.total === 0) {
+ return (
+ <EmptyState
+ title="No dependencies recorded"
+ description="No manifest files (package.json, pyproject.toml, …) were parsed during indexing, or the repo declares no third-party dependencies."
+ />
+ );
+ }
+
+ return (
+ <div className="space-y-4">
+ {/* Summary strip */}
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-[var(--color-text-secondary)]">
+ <span>
+ <span className="font-semibold text-[var(--color-text-primary)] tabular-nums">{data.total}</span>{" "}
+ declared dependencies
+ </span>
+ <span className="tabular-nums">{data.prod_count} runtime</span>
+ <span className="tabular-nums">{data.dev_count} dev-only</span>
+ <span className="tabular-nums">
+ {data.ecosystems.length} ecosystem{data.ecosystems.length === 1 ? "" : "s"}
+ </span>
+ <span className="tabular-nums">
+ {data.manifests.length} manifest{data.manifests.length === 1 ? "" : "s"}
+ </span>
+ </div>
+
+ {/* Filters */}
+ <div className="flex flex-wrap items-center gap-2">
+ <div className="flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1.5">
+ <Search className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)]" />
+ <input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Search dependencies…"
+ aria-label="Search dependencies"
+ className="w-40 bg-transparent text-xs text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-tertiary)] sm:w-56"
+ />
+ {query && (
+ <button onClick={() => setQuery("")} aria-label="Clear search">
+ <X className="h-3 w-3 text-[var(--color-text-tertiary)]" />
+ </button>
+ )}
+ </div>
+
+ <div className="flex gap-0.5 rounded-md border border-[var(--color-border-default)] p-0.5">
+ {(["all", "prod", "dev"] as const).map((f) => (
+ <button
+ key={f}
+ onClick={() => setDepFilter(f)}
+ className={cn(
+ "rounded px-2 py-1 text-[11px] font-medium transition-colors",
+ depFilter === f
+ ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"
+ : "text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]",
+ )}
+ aria-pressed={depFilter === f}
+ >
+ {f === "all" ? "All" : f === "prod" ? "Runtime" : "Dev"}
+ </button>
+ ))}
+ </div>
+
+ {data.ecosystems.length > 1 && (
+ <select
+ value={ecosystem ?? ""}
+ onChange={(e) => setEcosystem(e.target.value || null)}
+ aria-label="Filter by ecosystem"
+ className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1.5 text-[11px] text-[var(--color-text-primary)] outline-none"
+ >
+ <option value="">All ecosystems</option>
+ {data.ecosystems.map((eco) => (
+ <option key={eco} value={eco}>
+ {eco}
+ </option>
+ ))}
+ </select>
+ )}
+
+ {data.manifests.length > 1 && (
+ <select
+ value={manifest ?? ""}
+ onChange={(e) => setManifest(e.target.value || null)}
+ aria-label="Filter by manifest"
+ className="max-w-[260px] rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1.5 text-[11px] text-[var(--color-text-primary)] outline-none"
+ >
+ <option value="">All manifests</option>
+ {data.manifests.map((m) => (
+ <option key={m} value={m}>
+ {m}
+ </option>
+ ))}
+ </select>
+ )}
+ </div>
+
+ {filtered.length === 0 ? (
+ <EmptyState
+ title="No dependencies match"
+ description="Adjust the search or filters to see more of the registry."
+ />
+ ) : (
+ CATEGORY_ORDER.filter((c) => grouped.has(c)).map((category) => {
+ const meta = CATEGORY_META[category]!;
+ const Icon = meta.icon;
+ const entries = grouped.get(category)!;
+ return (
+ <section key={category}>
+ <h3 className="mb-2 flex items-center gap-1.5 text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ <Icon className="h-3.5 w-3.5" />
+ {meta.label}
+ <span className="tabular-nums">({entries.length})</span>
+ </h3>
+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2 xl:grid-cols-3">
+ {entries.map((e) => (
+ <div
+ key={`${e.name}:${e.declared_in}`}
+ className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3"
+ >
+ <div className="flex items-start justify-between gap-2">
+ <p
+ className="min-w-0 truncate text-sm font-medium text-[var(--color-text-primary)]"
+ title={e.name}
+ >
+ {e.display_name || e.name}
+ </p>
+ <div className="flex shrink-0 items-center gap-1">
+ {e.is_dev_dep && (
+ <Badge variant="outline" className="text-[9px]">
+ dev
+ </Badge>
+ )}
+ <Badge variant="outline" className="text-[9px]">
+ {e.ecosystem}
+ </Badge>
+ </div>
+ </div>
+ <div className="mt-1.5 flex items-center justify-between gap-2 text-[11px] text-[var(--color-text-tertiary)]">
+ <span className="min-w-0 truncate font-mono" title={e.declared_in}>
+ {renderManifestLink
+ ? renderManifestLink(e.declared_in, e.declared_in)
+ : e.declared_in}
+ </span>
+ {e.version && (
+ <span className="shrink-0 font-mono tabular-nums">{e.version}</span>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ </section>
+ );
+ })
+ )}
+ </div>
+ );
+}
diff --git a/packages/ui/src/dependencies/index.ts b/packages/ui/src/dependencies/index.ts
new file mode 100644
index 000000000..2216b6a9c
--- /dev/null
+++ b/packages/ui/src/dependencies/index.ts
@@ -0,0 +1,4 @@
+export {
+ DependencyRegistry,
+ type DependencyRegistryProps,
+} from "./dependency-registry";
diff --git a/packages/ui/src/docs/docs-tree.tsx b/packages/ui/src/docs/docs-tree.tsx
index 2a84ebed3..66b421a50 100644
--- a/packages/ui/src/docs/docs-tree.tsx
+++ b/packages/ui/src/docs/docs-tree.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useMemo } from "react";
+import { useEffect, useState, useMemo } from "react";
import {
ChevronDown,
ChevronRight,
@@ -32,6 +32,9 @@ import type { DocPage } from "@repowise-dev/types/docs";
// real target_path (which never starts with "@") so directory lookups don't
// collide with module paths.
const ONBOARDING_DIR_KEY = "@onboarding";
+// Tree expansion survives reloads (per-browser, not per-repo — paths rarely
+// collide across repos and the fallback is just the default expansion).
+const EXPANDED_DIRS_KEY = "repowise:docs-tree-expanded";
// ---------------------------------------------------------------------------
// Types
@@ -781,15 +784,36 @@ export function DocsTree({ pages, selectedPageId, onSelectPage, className }: Doc
const [viewMode, setViewMode] = useState<ViewMode>("domain");
const [expandedDirs, setExpandedDirs] = useState<Set<string>>(() => {
// Auto-expand first two levels, the Onboarding folder, and every domain
- // section so both views open in a useful state.
+ // section so both views open in a useful state; then ADD any previously
+ // expanded dirs from localStorage. Union (not replace) — the key is
+ // shared across repos, so a stale saved set must never collapse another
+ // repo's default-open sections.
const dirs = new Set<string>(DOMAIN_SECTION_KEYS);
dirs.add(ONBOARDING_DIR_KEY);
for (const page of pages) {
const parts = page.target_path.split("/");
if (parts.length > 1 && parts[0]) dirs.add(parts[0]);
}
+ if (typeof window !== "undefined") {
+ try {
+ const saved = window.localStorage.getItem(EXPANDED_DIRS_KEY);
+ if (saved) for (const d of JSON.parse(saved) as string[]) dirs.add(d);
+ } catch {
+ // Corrupt state — defaults are fine.
+ }
+ }
return dirs;
});
+ useEffect(() => {
+ try {
+ window.localStorage.setItem(
+ EXPANDED_DIRS_KEY,
+ JSON.stringify([...expandedDirs]),
+ );
+ } catch {
+ // Quota/SSR — persistence is best-effort.
+ }
+ }, [expandedDirs]);
// Filters are a power-user affordance — start hidden so the panel opens
// calm; the funnel button shows a count when any filter is active.
const [showFilters, setShowFilters] = useState(false);
@@ -916,7 +940,8 @@ export function DocsTree({ pages, selectedPageId, onSelectPage, className }: Doc
</div>
)}
- {/* Stats line — quiet when everything is fresh */}
+ {/* Stats line — quiet when everything is fresh; dots get a legend the
+ moment any are shown. */}
<div className="text-[10px] text-[var(--color-text-tertiary)]">
{totalPages} pages
{needAttention === 0 ? (
@@ -924,6 +949,18 @@ export function DocsTree({ pages, selectedPageId, onSelectPage, className }: Doc
) : (
<span className="text-[var(--color-warning)]"> · {needAttention} need attention</span>
)}
+ {needAttention > 0 && (
+ <span className="ml-2 inline-flex items-center gap-2">
+ <span className="inline-flex items-center gap-1">
+ <span className="h-1.5 w-1.5 rounded-full bg-[var(--color-warning)]" />
+ stale
+ </span>
+ <span className="inline-flex items-center gap-1">
+ <span className="h-1.5 w-1.5 rounded-full bg-[var(--color-error)]" />
+ outdated
+ </span>
+ </span>
+ )}
</div>
</div>
diff --git a/packages/ui/src/files/file-coverage-tab.tsx b/packages/ui/src/files/file-coverage-tab.tsx
new file mode 100644
index 000000000..7cacdfa30
--- /dev/null
+++ b/packages/ui/src/files/file-coverage-tab.tsx
@@ -0,0 +1,76 @@
+import { Shield } from "lucide-react";
+import { EmptyState } from "../shared/empty-state";
+import { coverageColor } from "../health/tokens";
+import { formatRelativeTime } from "../lib/format";
+import type { FileDetailCoverage } from "@repowise-dev/types/files";
+
+interface FileCoverageTabProps {
+ coverage: FileDetailCoverage | null;
+ /**
+ * Shiki-highlighted source HTML where each `.line` carries a
+ * `data-covered="y" | "n"` attribute (host adds it via a transformer).
+ * When absent we fall back to a summary-only view.
+ */
+ coverageCodeHtml?: string | undefined;
+}
+
+export function FileCoverageTab({ coverage, coverageCodeHtml }: FileCoverageTabProps) {
+ if (!coverage) {
+ return (
+ <EmptyState
+ icon={<Shield className="h-8 w-8" />}
+ title="No coverage data"
+ description="Ingest a coverage report (repowise health --coverage <report>) to see line-level coverage here."
+ />
+ );
+ }
+
+ const pct = coverage.line_coverage_pct;
+ const coveredCount = coverage.covered_lines.length;
+
+ return (
+ <div className="space-y-4">
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2">
+ <span className="text-2xl font-semibold tabular-nums" style={{ color: coverageColor(pct) }}>
+ {pct.toFixed(1)}%
+ </span>
+ <span className="text-xs text-[var(--color-text-secondary)]">
+ {coveredCount.toLocaleString()} of {coverage.total_coverable_lines.toLocaleString()}{" "}
+ coverable lines hit
+ {coverage.branch_coverage_pct != null &&
+ ` · branches ${coverage.branch_coverage_pct.toFixed(1)}%`}
+ </span>
+ <span className="text-[10px] text-[var(--color-text-tertiary)] ml-auto">
+ {coverage.source_format}
+ {coverage.ingested_at && ` · ingested ${formatRelativeTime(coverage.ingested_at)}`}
+ {coverage.ingested_commit_sha && ` @ ${coverage.ingested_commit_sha.slice(0, 7)}`}
+ </span>
+ </div>
+ <div className="h-2 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]">
+ <div
+ className="h-full rounded-full"
+ style={{ width: `${pct}%`, background: coverageColor(pct) }}
+ />
+ </div>
+
+ {coverageCodeHtml ? (
+ <div className="coverage-code overflow-x-auto rounded-md border border-[var(--color-border-default)] text-xs leading-relaxed">
+ {/* Highlighted by the host through the shared shiki path; the
+ data-covered line attributes drive the gutter tint below. */}
+ <div dangerouslySetInnerHTML={{ __html: coverageCodeHtml }} />
+ <style>{`
+ .coverage-code pre { margin: 0; padding: 0.75rem 0; background: transparent !important; }
+ .coverage-code code { display: block; }
+ .coverage-code .line { display: inline-block; width: 100%; padding: 0 0.75rem 0 0.5rem; border-left: 3px solid transparent; }
+ .coverage-code .line[data-covered="y"] { border-left-color: var(--color-success); background: color-mix(in srgb, var(--color-success) 7%, transparent); }
+ .coverage-code .line[data-covered="n"] { border-left-color: var(--color-error); background: color-mix(in srgb, var(--color-error) 8%, transparent); }
+ `}</style>
+ </div>
+ ) : (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Source preview unavailable — coverage summary only.
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/packages/ui/src/files/file-doc-tab.tsx b/packages/ui/src/files/file-doc-tab.tsx
new file mode 100644
index 000000000..89774e497
--- /dev/null
+++ b/packages/ui/src/files/file-doc-tab.tsx
@@ -0,0 +1,74 @@
+import type { ReactNode } from "react";
+import { BookOpen } from "lucide-react";
+import { EmptyState } from "../shared/empty-state";
+import { Badge } from "../ui/badge";
+import { formatRelativeTime } from "../lib/format";
+import type { FileWikiPageRef } from "@repowise-dev/types/files";
+
+interface FileDocTabProps {
+ wikiPage: FileWikiPageRef | null;
+ /** Server-rendered wiki content (the host renders markdown its own way). */
+ docSlot?: ReactNode | undefined;
+ /** Deep link into the docs reading surface. */
+ wikiHref?: string | undefined;
+}
+
+const FRESHNESS_CLASS: Record<string, string> = {
+ fresh: "text-[var(--color-success)] border-[var(--color-success)]/30",
+ stale: "text-[var(--color-warning)] border-[var(--color-warning)]/30",
+ outdated: "text-[var(--color-error)] border-[var(--color-error)]/30",
+};
+
+export function FileDocTab({ wikiPage, docSlot, wikiHref }: FileDocTabProps) {
+ if (!wikiPage) {
+ return (
+ <EmptyState
+ icon={<BookOpen className="h-8 w-8" />}
+ title="No documentation yet"
+ description="This file hasn't been documented. Run a sync to generate its wiki page."
+ />
+ );
+ }
+
+ return (
+ <div className="space-y-4">
+ <div className="flex flex-wrap items-center gap-2">
+ <Badge
+ variant="outline"
+ className={`text-[10px] h-5 ${FRESHNESS_CLASS[wikiPage.freshness_status] ?? ""}`}
+ >
+ {wikiPage.freshness_status}
+ </Badge>
+ {wikiPage.updated_at && (
+ <span
+ className="text-[11px] text-[var(--color-text-tertiary)]"
+ title={new Date(wikiPage.updated_at).toLocaleString()}
+ >
+ updated {formatRelativeTime(wikiPage.updated_at)}
+ </span>
+ )}
+ {wikiHref && (
+ <a
+ href={wikiHref}
+ className="ml-auto text-[11px] text-[var(--color-accent-primary)] hover:underline"
+ >
+ Open in Docs →
+ </a>
+ )}
+ </div>
+ {wikiPage.human_notes && (
+ <div className="rounded-md border border-[var(--color-accent-primary)]/30 bg-[var(--color-bg-elevated)] p-3">
+ <p className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)] mb-1">
+ Team notes
+ </p>
+ <p className="text-xs text-[var(--color-text-secondary)] whitespace-pre-wrap">
+ {wikiPage.human_notes}
+ </p>
+ </div>
+ )}
+ <article className="prose prose-invert max-w-none leading-relaxed overflow-hidden">
+ {docSlot}
+ </article>
+ </div>
+ );
+}
diff --git a/packages/ui/src/files/file-graph-tab.tsx b/packages/ui/src/files/file-graph-tab.tsx
new file mode 100644
index 000000000..9c8df8a93
--- /dev/null
+++ b/packages/ui/src/files/file-graph-tab.tsx
@@ -0,0 +1,144 @@
+import { Network } from "lucide-react";
+import { EmptyState } from "../shared/empty-state";
+import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
+import { truncatePath } from "../lib/format";
+import type { FileDetailGraph, FileGraphNeighbor } from "@repowise-dev/types/files";
+
+interface FileGraphTabProps {
+ graph: FileDetailGraph | null;
+ filePath: string;
+ linkPrefix: string;
+ /** Build a file-page href for a neighbor file node. */
+ fileHref: (path: string) => string;
+ /** Build a symbol-page href for a neighbor symbol node. */
+ symbolHref: (symbolId: string) => string;
+}
+
+function NeighborList({
+ title,
+ neighbors,
+ fileHref,
+ symbolHref,
+}: {
+ title: string;
+ neighbors: FileGraphNeighbor[];
+ fileHref: (path: string) => string;
+ symbolHref: (symbolId: string) => string;
+}) {
+ return (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">
+ {title}{" "}
+ <span className="text-[10px] font-normal text-[var(--color-text-tertiary)] tabular-nums">
+ {neighbors.length}
+ </span>
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ {neighbors.length === 0 ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">None in the indexed graph.</p>
+ ) : (
+ <ul className="space-y-1">
+ {neighbors.map((n) => {
+ const isSymbol = n.node_type === "symbol" || n.node_id.includes("::");
+ const href = isSymbol ? symbolHref(n.node_id) : fileHref(n.node_id);
+ return (
+ <li key={`${n.node_id}-${n.edge_type}`}>
+ <a
+ href={href}
+ className="flex items-center gap-2 -mx-2 px-2 py-0.5 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"
+ >
+ <span className="text-[11px] font-mono text-[var(--color-text-primary)] truncate flex-1 min-w-0">
+ {truncatePath(n.node_id, 48)}
+ </span>
+ <span className="text-[10px] text-[var(--color-text-tertiary)] shrink-0">
+ {n.edge_type}
+ </span>
+ </a>
+ {n.imported_names.length > 0 && (
+ <p
+ className="pl-1 text-[10px] text-[var(--color-text-tertiary)] truncate"
+ title={n.imported_names.join(", ")}
+ >
+ {n.imported_names.slice(0, 6).join(", ")}
+ {n.imported_names.length > 6 && ` +${n.imported_names.length - 6}`}
+ </p>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
+
+export function FileGraphTab({ graph, filePath, linkPrefix, fileHref, symbolHref }: FileGraphTabProps) {
+ if (!graph) {
+ return (
+ <EmptyState
+ icon={<Network className="h-8 w-8" />}
+ title="Not in the dependency graph"
+ description="This file isn't part of the indexed graph (it may be excluded or unparsed)."
+ />
+ );
+ }
+
+ return (
+ <div className="space-y-4">
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
+ <Stat
+ label="PageRank"
+ value={`${Math.round(graph.pagerank_percentile)}th pct`}
+ hint={graph.pagerank.toFixed(6)}
+ />
+ <Stat label="Dependents (in)" value={String(graph.in_degree)} />
+ <Stat label="Dependencies (out)" value={String(graph.out_degree)} />
+ <Stat label="Community" value={graph.community_label ?? `#${graph.community_id}`} />
+ </div>
+ <div className="flex flex-wrap gap-2 text-[11px]">
+ <a
+ href={`${linkPrefix}/architecture?view=graph&node=${encodeURIComponent(filePath)}`}
+ className="text-[var(--color-accent-primary)] hover:underline"
+ >
+ Show in dependency graph →
+ </a>
+ <a
+ href={`${linkPrefix}/architecture?view=symbols&file=${encodeURIComponent(filePath)}`}
+ className="text-[var(--color-accent-primary)] hover:underline"
+ >
+ View symbols →
+ </a>
+ </div>
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
+ <NeighborList
+ title="Dependents"
+ neighbors={graph.dependents}
+ fileHref={fileHref}
+ symbolHref={symbolHref}
+ />
+ <NeighborList
+ title="Dependencies"
+ neighbors={graph.dependencies}
+ fileHref={fileHref}
+ symbolHref={symbolHref}
+ />
+ </div>
+ </div>
+ );
+}
+
+function Stat({ label, value, hint }: { label: string; value: string; hint?: string }) {
+ return (
+ <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-2.5">
+ <p className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)] mb-0.5">
+ {label}
+ </p>
+ <p className="text-sm font-semibold text-[var(--color-text-primary)]" title={hint}>
+ {value}
+ </p>
+ </div>
+ );
+}
diff --git a/packages/ui/src/files/file-health-tab.tsx b/packages/ui/src/files/file-health-tab.tsx
new file mode 100644
index 000000000..b0ea3f06d
--- /dev/null
+++ b/packages/ui/src/files/file-health-tab.tsx
@@ -0,0 +1,272 @@
+"use client";
+
+import { useState } from "react";
+import { HeartPulse } from "lucide-react";
+import { EmptyState } from "../shared/empty-state";
+import { ScoreBreakdown, type ScoreBreakdownCategory } from "../health/score-breakdown";
+import { BiomarkerDetails, type BiomarkerDetailsRecord } from "../health/biomarker-details";
+import { biomarkerInfo, biomarkerLabel, CATEGORY_LABEL } from "../health/biomarker-glossary";
+import { SEVERITY_CHIP, SEVERITY_LABEL, scoreBadgeClass, type Severity } from "../health/tokens";
+import type { FileDetailHealth, FunctionBlameRow } from "@repowise-dev/types/files";
+
+export type FindingStatus = "open" | "acknowledged" | "resolved" | "false_positive";
+
+const STATUS_OPTIONS: { value: FindingStatus; label: string }[] = [
+ { value: "open", label: "Open" },
+ { value: "acknowledged", label: "Acknowledged" },
+ { value: "resolved", label: "Resolved" },
+ { value: "false_positive", label: "False positive" },
+];
+
+interface FileHealthTabProps {
+ health: FileDetailHealth;
+ functionBlame: FunctionBlameRow[];
+ /** Triage callback — PATCH the finding status. Buttons hide when absent. */
+ onFindingStatusChange?:
+ | ((findingId: string, status: FindingStatus) => Promise<void> | void)
+ | undefined;
+ /** Build an href for a co-change partner file (hidden-coupling details). */
+ partnerHref?: ((path: string) => string) | undefined;
+ /** Build a symbol-page href for a function row. */
+ symbolHref?: ((symbolId: string) => string) | undefined;
+}
+
+function medianAgeDays(medianAuthorTime: number | null): number | null {
+ if (!medianAuthorTime) return null;
+ return Math.max(0, Math.round((Date.now() / 1000 - medianAuthorTime) / 86400));
+}
+
+export function FileHealthTab({
+ health,
+ functionBlame,
+ onFindingStatusChange,
+ partnerHref,
+ symbolHref,
+}: FileHealthTabProps) {
+ const [statusOverride, setStatusOverride] = useState<Record<string, FindingStatus>>({});
+ const [savingId, setSavingId] = useState<string | null>(null);
+ const { metric, breakdown, findings } = health;
+
+ if (!metric && findings.length === 0) {
+ return (
+ <EmptyState
+ icon={<HeartPulse className="h-8 w-8" />}
+ title="No health data"
+ description="Run repowise init (or repowise health) to score this file."
+ />
+ );
+ }
+
+ const setStatus = async (id: string, status: FindingStatus) => {
+ if (!onFindingStatusChange) return;
+ setSavingId(id);
+ try {
+ await onFindingStatusChange(id, status);
+ setStatusOverride((m) => ({ ...m, [id]: status }));
+ } finally {
+ setSavingId(null);
+ }
+ };
+
+ return (
+ <div className="space-y-5">
+ {metric && (
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
+ <Stat
+ label="Score"
+ value={
+ <span
+ className={`inline-flex items-baseline rounded px-2 py-0.5 font-bold tabular-nums ${scoreBadgeClass(metric.score)}`}
+ >
+ {metric.score.toFixed(1)}
+ <span className="ml-0.5 text-[10px] font-normal opacity-70">/10</span>
+ </span>
+ }
+ />
+ <Stat label="Max CCN" value={<Num v={metric.max_ccn} />} />
+ <Stat label="Max nesting" value={<Num v={metric.max_nesting} />} />
+ <Stat label="NLOC" value={<Num v={metric.nloc} />} />
+ <Stat label="Tests" value={<span className="text-xs">{metric.has_test_file ? "Paired" : "None"}</span>} />
+ <Stat
+ label="Coverage"
+ value={
+ <span className="text-xs tabular-nums">
+ {metric.line_coverage_pct == null ? "—" : `${metric.line_coverage_pct.toFixed(0)}%`}
+ </span>
+ }
+ />
+ <Stat
+ label="Duplication"
+ value={
+ <span className="text-xs tabular-nums">
+ {metric.duplication_pct == null ? "—" : `${metric.duplication_pct.toFixed(0)}%`}
+ </span>
+ }
+ />
+ <Stat label="Module" value={<span className="text-xs">{metric.module ?? "—"}</span>} />
+ </div>
+ )}
+
+ {breakdown && (
+ <section className="space-y-2">
+ <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ Why this score?
+ </h3>
+ <ScoreBreakdown
+ score={breakdown.score}
+ totalDeduction={breakdown.total_deduction}
+ categories={breakdown.categories as ScoreBreakdownCategory[]}
+ />
+ </section>
+ )}
+
+ {findings.length > 0 && (
+ <section className="space-y-2">
+ <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ Findings ({findings.length})
+ </h3>
+ <ul className="space-y-2">
+ {findings.map((f) => {
+ const info = biomarkerInfo(f.biomarker_type);
+ const status = statusOverride[f.id] ?? (f.status as FindingStatus) ?? "open";
+ return (
+ <li
+ key={f.id}
+ className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3 space-y-1"
+ >
+ <div className="flex items-center gap-2 flex-wrap">
+ <span
+ className={`inline-block rounded px-1.5 py-px text-[10px] uppercase font-semibold ${SEVERITY_CHIP[f.severity as Severity]}`}
+ >
+ {SEVERITY_LABEL[f.severity as Severity]}
+ </span>
+ <span className="text-xs font-semibold text-[var(--color-text-primary)]">
+ {biomarkerLabel(f.biomarker_type)}
+ </span>
+ <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ {CATEGORY_LABEL[info.category]}
+ </span>
+ {f.function_name && (
+ <span className="text-xs font-mono text-[var(--color-text-tertiary)]">
+ {f.function_name}
+ {f.line_start ? `:${f.line_start}` : ""}
+ </span>
+ )}
+ <span className="ml-auto text-xs tabular-nums text-[var(--color-error)]">
+ −{f.health_impact.toFixed(2)}
+ </span>
+ </div>
+ <p className="text-xs text-[var(--color-text-secondary)]">{f.reason}</p>
+ <BiomarkerDetails
+ biomarkerType={f.biomarker_type}
+ details={f.details as BiomarkerDetailsRecord | null}
+ onPartnerHref={partnerHref}
+ />
+ {onFindingStatusChange && (
+ <div className="flex items-center gap-1.5 pt-1">
+ {STATUS_OPTIONS.map((opt) => (
+ <button
+ key={opt.value}
+ type="button"
+ disabled={savingId === f.id || status === opt.value}
+ onClick={() => setStatus(f.id, opt.value)}
+ className={`rounded border px-1.5 py-0.5 text-[10px] transition-colors ${
+ status === opt.value
+ ? "border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"
+ : "border-[var(--color-border-default)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"
+ }`}
+ >
+ {opt.label}
+ </button>
+ ))}
+ </div>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ </section>
+ )}
+
+ {functionBlame.length > 0 && (
+ <section className="space-y-2">
+ <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ Functions by churn
+ </h3>
+ <div className="overflow-x-auto rounded-md border border-[var(--color-border-default)]">
+ <table className="w-full text-xs">
+ <thead>
+ <tr className="border-b border-[var(--color-border-default)] text-left text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ <th className="px-3 py-2 font-medium">Function</th>
+ <th className="px-3 py-2 font-medium text-right">Mods</th>
+ <th className="px-3 py-2 font-medium text-right">Recent</th>
+ <th className="px-3 py-2 font-medium text-right">Median age</th>
+ <th className="px-3 py-2 font-medium">Owner</th>
+ </tr>
+ </thead>
+ <tbody>
+ {functionBlame.map((b) => {
+ const age = medianAgeDays(b.median_author_time);
+ const name = (
+ <span className="font-mono">
+ {b.function_name}
+ <span className="text-[var(--color-text-tertiary)]">:{b.start_line}</span>
+ </span>
+ );
+ return (
+ <tr
+ key={b.symbol_id}
+ className="border-b border-[var(--color-border-default)] last:border-0"
+ >
+ <td className="px-3 py-1.5 text-[var(--color-text-primary)]">
+ {symbolHref ? (
+ <a
+ href={symbolHref(b.symbol_id)}
+ className="hover:text-[var(--color-accent-primary)] hover:underline"
+ >
+ {name}
+ </a>
+ ) : (
+ name
+ )}
+ </td>
+ <td className="px-3 py-1.5 text-right tabular-nums">{b.mod_count}</td>
+ <td className="px-3 py-1.5 text-right tabular-nums">{b.recent_mod_count}</td>
+ <td className="px-3 py-1.5 text-right tabular-nums">
+ {age == null ? "—" : `${age}d`}
+ </td>
+ <td className="px-3 py-1.5 text-[var(--color-text-secondary)]">
+ {b.owner_name ?? "—"}
+ {b.owner_line_pct != null && (
+ <span className="text-[var(--color-text-tertiary)]">
+ {" "}
+ ({Math.round(b.owner_line_pct * 100)}%)
+ </span>
+ )}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ </section>
+ )}
+ </div>
+ );
+}
+
+function Stat({ label, value }: { label: string; value: React.ReactNode }) {
+ return (
+ <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-2.5">
+ <p className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)] mb-0.5">
+ {label}
+ </p>
+ <div className="text-[var(--color-text-primary)]">{value}</div>
+ </div>
+ );
+}
+
+function Num({ v }: { v: number }) {
+ return <span className="text-base font-semibold tabular-nums">{v}</span>;
+}
diff --git a/packages/ui/src/files/file-history-tab.tsx b/packages/ui/src/files/file-history-tab.tsx
new file mode 100644
index 000000000..a4228e79a
--- /dev/null
+++ b/packages/ui/src/files/file-history-tab.tsx
@@ -0,0 +1,205 @@
+import { GitBranch, Bot } from "lucide-react";
+import { EmptyState } from "../shared/empty-state";
+import { CommitCategorySparkline } from "../git/commit-category-sparkline";
+import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
+import { formatRelativeTime, truncatePath } from "../lib/format";
+import type { FileDetailGit } from "@repowise-dev/types/files";
+
+interface FileHistoryTabProps {
+ git: FileDetailGit | null;
+ linkPrefix: string;
+ /** Build a file-page href for a co-change partner. */
+ partnerHref: (path: string) => string;
+}
+
+const TIER_LABELS: Record<string, string> = {
+ "1": "near-autonomous",
+ "2": "human-driven",
+ "3": "assisted",
+};
+
+export function FileHistoryTab({ git, linkPrefix, partnerHref }: FileHistoryTabProps) {
+ if (!git) {
+ return (
+ <EmptyState
+ icon={<GitBranch className="h-8 w-8" />}
+ title="No git history"
+ description="Git metadata appears once the repository's history is indexed."
+ />
+ );
+ }
+
+ const hasCategories = Object.values(git.commit_categories ?? {}).some((v) => v > 0);
+ const agentPct =
+ git.agent.agent_authored_pct != null ? Math.round(git.agent.agent_authored_pct * 100) : null;
+
+ return (
+ <div className="space-y-4">
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
+ <Stat label="Commits (total)" value={git.commit_count_total ?? 0} />
+ <Stat label="Commits (90d)" value={git.commit_count_90d} />
+ <Stat label="Contributors" value={git.contributor_count} />
+ <Stat label="Bus factor" value={git.bus_factor} />
+ </div>
+
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">Significant commits</CardTitle>
+ </CardHeader>
+ <CardContent>
+ {git.significant_commits.length === 0 ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ No significant commits recorded.
+ </p>
+ ) : (
+ <ul className="space-y-1.5">
+ {git.significant_commits.slice(0, 8).map((c) => (
+ <li key={c.sha}>
+ <a
+ href={`${linkPrefix}/commits?commit=${c.sha}`}
+ className="flex items-center gap-2 -mx-2 px-2 py-1 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"
+ >
+ <span className="text-[11px] font-mono text-[var(--color-text-tertiary)] shrink-0">
+ {c.sha.slice(0, 8)}
+ </span>
+ <span className="text-xs text-[var(--color-text-primary)] truncate flex-1">
+ {c.message}
+ </span>
+ <span className="text-[10px] text-[var(--color-text-tertiary)] shrink-0">
+ {c.date ? formatRelativeTime(c.date) : ""}
+ </span>
+ </a>
+ </li>
+ ))}
+ </ul>
+ )}
+ </CardContent>
+ </Card>
+
+ <div className="space-y-4">
+ {hasCategories && (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">Commit mix</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <CommitCategorySparkline categories={git.commit_categories} />
+ </CardContent>
+ </Card>
+ )}
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium flex items-center gap-2">
+ <Bot className="h-4 w-4 text-[var(--color-text-secondary)]" />
+ Agent share
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ {git.agent.agent_commit_count === 0 ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ No agent-attributed commits on this file.
+ </p>
+ ) : (
+ <div className="space-y-2">
+ <p className="text-xs text-[var(--color-text-secondary)]">
+ <span className="text-base font-semibold tabular-nums text-[var(--color-text-primary)]">
+ {git.agent.agent_commit_count}
+ </span>{" "}
+ agent commit{git.agent.agent_commit_count === 1 ? "" : "s"}
+ {agentPct != null && ` · ${agentPct}% of indexed history`}
+ </p>
+ {Object.keys(git.agent.tier_counts).length > 0 && (
+ <div className="flex flex-wrap gap-1.5">
+ {Object.entries(git.agent.tier_counts).map(([tier, count]) => (
+ <span
+ key={tier}
+ className="rounded border border-[var(--color-border-default)] px-1.5 py-0.5 text-[10px] text-[var(--color-text-secondary)]"
+ >
+ {TIER_LABELS[tier] ?? `tier ${tier}`}: {count}
+ </span>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ </div>
+
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">Top authors</CardTitle>
+ </CardHeader>
+ <CardContent>
+ {git.top_authors.length === 0 ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">No author data.</p>
+ ) : (
+ <ul className="space-y-1">
+ {git.top_authors.slice(0, 6).map((a) => (
+ <li key={a.name} className="flex items-center justify-between gap-2">
+ <a
+ href={`${linkPrefix}/owners/${encodeURIComponent(a.name)}`}
+ className="text-xs text-[var(--color-text-primary)] hover:text-[var(--color-accent-primary)] hover:underline truncate"
+ >
+ {a.name}
+ </a>
+ <span className="text-[10px] tabular-nums text-[var(--color-text-tertiary)] shrink-0">
+ {a.commit_count} commits
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">Changes together with</CardTitle>
+ </CardHeader>
+ <CardContent>
+ {git.co_change_partners.length === 0 ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ No co-change partners detected.
+ </p>
+ ) : (
+ <ul className="space-y-1">
+ {git.co_change_partners.slice(0, 8).map((p) => (
+ <li key={p.file_path}>
+ <a
+ href={partnerHref(p.file_path)}
+ className="flex items-center justify-between gap-2 -mx-2 px-2 py-0.5 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"
+ >
+ <span className="text-[11px] font-mono text-[var(--color-text-primary)] truncate">
+ {truncatePath(p.file_path, 44)}
+ </span>
+ <span className="text-[10px] tabular-nums text-[var(--color-text-tertiary)] shrink-0">
+ ×{p.co_change_count}
+ </span>
+ </a>
+ </li>
+ ))}
+ </ul>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ </div>
+ );
+}
+
+function Stat({ label, value }: { label: string; value: number }) {
+ return (
+ <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-2.5">
+ <p className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)] mb-0.5">
+ {label}
+ </p>
+ <p className="text-base font-semibold tabular-nums text-[var(--color-text-primary)]">
+ {value}
+ </p>
+ </div>
+ );
+}
diff --git a/packages/ui/src/files/file-page-tabs.ts b/packages/ui/src/files/file-page-tabs.ts
new file mode 100644
index 000000000..3fdea0103
--- /dev/null
+++ b/packages/ui/src/files/file-page-tabs.ts
@@ -0,0 +1,4 @@
+/** Tab ids for the file entity page. Lives outside the client component so
+ * server components can validate `?tab=` values without importing client code. */
+export const FILE_PAGE_TABS = ["doc", "health", "history", "coverage", "graph"] as const;
+export type FilePageTab = (typeof FILE_PAGE_TABS)[number];
diff --git a/packages/ui/src/files/file-page.tsx b/packages/ui/src/files/file-page.tsx
new file mode 100644
index 000000000..182cbe71a
--- /dev/null
+++ b/packages/ui/src/files/file-page.tsx
@@ -0,0 +1,174 @@
+"use client";
+
+import type { ReactNode } from "react";
+import { Flame, DoorOpen, Trash2 } from "lucide-react";
+import { Badge } from "../ui/badge";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";
+import { scoreBadgeClass } from "../health/tokens";
+import { fileEntityPath, symbolEntityPath } from "../shared/entity/routes";
+import { FileDocTab } from "./file-doc-tab";
+import { FileHealthTab, type FindingStatus } from "./file-health-tab";
+import { FileHistoryTab } from "./file-history-tab";
+import { FileCoverageTab } from "./file-coverage-tab";
+import { FileGraphTab } from "./file-graph-tab";
+import type { FileDetailResponse } from "@repowise-dev/types/files";
+import { FILE_PAGE_TABS, type FilePageTab } from "./file-page-tabs";
+
+export interface FilePageProps {
+ data: FileDetailResponse;
+ repoId: string;
+ linkPrefix?: string;
+ /** Server-rendered wiki content for the Doc tab. */
+ docSlot?: ReactNode;
+ /** Shiki HTML with per-line data-covered attributes (Coverage tab). */
+ coverageCodeHtml?: string;
+ /** Deep link into the docs reading surface. */
+ wikiHref?: string;
+ initialTab?: FilePageTab;
+ onTabChange?: (tab: FilePageTab) => void;
+ onFindingStatusChange?: (findingId: string, status: FindingStatus) => Promise<void> | void;
+}
+
+/**
+ * The canonical "everything about this file" page. Header (path, owner,
+ * health, signal chips, governing decisions) + Doc / Health / History /
+ * Coverage / Graph tabs. Purely presentational — data and callbacks come
+ * from the host; routing is plain hrefs built off `linkPrefix`.
+ */
+export function FilePage({
+ data,
+ repoId,
+ linkPrefix,
+ docSlot,
+ coverageCodeHtml,
+ wikiHref,
+ initialTab,
+ onTabChange,
+ onFindingStatusChange,
+}: FilePageProps) {
+ const prefix = linkPrefix ?? `/repos/${repoId}`;
+ const score = data.health.metric?.score;
+ const language = data.graph?.language;
+ const owner = data.git?.primary_owner ?? null;
+ const deadLines = data.dead_code.reduce((s, f) => s + f.lines, 0);
+ const fileHref = (p: string) => fileEntityPath(prefix, p);
+ const symbolHref = (s: string) => symbolEntityPath(prefix, s);
+
+ const defaultTab: FilePageTab =
+ initialTab && FILE_PAGE_TABS.includes(initialTab) ? initialTab : "doc";
+
+ return (
+ <div className="space-y-4">
+ {/* ── Header ── */}
+ <div className="space-y-2">
+ <h1
+ className="font-mono text-base sm:text-lg text-[var(--color-text-primary)] break-all"
+ title={data.file_path}
+ >
+ {data.file_path}
+ </h1>
+ <div className="flex flex-wrap items-center gap-2">
+ {score != null && (
+ <span
+ className={`inline-flex items-baseline rounded px-2 py-0.5 text-sm font-bold tabular-nums ${scoreBadgeClass(score)}`}
+ >
+ {score.toFixed(1)}
+ <span className="ml-0.5 text-[10px] font-normal opacity-70">/10</span>
+ </span>
+ )}
+ {language && (
+ <Badge variant="outline" className="text-[10px] h-5 capitalize">
+ {language}
+ </Badge>
+ )}
+ {data.graph?.is_entry_point && (
+ <Badge variant="outline" className="text-[10px] h-5 text-[var(--color-info)] border-[var(--color-info)]/30">
+ <DoorOpen className="h-2.5 w-2.5" /> entry point
+ </Badge>
+ )}
+ {data.git?.is_hotspot && (
+ <Badge variant="outline" className="text-[10px] h-5 text-[var(--color-error)] border-[var(--color-error)]/30">
+ <Flame className="h-2.5 w-2.5" /> hotspot
+ </Badge>
+ )}
+ {data.dead_code.length > 0 && (
+ <Badge variant="outline" className="text-[10px] h-5 text-[var(--color-warning)] border-[var(--color-warning)]/30">
+ <Trash2 className="h-2.5 w-2.5" /> {data.dead_code.length} dead ({deadLines} lines)
+ </Badge>
+ )}
+ {owner && (
+ <a
+ href={`${prefix}/owners/${encodeURIComponent(owner)}`}
+ className="text-[11px] text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:underline"
+ >
+ owned by <span className="font-medium">{owner}</span>
+ {data.git?.primary_owner_commit_pct != null &&
+ ` (${Math.round(data.git.primary_owner_commit_pct * 100)}%)`}
+ </a>
+ )}
+ </div>
+ {data.governing_decisions.length > 0 && (
+ <div className="flex flex-wrap items-center gap-1.5">
+ <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ Governed by
+ </span>
+ {data.governing_decisions.map((d) => (
+ <a
+ key={d.id}
+ href={`${prefix}/decisions/${d.id}`}
+ className="rounded border border-[var(--color-border-default)] px-1.5 py-0.5 text-[11px] text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:border-[var(--color-accent-primary)] transition-colors"
+ >
+ {d.title}
+ </a>
+ ))}
+ </div>
+ )}
+ </div>
+
+ {/* ── Tabs ── */}
+ <Tabs defaultValue={defaultTab} onValueChange={(v) => onTabChange?.(v as FilePageTab)}>
+ <TabsList className="flex-wrap">
+ <TabsTrigger value="doc">Doc</TabsTrigger>
+ <TabsTrigger value="health">
+ Health
+ {data.health.findings.length > 0 && (
+ <span className="ml-1 text-[10px] tabular-nums opacity-70">
+ {data.health.findings.length}
+ </span>
+ )}
+ </TabsTrigger>
+ <TabsTrigger value="history">History</TabsTrigger>
+ <TabsTrigger value="coverage">Coverage</TabsTrigger>
+ <TabsTrigger value="graph">Graph</TabsTrigger>
+ </TabsList>
+ <TabsContent value="doc" className="mt-4">
+ <FileDocTab wikiPage={data.wiki_page} docSlot={docSlot} wikiHref={wikiHref} />
+ </TabsContent>
+ <TabsContent value="health" className="mt-4">
+ <FileHealthTab
+ health={data.health}
+ functionBlame={data.function_blame}
+ onFindingStatusChange={onFindingStatusChange}
+ partnerHref={fileHref}
+ symbolHref={symbolHref}
+ />
+ </TabsContent>
+ <TabsContent value="history" className="mt-4">
+ <FileHistoryTab git={data.git} linkPrefix={prefix} partnerHref={fileHref} />
+ </TabsContent>
+ <TabsContent value="coverage" className="mt-4">
+ <FileCoverageTab coverage={data.coverage} coverageCodeHtml={coverageCodeHtml} />
+ </TabsContent>
+ <TabsContent value="graph" className="mt-4">
+ <FileGraphTab
+ graph={data.graph}
+ filePath={data.file_path}
+ linkPrefix={prefix}
+ fileHref={fileHref}
+ symbolHref={symbolHref}
+ />
+ </TabsContent>
+ </Tabs>
+ </div>
+ );
+}
diff --git a/packages/ui/src/files/index.ts b/packages/ui/src/files/index.ts
new file mode 100644
index 000000000..1cbb9aa57
--- /dev/null
+++ b/packages/ui/src/files/index.ts
@@ -0,0 +1,7 @@
+export * from "./file-page";
+export * from "./file-page-tabs";
+export * from "./file-doc-tab";
+export * from "./file-health-tab";
+export * from "./file-history-tab";
+export * from "./file-coverage-tab";
+export * from "./file-graph-tab";
diff --git a/packages/ui/src/git/hotspot-table.tsx b/packages/ui/src/git/hotspot-table.tsx
index 9673ff649..72779e33d 100644
--- a/packages/ui/src/git/hotspot-table.tsx
+++ b/packages/ui/src/git/hotspot-table.tsx
@@ -336,9 +336,9 @@ export function HotspotTable({
{prefix && (
<RowActions
actions={[
- { icon: GitBranch, label: "Graph", href: `${prefix}/graph?node=${encodeURIComponent(h.file_path)}` },
+ { icon: GitBranch, label: "Graph", href: `${prefix}/architecture?view=graph&node=${encodeURIComponent(h.file_path)}` },
{ icon: BookOpen, label: "Docs", href: `${prefix}/docs?file=${encodeURIComponent(h.file_path)}` },
- { icon: Radius, label: "Blast Radius", href: `${prefix}/blast-radius?file=${encodeURIComponent(h.file_path)}` },
+ { icon: Radius, label: "Blast Radius", href: `${prefix}/code-health?tab=impact&file=${encodeURIComponent(h.file_path)}` },
]}
/>
)}
diff --git a/packages/ui/src/git/ownership-table.tsx b/packages/ui/src/git/ownership-table.tsx
index 3fb7869bb..38ce9b5f7 100644
--- a/packages/ui/src/git/ownership-table.tsx
+++ b/packages/ui/src/git/ownership-table.tsx
@@ -6,6 +6,10 @@ import { Badge } from "../ui/badge";
import { Input } from "../ui/input";
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";
import { EmptyState } from "../shared/empty-state";
+import {
+ ResponsiveTable,
+ type ResponsiveColumn,
+} from "../shared/responsive-table";
import { RowActions } from "../shared/row-actions";
import { cn } from "../lib/cn";
import type { OwnershipEntry } from "@repowise-dev/types/git";
@@ -53,6 +57,91 @@ export function OwnershipTable({ entries, repoId, linkPrefix }: OwnershipTablePr
const siloCount = entries.filter((e) => e.is_silo).length;
+ const columns: ResponsiveColumn<OwnershipEntry>[] = [
+ {
+ key: "module_path",
+ header: "Module / File",
+ priority: 1,
+ cellClassName: "font-mono text-xs text-[var(--color-text-primary)] min-w-[160px] max-w-[480px]",
+ render: (entry) => (
+ <span className="block truncate" title={entry.module_path}>
+ {entry.module_path}
+ </span>
+ ),
+ },
+ {
+ key: "owner",
+ header: "Owner",
+ priority: 2,
+ cellClassName: "text-xs text-[var(--color-text-secondary)] max-w-[200px]",
+ render: (entry) => (
+ <span className="block truncate" title={entry.primary_owner ?? undefined}>
+ {entry.primary_owner ?? "—"}
+ </span>
+ ),
+ },
+ {
+ key: "ownership",
+ header: "Ownership",
+ priority: 2,
+ headerClassName: "w-36",
+ render: (entry) =>
+ entry.owner_pct !== null ? (
+ <div className="flex items-center gap-2 min-w-[100px]">
+ <div className="h-1.5 flex-1 rounded-full bg-[var(--color-bg-elevated)]">
+ <div
+ className="h-1.5 rounded-full bg-[var(--color-accent-primary)]"
+ style={{ width: `${Math.min(100, entry.owner_pct * 100)}%` }}
+ />
+ </div>
+ <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums w-8">
+ {Math.round(entry.owner_pct * 100)}%
+ </span>
+ </div>
+ ) : (
+ <span className="text-[var(--color-text-tertiary)]">—</span>
+ ),
+ mobileRender: (entry) =>
+ entry.owner_pct !== null ? `${Math.round(entry.owner_pct * 100)}%` : null,
+ },
+ {
+ key: "files",
+ header: "Files",
+ priority: 3,
+ cellClassName: "text-xs text-[var(--color-text-tertiary)] tabular-nums",
+ render: (entry) => entry.file_count,
+ },
+ {
+ key: "actions",
+ header: "",
+ priority: 1,
+ headerClassName: "w-20",
+ render: (entry) => (
+ <div className="flex items-center gap-1">
+ {entry.is_silo && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <Badge variant="stale">Silo</Badge>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>Bus factor risk</TooltipContent>
+ </Tooltip>
+ )}
+ {prefix && (
+ <RowActions
+ actions={[
+ { icon: GitBranch, label: "Graph", href: `${prefix}/architecture?view=graph&node=${encodeURIComponent(entry.module_path)}` },
+ { icon: Flame, label: "Hotspots", href: `${prefix}/code-health?tab=hotspots` },
+ ]}
+ />
+ )}
+ </div>
+ ),
+ mobileRender: (entry) => (entry.is_silo ? <Badge variant="stale">Silo</Badge> : null),
+ },
+ ];
+
return (
<div className="space-y-3">
<div className="flex flex-wrap items-center gap-2">
@@ -95,90 +184,12 @@ export function OwnershipTable({ entries, repoId, linkPrefix }: OwnershipTablePr
</span>
</div>
- {filtered.length === 0 ? (
- <EmptyState title="No matches" description="Try adjusting your search or filters." />
- ) : (
- <div className="rounded-lg border border-[var(--color-border-default)] overflow-x-auto">
- <table className="w-full text-sm">
- <thead className="sticky top-0 z-10 bg-[var(--color-bg-elevated)]">
- <tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">
- <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
- Module / File
- </th>
- <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
- Owner
- </th>
- <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-36">
- Ownership
- </th>
- <th className="px-4 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-16">
- Files
- </th>
- <th className="px-4 py-2.5 w-20" />
- </tr>
- </thead>
- <tbody>
- {filtered.map((entry) => (
- <tr
- key={entry.module_path}
- className="border-b border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)] transition-colors last:border-0"
- >
- <td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-primary)] min-w-[200px] max-w-[480px]">
- <span className="block truncate" title={entry.module_path}>{entry.module_path}</span>
- </td>
- <td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)] max-w-[200px]">
- <span className="block truncate" title={entry.primary_owner ?? undefined}>
- {entry.primary_owner ?? "—"}
- </span>
- </td>
- <td className="px-4 py-2.5">
- {entry.owner_pct !== null ? (
- <div className="flex items-center gap-2">
- <div className="h-1.5 flex-1 rounded-full bg-[var(--color-bg-elevated)]">
- <div
- className="h-1.5 rounded-full bg-[var(--color-accent-primary)]"
- style={{ width: `${Math.min(100, entry.owner_pct * 100)}%` }}
- />
- </div>
- <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums w-8">
- {Math.round(entry.owner_pct * 100)}%
- </span>
- </div>
- ) : (
- <span className="text-[var(--color-text-tertiary)]">—</span>
- )}
- </td>
- <td className="px-4 py-2.5 text-xs text-[var(--color-text-tertiary)] tabular-nums">
- {entry.file_count}
- </td>
- <td className="px-4 py-2.5">
- <div className="flex items-center gap-1">
- {entry.is_silo && (
- <Tooltip>
- <TooltipTrigger asChild>
- <span>
- <Badge variant="stale">Silo</Badge>
- </span>
- </TooltipTrigger>
- <TooltipContent>Bus factor risk</TooltipContent>
- </Tooltip>
- )}
- {prefix && (
- <RowActions
- actions={[
- { icon: GitBranch, label: "Graph", href: `${prefix}/graph?node=${encodeURIComponent(entry.module_path)}` },
- { icon: Flame, label: "Hotspots", href: `${prefix}/hotspots` },
- ]}
- />
- )}
- </div>
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- )}
+ <ResponsiveTable
+ columns={columns}
+ rows={filtered}
+ rowKey={(entry) => entry.module_path}
+ empty={<EmptyState title="No matches" description="Try adjusting your search or filters." />}
+ />
</div>
);
}
diff --git a/packages/ui/src/graph/graph-community-panel.tsx b/packages/ui/src/graph/graph-community-panel.tsx
index 0ab4d6a14..f57b6c3bb 100644
--- a/packages/ui/src/graph/graph-community-panel.tsx
+++ b/packages/ui/src/graph/graph-community-panel.tsx
@@ -19,6 +19,8 @@ export interface GraphCommunityPanelProps {
* "Expand on canvas" affordance is shown (the constellation single-click now
* opens this panel instead of expanding, so the panel offers the expand). */
onExpandOnCanvas?: (() => void) | undefined;
+ /** Build a member href (typically the canonical file page). */
+ memberHref?: ((path: string) => string) | undefined;
}
export function GraphCommunityPanel({
@@ -27,6 +29,7 @@ export function GraphCommunityPanel({
isLoading,
onClose,
onExpandOnCanvas,
+ memberHref,
}: GraphCommunityPanelProps) {
return (
<div className="absolute right-0 top-0 bottom-0 w-full sm:w-[360px] border-l border-[var(--color-border-default)] bg-[var(--color-bg-surface)] z-20 flex flex-col shadow-lg shadow-black/20">
@@ -90,9 +93,19 @@ export function GraphCommunityPanel({
className="flex items-center gap-2 py-1 px-1.5 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"
>
<div className="min-w-0 flex-1">
- <p className="text-[11px] font-mono text-[var(--color-text-primary)] truncate" title={m.path}>
- {truncatePath(m.path)}
- </p>
+ {memberHref ? (
+ <a
+ href={memberHref(m.path)}
+ className="block text-[11px] font-mono text-[var(--color-text-primary)] truncate hover:text-[var(--color-accent-primary)] hover:underline"
+ title={m.path}
+ >
+ {truncatePath(m.path)}
+ </a>
+ ) : (
+ <p className="text-[11px] font-mono text-[var(--color-text-primary)] truncate" title={m.path}>
+ {truncatePath(m.path)}
+ </p>
+ )}
</div>
{/* PageRank bar */}
<div className="w-16 h-1.5 rounded-full bg-[var(--color-bg-elevated)] overflow-hidden shrink-0">
diff --git a/packages/ui/src/graph/graph-ego-sidebar.tsx b/packages/ui/src/graph/graph-ego-sidebar.tsx
deleted file mode 100644
index 9d8a3ec4b..000000000
--- a/packages/ui/src/graph/graph-ego-sidebar.tsx
+++ /dev/null
@@ -1,128 +0,0 @@
-"use client";
-
-import { X, GitCommit, User, Clock, ArrowDownToLine, ArrowUpFromLine, FileText } from "lucide-react";
-import { Button } from "../ui/button";
-import { formatRelativeTime } from "../lib/format";
-import type { EgoGraph } from "@repowise-dev/types/graph";
-
-interface GraphEgoSidebarProps {
- graph: EgoGraph;
- onClose: () => void;
- onNavigateToNode?: (nodeId: string) => void;
-}
-
-export function GraphEgoSidebar({ graph, onClose, onNavigateToNode }: GraphEgoSidebarProps) {
- const meta = graph.center_git_meta;
- const centerNode = graph.nodes.find((n) => n.node_id === graph.center_node_id);
-
- return (
- <div className="absolute top-3 right-3 z-20 w-[min(18rem,calc(100vw-1.5rem))] rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)]/95 backdrop-blur-sm shadow-xl text-xs">
- <div className="flex items-start justify-between p-3 border-b border-[var(--color-border-default)]">
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-1.5 mb-0.5">
- <FileText className="h-3.5 w-3.5 text-[var(--color-text-tertiary)] shrink-0" />
- <p className="font-mono text-[var(--color-text-primary)] font-medium truncate">
- {graph.center_node_id.split("/").pop()}
- </p>
- </div>
- <p className="font-mono text-[var(--color-text-tertiary)] truncate pl-5">
- {graph.center_node_id}
- </p>
- </div>
- <Button size="sm" variant="ghost" onClick={onClose} className="h-6 w-6 p-0 shrink-0 ml-2">
- <X className="h-3.5 w-3.5" />
- </Button>
- </div>
-
- <div className="p-3 space-y-2">
- <div className="grid grid-cols-2 gap-2">
- <div className="rounded-md bg-[var(--color-bg-elevated)] p-2">
- <div className="flex items-center gap-1.5 text-[var(--color-text-tertiary)] mb-1">
- <ArrowDownToLine className="h-3 w-3" />
- <span>Inbound</span>
- </div>
- <p className="text-lg font-bold text-[var(--color-text-primary)] tabular-nums">
- {graph.inbound_count}
- </p>
- </div>
- <div className="rounded-md bg-[var(--color-bg-elevated)] p-2">
- <div className="flex items-center gap-1.5 text-[var(--color-text-tertiary)] mb-1">
- <ArrowUpFromLine className="h-3 w-3" />
- <span>Outbound</span>
- </div>
- <p className="text-lg font-bold text-[var(--color-text-primary)] tabular-nums">
- {graph.outbound_count}
- </p>
- </div>
- </div>
-
- {centerNode && (
- <div className="flex justify-between text-[var(--color-text-secondary)] pt-1">
- <span>Symbols</span>
- <span className="font-medium text-[var(--color-text-primary)] tabular-nums">
- {centerNode.symbol_count}
- </span>
- </div>
- )}
-
- {meta && (
- <div className="border-t border-[var(--color-border-default)] pt-2 space-y-1.5">
- {meta.primary_owner_name && (
- <div className="flex items-center justify-between text-[var(--color-text-secondary)]">
- <div className="flex items-center gap-1.5">
- <User className="h-3 w-3" />
- <span>Owner</span>
- </div>
- <span className="font-medium text-[var(--color-text-primary)] truncate max-w-[120px]">
- {meta.primary_owner_name}
- </span>
- </div>
- )}
- {meta.last_commit_at != null && (
- <div className="flex items-center justify-between text-[var(--color-text-secondary)]">
- <div className="flex items-center gap-1.5">
- <Clock className="h-3 w-3" />
- <span>Last commit</span>
- </div>
- <span className="font-medium text-[var(--color-text-primary)]">
- {formatRelativeTime(meta.last_commit_at)}
- </span>
- </div>
- )}
- <div className="flex items-center justify-between text-[var(--color-text-secondary)]">
- <div className="flex items-center gap-1.5">
- <GitCommit className="h-3 w-3" />
- <span>Commits (30d)</span>
- </div>
- <span className="font-medium text-[var(--color-text-primary)] tabular-nums">
- {meta.commit_count_30d}
- </span>
- </div>
- </div>
- )}
-
- {graph.nodes.length > 1 && (
- <div className="border-t border-[var(--color-border-default)] pt-2">
- <p className="text-[var(--color-text-tertiary)] mb-1.5">
- {graph.nodes.length - 1} neighbors in {graph.links.length} edges
- </p>
- <div className="space-y-0.5 max-h-32 overflow-y-auto">
- {graph.nodes
- .filter((n) => n.node_id !== graph.center_node_id)
- .slice(0, 8)
- .map((n) => (
- <button
- key={n.node_id}
- onClick={() => onNavigateToNode?.(n.node_id)}
- className="w-full text-left px-1.5 py-1 rounded hover:bg-[var(--color-bg-elevated)] font-mono text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] truncate transition-colors"
- >
- {n.node_id}
- </button>
- ))}
- </div>
- </div>
- )}
- </div>
- </div>
- );
-}
diff --git a/packages/ui/src/graph/graph-flow.tsx b/packages/ui/src/graph/graph-flow.tsx
index 24df8243e..0edf8a873 100644
--- a/packages/ui/src/graph/graph-flow.tsx
+++ b/packages/ui/src/graph/graph-flow.tsx
@@ -23,6 +23,16 @@ const HUB_FOCUS_RATIO = 0.45;
// Below this node count file graphs build synchronously; at or above it we
// build in chunks off the critical path (see sigmaGraph below).
const ASYNC_BUILD_THRESHOLD = 1000;
+
+/** Deterministic 0–1 value from a string (FNV-1a) — stable layout jitter. */
+function hashUnit(s: string): number {
+ let h = 0x811c9dc5;
+ for (let i = 0; i < s.length; i++) {
+ h ^= s.charCodeAt(i);
+ h = Math.imul(h, 0x01000193);
+ }
+ return (h >>> 0) / 0xffffffff;
+}
import { useExpandedModules } from "./use-expanded-modules";
import { useExpandedHubs } from "./use-expanded-hubs";
import { traceToEdgeKeys } from "./graph-flow-helpers";
@@ -34,6 +44,7 @@ import { GraphToolbar, type ColorMode, type ViewMode, type LayoutMode, type Grap
import { GraphLegend } from "./graph-legend";
import { GraphContextMenu } from "./graph-context-menu";
import { GraphInspectionPanel } from "./graph-inspection-panel";
+import { GraphShortcutHelp } from "./graph-shortcut-help";
import type {
GraphExport,
ModuleGraph,
@@ -91,12 +102,24 @@ export interface GraphFlowProps {
communities?: CommunitySummaryItem[];
executionFlows?: ExecutionFlows;
initialViewMode?: ViewMode;
+ /** Initial node color mode. Hosts derive this from their URL state instead
+ * of the component reading window.location. */
+ initialColorMode?: ColorMode;
initialSelectedNode?: string | null;
onViewModeChange?: (mode: ViewMode) => void;
+ /** Fired when the node color mode changes (toolbar or 1/2/3 shortcut) so
+ * hosts can sync it to the URL. */
+ onColorModeChange?: (mode: ColorMode) => void;
onModulePathChange?: (path: string[]) => void;
onExpandedModulesChange?: (expanded: Set<string>) => void;
onNodeClick?: (nodeId: string, nodeType: string) => void | Promise<void>;
onNodeViewDocs?: (nodeId: string) => void;
+ /** "Symbols" action in the inspection panel — jump to the symbols view
+ * filtered to the selected file. */
+ onNodeViewSymbols?: (nodeId: string) => void;
+ /** Canonical file-page href for a file node — renders an "Open file page"
+ * action in the inspection panel. */
+ fileHrefFor?: (nodeId: string) => string;
renderPathFinder?: (props: {
initialFrom: string;
initialTo: string;
@@ -134,12 +157,16 @@ export function GraphFlow(props: GraphFlowProps) {
communities,
executionFlows,
initialViewMode,
+ initialColorMode,
initialSelectedNode,
onViewModeChange,
+ onColorModeChange,
onModulePathChange,
onExpandedModulesChange,
onNodeClick,
onNodeViewDocs,
+ onNodeViewSymbols,
+ fileHrefFor,
renderPathFinder,
renderCommunityPanel,
onCommunityPanelOpen,
@@ -151,17 +178,11 @@ export function GraphFlow(props: GraphFlowProps) {
// ---- Core state ----
// Default scope is the constellation (radial Knowledge Graph).
const [viewMode, setViewMode] = useState<ViewMode>(initialViewMode ?? "architecture");
- const [colorMode, setColorMode] = useState<ColorMode>(() => {
- if (typeof window !== "undefined") {
- const params = new URLSearchParams(window.location.search);
- const cm = params.get("colorMode");
- if (cm === "community" || cm === "language" || cm === "risk") return cm;
- }
- return "community";
- });
+ const [colorMode, setColorMode] = useState<ColorMode>(initialColorMode ?? "community");
const [highlightedPath, setHighlightedPath] = useState<Set<string>>(new Set());
const [highlightedEdges, setHighlightedEdges] = useState<Set<string>>(new Set());
const [showPathFinder, setShowPathFinder] = useState(false);
+ const [showShortcutHelp, setShowShortcutHelp] = useState(false);
// Constellation is the default scope → its fixed radial layout.
const [layoutMode, setLayoutMode] = useState<LayoutMode>(
(initialViewMode ?? "architecture") === "architecture" ? "radial" : "force",
@@ -179,15 +200,12 @@ export function GraphFlow(props: GraphFlowProps) {
() => new Set(["import", "crossCommunity"]),
);
- // Signal overlays (replaces separate view modes for dead/hot/arch)
+ // Signal overlays (replaces separate view modes for dead/hot/arch).
+ // Derived from the host-provided initial view mode — no URL reads here.
const [activeSignals, setActiveSignals] = useState<Set<Signal>>(() => {
- if (typeof window !== "undefined") {
- const params = new URLSearchParams(window.location.search);
- const vm = params.get("viewMode");
- if (vm === "dead") return new Set<Signal>(["dead"]);
- if (vm === "hotfiles") return new Set<Signal>(["hot"]);
- if (vm === "unified") return new Set<Signal>(["dead", "hot"]);
- }
+ if (initialViewMode === "dead") return new Set<Signal>(["dead"]);
+ if (initialViewMode === "hotfiles") return new Set<Signal>(["hot"]);
+ if (initialViewMode === "unified") return new Set<Signal>(["dead", "hot"]);
return new Set<Signal>();
});
const hideTests = activeSignals.has("hideTests");
@@ -467,8 +485,10 @@ export function GraphFlow(props: GraphFlowProps) {
const color = sigmaLanguageColor(node.language);
graph.addNode(node.node_id, {
- x: modX + (Math.random() - 0.5) * jitter,
- y: modY + (Math.random() - 0.5) * jitter,
+ // Deterministic per-node jitter (id hash) so expanding a module
+ // always blossoms its files into the same positions.
+ x: modX + (hashUnit(node.node_id) - 0.5) * jitter,
+ y: modY + (hashUnit(node.node_id + "y") - 0.5) * jitter,
size,
color,
label: node.node_id.split("/").pop() ?? node.node_id,
@@ -802,6 +822,10 @@ export function GraphFlow(props: GraphFlowProps) {
// 2. else any hub expanded → collapse the most recent
// 3. else → fall through to the default clear (search, ctx menu, …)
const handleEscapeCollapse = useCallback((): boolean => {
+ if (showShortcutHelp) {
+ setShowShortcutHelp(false);
+ return true;
+ }
if (selectedNodeId !== null || communityPanelId !== null) {
setSelectedNodeId(null);
setCommunityPanelId(null);
@@ -813,9 +837,13 @@ export function GraphFlow(props: GraphFlowProps) {
return true;
}
return false;
- }, [selectedNodeId, communityPanelId, isConstellation, expandedHubs.length, collapseLast]);
+ }, [showShortcutHelp, selectedNodeId, communityPanelId, isConstellation, expandedHubs.length, collapseLast]);
+
+ const handleToggleShortcutHelp = useCallback(() => {
+ setShowShortcutHelp((s) => !s);
+ }, []);
- // Global keyboard shortcuts (f/Escape/1-3//, cmd+k)
+ // Global keyboard shortcuts (f/Escape/1-3//, cmd+k, ?)
useGraphKeyboardShortcuts({
sigmaRef,
setSelectedNodeId,
@@ -825,8 +853,21 @@ export function GraphFlow(props: GraphFlowProps) {
setCommunityPanelId,
setColorMode,
onEscape: handleEscapeCollapse,
+ onToggleHelp: handleToggleShortcutHelp,
});
+ // Surface color-mode changes (toolbar or 1/2/3 shortcut) to the host so it
+ // can sync the URL. Skip the mount-time report — only real changes count.
+ const colorModeReported = useRef(false);
+ useEffect(() => {
+ if (!colorModeReported.current) {
+ colorModeReported.current = true;
+ return;
+ }
+ onColorModeChange?.(colorMode);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [colorMode]);
+
const handlePathFound = useCallback(
(pathNodes: string[]) => {
setHighlightedPath(new Set(pathNodes));
@@ -916,6 +957,8 @@ export function GraphFlow(props: GraphFlowProps) {
if (selectedNodeId) {
setPathFrom(selectedNodeId);
setShowPathFinder(true);
+ setShowFlows(false);
+ setActiveFlowIdx(null);
}
}, [selectedNodeId]);
@@ -952,12 +995,22 @@ export function GraphFlow(props: GraphFlowProps) {
}, [ctxMenu, isModuleView, onNodeClick, setCtxMenu]);
const handleCtxPathFrom = useCallback(() => {
- if (ctxMenu) { setPathFrom(ctxMenu.nodeId); setShowPathFinder(true); }
+ if (ctxMenu) {
+ setPathFrom(ctxMenu.nodeId);
+ setShowPathFinder(true);
+ setShowFlows(false);
+ setActiveFlowIdx(null);
+ }
setCtxMenu(null);
}, [ctxMenu, setCtxMenu]);
const handleCtxPathTo = useCallback(() => {
- if (ctxMenu) { setPathTo(ctxMenu.nodeId); setShowPathFinder(true); }
+ if (ctxMenu) {
+ setPathTo(ctxMenu.nodeId);
+ setShowPathFinder(true);
+ setShowFlows(false);
+ setActiveFlowIdx(null);
+ }
setCtxMenu(null);
}, [ctxMenu, setCtxMenu]);
@@ -1072,9 +1125,19 @@ export function GraphFlow(props: GraphFlowProps) {
}}
onFitView={handleFitView}
showPathFinder={showPathFinder}
- onTogglePathFinder={() => setShowPathFinder((s) => !s)}
+ onTogglePathFinder={() => {
+ // Path finder and flows share the same overlay slot — opening
+ // one always closes the other.
+ setShowPathFinder((s) => !s);
+ setShowFlows(false);
+ setActiveFlowIdx(null);
+ }}
showFlows={showFlows}
- onToggleFlows={() => { setShowFlows((s) => !s); setActiveFlowIdx(null); }}
+ onToggleFlows={() => {
+ setShowFlows((s) => !s);
+ setActiveFlowIdx(null);
+ setShowPathFinder(false);
+ }}
searchQuery={searchQuery}
onSearchChange={setSearchQuery}
searchMatchCount={searchResults.length}
@@ -1084,6 +1147,7 @@ export function GraphFlow(props: GraphFlowProps) {
onLayoutModeChange={handleLayoutModeChange}
graphTheme={graphTheme}
onGraphThemeChange={handleGraphThemeChange}
+ onToggleHelp={handleToggleShortcutHelp}
/>
</div>
@@ -1158,6 +1222,11 @@ export function GraphFlow(props: GraphFlowProps) {
/>
</div>
+ {/* Keyboard shortcut help (toggled with ?) */}
+ {showShortcutHelp && (
+ <GraphShortcutHelp onClose={() => setShowShortcutHelp(false)} />
+ )}
+
{/* Context menu */}
{ctxMenu && (
<GraphContextMenu
@@ -1196,6 +1265,12 @@ export function GraphFlow(props: GraphFlowProps) {
onClose={() => { setSelectedNodeId(null); }}
onNavigateToNode={handleInspectNavigate}
onViewDocs={() => { onNodeViewDocs?.(selectedNodeId); }}
+ onViewSymbols={
+ fileNd && onNodeViewSymbols
+ ? () => { onNodeViewSymbols(selectedNodeId); }
+ : undefined
+ }
+ filePageHref={fileNd ? fileHrefFor?.(selectedNodeId) : undefined}
onFindPath={handleInspectFindPath}
onExpandModule={modNd ? handleInspectExpandModule : undefined}
egoDepth={egoDepth}
diff --git a/packages/ui/src/graph/graph-inspection-panel.tsx b/packages/ui/src/graph/graph-inspection-panel.tsx
index f5a5698ea..6f6de463a 100644
--- a/packages/ui/src/graph/graph-inspection-panel.tsx
+++ b/packages/ui/src/graph/graph-inspection-panel.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useMemo, memo } from "react";
+import { useMemo, useRef, memo } from "react";
import {
X,
FileText,
@@ -38,7 +38,9 @@ export interface GraphInspectionPanelProps {
onClose: () => void;
onNavigateToNode: (nodeId: string) => void;
onViewDocs?: () => void;
- onViewSymbols?: () => void;
+ onViewSymbols?: (() => void) | undefined;
+ /** Canonical file-page href — renders the primary "Open file page" action. */
+ filePageHref?: string | undefined;
onFindPath?: (() => void) | undefined;
onShowEgoGraph?: (() => void) | undefined;
onExpandModule?: (() => void) | undefined;
@@ -71,6 +73,7 @@ export const GraphInspectionPanel = memo(function GraphInspectionPanel({
onNavigateToNode,
onViewDocs,
onViewSymbols,
+ filePageHref,
onFindPath,
onShowEgoGraph,
onExpandModule,
@@ -79,6 +82,7 @@ export const GraphInspectionPanel = memo(function GraphInspectionPanel({
egoVisibleCount,
}: GraphInspectionPanelProps) {
const communityFamily = useCommunityFamilies();
+ const touchStartY = useRef<number | null>(null);
const neighbors = useMemo(() => {
if (!graph || !graph.hasNode(nodeId)) return [];
const result: NeighborInfo[] = [];
@@ -132,8 +136,23 @@ export const GraphInspectionPanel = memo(function GraphInspectionPanel({
return (
<div
- className="absolute right-0 top-0 bottom-0 w-full sm:w-[300px] border-l border-[var(--color-border-default)] bg-[var(--color-bg-surface)] z-20 flex flex-col shadow-xl shadow-black/20 animate-in slide-in-from-right duration-200"
+ // Right panel on sm+; bottom sheet (drag handle + swipe-dismiss) below.
+ className="absolute inset-x-0 bottom-0 top-auto max-h-[70%] rounded-t-xl border-t border-[var(--color-border-default)] bg-[var(--color-bg-surface)] z-20 flex flex-col shadow-xl shadow-black/20 animate-in slide-in-from-bottom sm:slide-in-from-bottom-0 sm:slide-in-from-right duration-200 sm:inset-x-auto sm:right-0 sm:top-0 sm:bottom-0 sm:left-auto sm:w-[300px] sm:max-h-none sm:rounded-none sm:border-t-0 sm:border-l"
+ onTouchStart={(e) => {
+ touchStartY.current = e.touches[0]?.clientY ?? null;
+ }}
+ onTouchEnd={(e) => {
+ const start = touchStartY.current;
+ touchStartY.current = null;
+ if (start == null || window.innerWidth >= 640) return;
+ const end = e.changedTouches[0]?.clientY ?? start;
+ if (end - start > 80) onClose();
+ }}
>
+ {/* Drag handle (mobile sheet only) */}
+ <div className="flex justify-center py-1.5 sm:hidden" aria-hidden>
+ <span className="h-1 w-9 rounded-full bg-[var(--color-border-default)]" />
+ </div>
{/* Header */}
<div className="flex items-start gap-2 px-4 py-3 border-b border-[var(--color-border-default)]">
{headerIcon}
@@ -239,6 +258,14 @@ export const GraphInspectionPanel = memo(function GraphInspectionPanel({
{/* Actions */}
<div className="border-t border-[var(--color-border-default)] p-3 grid grid-cols-2 gap-2">
+ {!isMod && filePageHref && (
+ <a
+ href={filePageHref}
+ className="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 py-1.5 text-[10px] font-medium text-[var(--color-accent-graph)] transition-colors col-span-2"
+ >
+ <FileText className="w-3 h-3" /> Open file page
+ </a>
+ )}
{isMod && onExpandModule && (
<button
onClick={onExpandModule}
diff --git a/packages/ui/src/graph/graph-legend.tsx b/packages/ui/src/graph/graph-legend.tsx
index 12c69181c..d24e30824 100644
--- a/packages/ui/src/graph/graph-legend.tsx
+++ b/packages/ui/src/graph/graph-legend.tsx
@@ -61,7 +61,9 @@ export const GraphLegend = memo(function GraphLegend({
// Constellation legend: families + member counts, click focuses the hub.
if (isConstellation) {
- const entries = (constellationEntries ?? []).slice(0, 12);
+ const allEntries = constellationEntries ?? [];
+ const entries = allEntries.slice(0, 12);
+ const overflow = allEntries.length - entries.length;
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-[160px] max-w-[220px]">
<button
@@ -69,7 +71,7 @@ export const GraphLegend = memo(function GraphLegend({
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">
- {entries.length} communit{entries.length === 1 ? "y" : "ies"}
+ {allEntries.length} communit{allEntries.length === 1 ? "y" : "ies"}
</span>
{expanded ? (
<ChevronDown className="w-3 h-3 shrink-0 ml-1.5" />
@@ -104,6 +106,12 @@ export const GraphLegend = memo(function GraphLegend({
</button>
);
})}
+ {overflow > 0 && (
+ <p className="text-[10px] text-[var(--color-text-tertiary)]">
+ +{overflow} smaller communit{overflow === 1 ? "y" : "ies"} not
+ listed
+ </p>
+ )}
<p className="text-[9px] text-[var(--color-text-tertiary)] pt-1.5 border-t border-[var(--color-border-default)]">
Inner ring = entry surface
</p>
diff --git a/packages/ui/src/graph/graph-shortcut-help.tsx b/packages/ui/src/graph/graph-shortcut-help.tsx
new file mode 100644
index 000000000..c8cf66f91
--- /dev/null
+++ b/packages/ui/src/graph/graph-shortcut-help.tsx
@@ -0,0 +1,75 @@
+"use client";
+
+import { X } from "lucide-react";
+
+const SHORTCUTS: { keys: string[]; action: string }[] = [
+ { keys: ["f"], action: "Fit graph to view" },
+ { keys: ["/"], action: "Focus search" },
+ { keys: ["⌘K"], action: "Focus search" },
+ { keys: ["1"], action: "Color by language" },
+ { keys: ["2"], action: "Color by community" },
+ { keys: ["3"], action: "Color by risk" },
+ { keys: ["Esc"], action: "Dismiss top layer (panel, selection, blossom…)" },
+ { keys: ["?"], action: "Toggle this help" },
+];
+
+const GESTURES: { gesture: string; action: string }[] = [
+ { gesture: "Click", action: "Select + inspect a node" },
+ { gesture: "Double-click", action: "Drill deeper (expand module / blossom hub / open doc)" },
+ { gesture: "Right-click", action: "Context menu (docs, explore, path from/to)" },
+];
+
+/** Keyboard + gesture cheatsheet, toggled with `?`. */
+export function GraphShortcutHelp({ onClose }: { onClose: () => void }) {
+ return (
+ <div className="absolute inset-0 z-20 flex items-center justify-center bg-black/40 p-4" onClick={onClose}>
+ <div
+ className="w-full max-w-sm rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 shadow-xl shadow-black/30"
+ onClick={(e) => e.stopPropagation()}
+ role="dialog"
+ aria-label="Graph keyboard shortcuts"
+ >
+ <div className="mb-3 flex items-center justify-between">
+ <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">
+ Keyboard shortcuts
+ </h3>
+ <button
+ onClick={onClose}
+ aria-label="Close shortcut help"
+ className="text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-text-primary)]"
+ >
+ <X className="h-4 w-4" />
+ </button>
+ </div>
+ <div className="space-y-1.5">
+ {SHORTCUTS.map((s) => (
+ <div key={s.keys.join("+") + s.action} className="flex items-center justify-between gap-3 text-xs">
+ <span className="text-[var(--color-text-secondary)]">{s.action}</span>
+ <span className="flex shrink-0 gap-1">
+ {s.keys.map((k) => (
+ <kbd
+ key={k}
+ className="rounded border border-[var(--color-border-default)] bg-[var(--color-bg-inset)] px-1.5 py-0.5 font-mono text-[10px] text-[var(--color-text-primary)]"
+ >
+ {k}
+ </kbd>
+ ))}
+ </span>
+ </div>
+ ))}
+ </div>
+ <p className="mb-1.5 mt-3 text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ Mouse
+ </p>
+ <div className="space-y-1.5">
+ {GESTURES.map((g) => (
+ <div key={g.gesture} className="flex items-start justify-between gap-3 text-xs">
+ <span className="shrink-0 text-[var(--color-text-primary)]">{g.gesture}</span>
+ <span className="text-right text-[var(--color-text-secondary)]">{g.action}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/graph/graph-toolbar.tsx b/packages/ui/src/graph/graph-toolbar.tsx
index ce05afcaf..d208d4551 100644
--- a/packages/ui/src/graph/graph-toolbar.tsx
+++ b/packages/ui/src/graph/graph-toolbar.tsx
@@ -19,8 +19,10 @@ import {
Waypoints,
Sun,
Moon,
+ SlidersHorizontal,
+ HelpCircle,
} from "lucide-react";
-import { memo } from "react";
+import { memo, useState } from "react";
import { Button } from "../ui/button";
export type ColorMode = "language" | "community" | "risk";
@@ -89,6 +91,8 @@ interface GraphToolbarProps {
onLayoutModeChange: (mode: LayoutMode) => void;
graphTheme: GraphTheme;
onGraphThemeChange: (theme: GraphTheme) => void;
+ /** Opens the keyboard-shortcut help overlay (also bound to `?`). */
+ onToggleHelp?: () => void;
}
// Scope = which subset of nodes are drawn. Mutually exclusive.
@@ -144,7 +148,12 @@ export const GraphToolbar = memo(function GraphToolbar({
onLayoutModeChange,
graphTheme,
onGraphThemeChange,
+ onToggleHelp,
}: GraphToolbarProps) {
+ // Below sm the full control cluster is too much chrome over the canvas —
+ // collapse it behind a single toggle, keeping search always reachable.
+ const [mobileOpen, setMobileOpen] = useState(false);
+ const clusterVisibility = mobileOpen ? "flex" : "hidden sm:flex";
// Derive scope + overlays from the legacy ViewMode so this component remains
// the single source of truth — callers can continue to round-trip the
// wire-format ``viewMode`` value through query params without translation.
@@ -168,8 +177,23 @@ export const GraphToolbar = memo(function GraphToolbar({
return (
<div className="flex flex-col gap-1.5 items-end">
+ {/* Mobile: single toggle for the control cluster */}
+ <button
+ onClick={() => setMobileOpen((s) => !s)}
+ className={`flex items-center gap-1.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm px-2 py-1.5 text-[10px] font-medium shadow-lg shadow-black/20 sm:hidden ${
+ mobileOpen
+ ? "text-[var(--color-accent-primary)]"
+ : "text-[var(--color-text-secondary)]"
+ }`}
+ aria-expanded={mobileOpen}
+ aria-label="Graph controls"
+ >
+ <SlidersHorizontal className="w-3 h-3" />
+ Controls
+ </button>
+
{/* Scope (mutually exclusive) */}
- <div className="flex gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-lg shadow-black/20">
+ <div className={`${clusterVisibility} gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-lg shadow-black/20`}>
{SCOPES.map((m) => {
const Icon = m.icon;
const isActive = activeScope === m.id;
@@ -195,7 +219,7 @@ export const GraphToolbar = memo(function GraphToolbar({
{/* Overlays (additive signal chips) — not applicable in the constellation */}
{!isConstellation && (
- <div className="flex gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-lg shadow-black/20">
+ <div className={`${clusterVisibility} gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-lg shadow-black/20`}>
{OVERLAYS.map((o) => {
const Icon = o.icon;
const isActive = activeOverlays.has(o.id);
@@ -220,7 +244,7 @@ export const GraphToolbar = memo(function GraphToolbar({
</div>
)}
- <div className="flex gap-1.5 items-center">
+ <div className={`${clusterVisibility} gap-1.5 items-center`}>
<div className="flex gap-0.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/90 backdrop-blur-sm p-1 shadow-lg shadow-black/20">
{isConstellation ? (
// Constellation is locked to the radial layout; show a single
@@ -345,6 +369,18 @@ export const GraphToolbar = memo(function GraphToolbar({
>
<Maximize className="w-3.5 h-3.5" />
</Button>
+ {onToggleHelp && (
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={onToggleHelp}
+ className="h-7 w-7 p-0 text-[var(--color-text-tertiary)]"
+ title="Keyboard shortcuts (?)"
+ aria-label="Keyboard shortcuts"
+ >
+ <HelpCircle className="w-3.5 h-3.5" />
+ </Button>
+ )}
</div>
</div>
diff --git a/packages/ui/src/graph/index.ts b/packages/ui/src/graph/index.ts
index 991455243..ef7c24717 100644
--- a/packages/ui/src/graph/index.ts
+++ b/packages/ui/src/graph/index.ts
@@ -1,5 +1,4 @@
export * from "./graph-context-menu";
-export * from "./graph-ego-sidebar";
export * from "./graph-legend";
export * from "./graph-toolbar";
export * from "./graph-doc-panel";
diff --git a/packages/ui/src/graph/use-graph-keyboard-shortcuts.ts b/packages/ui/src/graph/use-graph-keyboard-shortcuts.ts
index 019d62757..445d99bb1 100644
--- a/packages/ui/src/graph/use-graph-keyboard-shortcuts.ts
+++ b/packages/ui/src/graph/use-graph-keyboard-shortcuts.ts
@@ -15,6 +15,8 @@ interface GraphKeyboardShortcutOptions {
* the default clear. Used to dismiss the top UI layer first: clear an open
* selection/panel, else collapse the most recent constellation hub. */
onEscape?: (() => boolean) | undefined;
+ /** `?` toggles the shortcut help overlay. */
+ onToggleHelp?: (() => void) | undefined;
}
/**
@@ -32,6 +34,7 @@ export function useGraphKeyboardShortcuts(opts: GraphKeyboardShortcutOptions): v
setCommunityPanelId,
setColorMode,
onEscape,
+ onToggleHelp,
} = opts;
useEffect(() => {
@@ -73,6 +76,10 @@ export function useGraphKeyboardShortcuts(opts: GraphKeyboardShortcutOptions): v
.querySelector<HTMLInputElement>('[aria-label="Search graph nodes"]')
?.focus();
break;
+ case "?":
+ e.preventDefault();
+ onToggleHelp?.();
+ break;
}
if ((e.metaKey || e.ctrlKey) && e.key === "k") {
@@ -95,5 +102,6 @@ export function useGraphKeyboardShortcuts(opts: GraphKeyboardShortcutOptions): v
setCommunityPanelId,
setColorMode,
onEscape,
+ onToggleHelp,
]);
}
diff --git a/packages/ui/src/health/ai-prompt-modal.tsx b/packages/ui/src/health/ai-prompt-modal.tsx
index 69dd55e67..19527c0a6 100644
--- a/packages/ui/src/health/ai-prompt-modal.tsx
+++ b/packages/ui/src/health/ai-prompt-modal.tsx
@@ -42,6 +42,21 @@ const FLAVORS: {
{ value: "cursor", label: "Cursor", Icon: Code2, hint: "Uses @file context, Cursor editing conventions." },
];
+const FLAVOR_STORAGE_KEY = "repowise:ai-prompt-flavor";
+
+function loadStoredFlavor(): AiPromptFlavor {
+ if (typeof window === "undefined") return "generic";
+ try {
+ const stored = window.localStorage.getItem(FLAVOR_STORAGE_KEY);
+ if (stored && FLAVORS.some((f) => f.value === stored)) {
+ return stored as AiPromptFlavor;
+ }
+ } catch {
+ /* storage blocked */
+ }
+ return "generic";
+}
+
export function AiPromptModal({
open,
onOpenChange,
@@ -50,19 +65,25 @@ export function AiPromptModal({
title = "AI fix prompt",
description = "A ready-to-paste prompt that gives your AI coding agent every detail needed to make this change in one focused pass.",
}: AiPromptModalProps) {
- const [flavor, setFlavor] = useState<AiPromptFlavor>("generic");
+ const [flavor, setFlavorState] = useState<AiPromptFlavor>(loadStoredFlavor);
const [copied, setCopied] = useState(false);
+ const setFlavor = (next: AiPromptFlavor) => {
+ setFlavorState(next);
+ try {
+ window.localStorage.setItem(FLAVOR_STORAGE_KEY, next);
+ } catch {
+ /* storage blocked */
+ }
+ };
+
const prompt = useMemo(
() => (getPrompt ? getPrompt(flavor) : ""),
[getPrompt, flavor],
);
useEffect(() => {
- if (!open) {
- setCopied(false);
- setFlavor("generic");
- }
+ if (!open) setCopied(false);
}, [open]);
const handleCopy = async () => {
@@ -80,7 +101,7 @@ export function AiPromptModal({
<DialogContent className="max-w-3xl">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
- <Sparkles className="h-4 w-4 text-emerald-500" />
+ <Sparkles className="h-4 w-4 text-[var(--color-accent-primary)]" />
{title}
{filePath ? (
<span className="ml-2 text-xs font-mono font-normal text-[var(--color-text-tertiary)] truncate max-w-[260px]">
@@ -107,13 +128,13 @@ export function AiPromptModal({
className={
"rounded-md border px-3 py-2 text-left transition-colors " +
(active
- ? "border-emerald-500 bg-emerald-500/10"
+ ? "border-[var(--color-accent-primary)] bg-[var(--color-accent-muted)]"
: "border-[var(--color-border-default)] hover:border-[var(--color-border-strong)] hover:bg-[var(--color-bg-elevated)]")
}
title={f.hint}
>
<div className="flex items-center gap-1.5">
- <f.Icon className={`h-3.5 w-3.5 ${active ? "text-emerald-500" : "text-[var(--color-text-tertiary)]"}`} />
+ <f.Icon className={`h-3.5 w-3.5 ${active ? "text-[var(--color-accent-primary)]" : "text-[var(--color-text-tertiary)]"}`} />
<span className="text-xs font-semibold text-[var(--color-text-primary)]">
{f.label}
</span>
@@ -145,7 +166,7 @@ export function AiPromptModal({
className={
"inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-semibold transition-colors " +
(copied
- ? "bg-emerald-500 text-white"
+ ? "bg-[var(--color-success)] text-[var(--color-text-inverse)]"
: "bg-[var(--color-accent-primary)] text-[var(--color-bg-surface)] hover:opacity-90")
}
>
diff --git a/packages/ui/src/health/biomarker-details.tsx b/packages/ui/src/health/biomarker-details.tsx
index f5e831390..91ad76b2e 100644
--- a/packages/ui/src/health/biomarker-details.tsx
+++ b/packages/ui/src/health/biomarker-details.tsx
@@ -23,6 +23,87 @@ function str(v: unknown): string | null {
return typeof v === "string" && v.length > 0 ? v : null;
}
+function pct(v: number | null, digits = 0): string | null {
+ return v == null ? null : `${(v * 100).toFixed(digits)}%`;
+}
+
+/** Compose " · "-joined stat fragments, dropping empties. */
+function joinStats(...parts: Array<string | null | undefined>): string | null {
+ const kept = parts.filter((p): p is string => Boolean(p));
+ return kept.length ? kept.join(" · ") : null;
+}
+
+function StatLine({ children }: { children: React.ReactNode }) {
+ return (
+ <div className="text-[11px] text-[var(--color-text-tertiary)] tabular-nums">
+ {children}
+ </div>
+ );
+}
+
+function PartnerLink({
+ path,
+ onPartnerSelect,
+ onPartnerHref,
+}: {
+ path: string;
+ onPartnerSelect?: ((path: string) => void) | undefined;
+ onPartnerHref?: ((path: string) => string) | undefined;
+}) {
+ const href = onPartnerHref ? onPartnerHref(path) : undefined;
+ const inner = (
+ <span className="inline-flex items-center gap-1 font-mono truncate">
+ <ArrowLeftRight className="h-3 w-3 shrink-0" aria-hidden="true" />
+ <span className="truncate">{path}</span>
+ </span>
+ );
+ if (href) {
+ return (
+ <a
+ href={href}
+ onClick={(e) => {
+ if (onPartnerSelect) {
+ e.preventDefault();
+ onPartnerSelect(path);
+ }
+ }}
+ className="text-[var(--color-accent-primary)] hover:underline"
+ >
+ {inner}
+ </a>
+ );
+ }
+ if (onPartnerSelect) {
+ return (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ onPartnerSelect(path);
+ }}
+ className="text-[var(--color-accent-primary)] hover:underline text-left"
+ >
+ {inner}
+ </button>
+ );
+ }
+ return inner;
+}
+
+const ERROR_HANDLING_KIND_LABEL: Record<string, string> = {
+ swallowed_exception: "swallowed exception",
+ bare_except: "bare except",
+ unsafe_unwrap: "unsafe unwrap",
+ discarded_error: "discarded error return",
+ empty_catch: "empty catch block",
+};
+
+/**
+ * Per-type rendering of a finding's ``details_json``. Every biomarker the
+ * scorer can emit gets a compact stat line; partner-bearing types
+ * (hidden_coupling, dry_violation, duplicated_assertion_block) additionally
+ * render the partner file as a link.
+ */
export function BiomarkerDetails({
biomarkerType,
details,
@@ -33,47 +114,16 @@ export function BiomarkerDetails({
if (biomarkerType === "hidden_coupling") {
const partner = str(details.partner);
- const correlation = num(details.correlation);
- const coChanges = num(details.co_change_count);
if (!partner) return null;
- const corrPct =
- correlation != null ? `${Math.round(correlation * 100)}%` : null;
- const href = onPartnerHref ? onPartnerHref(partner) : undefined;
- const inner = (
- <span className="inline-flex items-center gap-1 font-mono truncate">
- <ArrowLeftRight className="h-3 w-3 shrink-0" aria-hidden="true" />
- <span className="truncate">{partner}</span>
- </span>
- );
+ const corrPct = pct(num(details.correlation));
+ const coChanges = num(details.co_change_count);
return (
<div className="text-[11px] text-[var(--color-text-tertiary)]">
- {href ? (
- <a
- href={href}
- onClick={(e) => {
- if (onPartnerSelect) {
- e.preventDefault();
- onPartnerSelect(partner);
- }
- }}
- className="text-[var(--color-accent-primary)] hover:underline"
- >
- {inner}
- </a>
- ) : onPartnerSelect ? (
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- onPartnerSelect(partner);
- }}
- className="text-[var(--color-accent-primary)] hover:underline text-left"
- >
- {inner}
- </button>
- ) : (
- inner
- )}
+ <PartnerLink
+ path={partner}
+ onPartnerSelect={onPartnerSelect}
+ onPartnerHref={onPartnerHref}
+ />
{corrPct || coChanges != null ? (
<span className="ml-1 tabular-nums">
{corrPct ? ` · ${corrPct} co-change` : ""}
@@ -84,41 +134,342 @@ export function BiomarkerDetails({
);
}
- if (biomarkerType === "complex_conditional") {
- const ops = num(details.operator_count);
- if (ops == null) return null;
+ if (biomarkerType === "dry_violation") {
+ const partner = str(details.worst_clone_partner);
+ const dup = num(details.duplication_pct);
+ const stats = joinStats(
+ dup != null ? `${dup.toFixed(0)}% duplicated` : null,
+ num(details.clone_pair_count) != null
+ ? `${num(details.clone_pair_count)} clone pairs`
+ : null,
+ num(details.worst_clone_lines) != null
+ ? `worst clone ${num(details.worst_clone_lines)} lines`
+ : null,
+ num(details.worst_clone_co_change)
+ ? `${num(details.worst_clone_co_change)} co-changes`
+ : null,
+ );
+ if (!partner && !stats) return null;
return (
- <div className="text-[11px] text-[var(--color-text-tertiary)] tabular-nums">
- ({ops} ops)
+ <div className="text-[11px] text-[var(--color-text-tertiary)]">
+ {stats ? <span className="tabular-nums">{stats}</span> : null}
+ {partner ? (
+ <div>
+ <PartnerLink
+ path={partner}
+ onPartnerSelect={onPartnerSelect}
+ onPartnerHref={onPartnerHref}
+ />
+ </div>
+ ) : null}
</div>
);
}
- if (biomarkerType === "function_hotspot") {
- const mod =
- num(details.modification_count) ?? num(details.mod_count);
- const p80 = num(details.repo_p80) ?? num(details.p80);
- if (mod == null) return null;
+ if (biomarkerType === "duplicated_assertion_block") {
+ const partner = str(details.partner_file);
+ const lines = Array.isArray(details.assertion_lines)
+ ? (details.assertion_lines as unknown[]).map(num).filter((v) => v != null)
+ : [];
return (
- <div className="text-[11px] text-[var(--color-text-tertiary)] tabular-nums">
- mod {mod}
- {p80 != null ? ` / p80 ${p80}` : ""}
+ <div className="text-[11px] text-[var(--color-text-tertiary)]">
+ {lines.length === 2 ? (
+ <span className="tabular-nums">lines {lines[0]}–{lines[1]}</span>
+ ) : null}
+ {partner ? (
+ <div>
+ <PartnerLink
+ path={partner}
+ onPartnerSelect={onPartnerSelect}
+ onPartnerHref={onPartnerHref}
+ />
+ </div>
+ ) : null}
</div>
);
}
- if (biomarkerType === "code_age_volatility") {
- const age = num(details.median_age_days);
- const recent = num(details.recent_mod_count);
- if (age == null && recent == null) return null;
- return (
- <div className="text-[11px] text-[var(--color-text-tertiary)] tabular-nums">
- {age != null ? `~${age}d old` : ""}
- {age != null && recent != null ? " · " : ""}
- {recent != null ? `${recent} edits/30d` : ""}
- </div>
- );
+ let line: string | null = null;
+ switch (biomarkerType) {
+ case "complex_conditional": {
+ const ops = num(details.operator_count);
+ const construct = str(details.enclosing_construct);
+ line =
+ ops == null
+ ? null
+ : `${ops} boolean operators${construct ? ` in ${construct}` : ""}`;
+ break;
+ }
+ case "function_hotspot": {
+ const mod = num(details.modification_count) ?? num(details.mod_count);
+ const p80 = num(details.repo_p80) ?? num(details.p80);
+ line =
+ mod == null
+ ? null
+ : joinStats(
+ `mod ${mod}${p80 != null ? ` / p80 ${p80}` : ""}`,
+ num(details.ccn) != null ? `CCN ${num(details.ccn)}` : null,
+ num(details.max_nesting) != null
+ ? `nest ${num(details.max_nesting)}`
+ : null,
+ );
+ break;
+ }
+ case "code_age_volatility": {
+ const age = num(details.median_age_days);
+ const recent = num(details.recent_mod_count);
+ line = joinStats(
+ age != null ? `~${age}d old` : null,
+ recent != null ? `${recent} edits/30d` : null,
+ );
+ break;
+ }
+ case "brain_method":
+ line = joinStats(
+ num(details.ccn) != null ? `CCN ${num(details.ccn)}` : null,
+ num(details.nloc) != null ? `${num(details.nloc)} NLOC` : null,
+ num(details.max_nesting) != null ? `nest ${num(details.max_nesting)}` : null,
+ num(details.dependents_count) != null
+ ? `${num(details.dependents_count)} dependents`
+ : null,
+ );
+ break;
+ case "complex_method":
+ line = joinStats(
+ num(details.ccn) != null ? `CCN ${num(details.ccn)}` : null,
+ num(details.cognitive) != null
+ ? `cognitive ${num(details.cognitive)}`
+ : null,
+ num(details.nloc) != null ? `${num(details.nloc)} NLOC` : null,
+ );
+ break;
+ case "large_method":
+ line = joinStats(
+ num(details.nloc) != null ? `${num(details.nloc)} NLOC` : null,
+ num(details.ccn) != null ? `CCN ${num(details.ccn)}` : null,
+ );
+ break;
+ case "nested_complexity":
+ line = joinStats(
+ num(details.max_nesting) != null
+ ? `nest ${num(details.max_nesting)}`
+ : null,
+ num(details.ccn) != null ? `CCN ${num(details.ccn)}` : null,
+ num(details.cognitive) != null
+ ? `cognitive ${num(details.cognitive)}`
+ : null,
+ );
+ break;
+ case "bumpy_road":
+ line = joinStats(
+ num(details.bumps) != null ? `${num(details.bumps)} bumps` : null,
+ num(details.ccn) != null ? `CCN ${num(details.ccn)}` : null,
+ num(details.max_nesting) != null ? `nest ${num(details.max_nesting)}` : null,
+ );
+ break;
+ case "primitive_obsession": {
+ const params = num(details.param_count);
+ line = params == null ? null : `${params} parameters`;
+ break;
+ }
+ case "god_class": {
+ const name = str(details.class_name);
+ const stats = joinStats(
+ num(details.method_count) != null
+ ? `${num(details.method_count)} methods`
+ : null,
+ num(details.total_nloc) != null
+ ? `${num(details.total_nloc)} NLOC`
+ : null,
+ num(details.max_method_ccn) != null
+ ? `max CCN ${num(details.max_method_ccn)}`
+ : null,
+ );
+ line = stats ? (name ? `${name}: ${stats}` : stats) : null;
+ break;
+ }
+ case "low_cohesion": {
+ const name = str(details.class_name);
+ const stats = joinStats(
+ num(details.lcom4) != null ? `LCOM4 ${num(details.lcom4)}` : null,
+ num(details.method_count) != null
+ ? `${num(details.method_count)} methods`
+ : null,
+ num(details.field_count) != null
+ ? `${num(details.field_count)} fields`
+ : null,
+ );
+ line = stats ? (name ? `${name}: ${stats}` : stats) : null;
+ break;
+ }
+ case "coverage_gap": {
+ const uncovered = num(details.uncovered_lines);
+ const total = num(details.total_coverable_lines);
+ line = joinStats(
+ uncovered != null && total != null
+ ? `${uncovered}/${total} lines uncovered`
+ : null,
+ num(details.line_coverage_pct) != null
+ ? `${num(details.line_coverage_pct)?.toFixed(0)}% line coverage`
+ : null,
+ num(details.branch_coverage_pct) != null
+ ? `${num(details.branch_coverage_pct)?.toFixed(0)}% branch`
+ : null,
+ );
+ break;
+ }
+ case "coverage_gradient":
+ line = joinStats(
+ num(details.line_coverage_pct) != null
+ ? `${num(details.line_coverage_pct)?.toFixed(0)}% line coverage`
+ : null,
+ pct(num(details.uncovered_fraction)) != null
+ ? `${pct(num(details.uncovered_fraction))} uncovered`
+ : null,
+ );
+ break;
+ case "untested_hotspot":
+ line = joinStats(
+ num(details.line_coverage_pct) != null
+ ? `${num(details.line_coverage_pct)?.toFixed(0)}% coverage`
+ : null,
+ details.has_test_file === false ? "no test file" : null,
+ num(details.dependents_count) != null
+ ? `${num(details.dependents_count)} dependents`
+ : null,
+ num(details.commit_count_90d) != null
+ ? `${num(details.commit_count_90d)} commits/90d`
+ : null,
+ );
+ break;
+ case "developer_congestion": {
+ const owner = str(details.primary_owner);
+ line = joinStats(
+ num(details.contributor_count) != null
+ ? `${num(details.contributor_count)} authors`
+ : null,
+ num(details.commit_count_90d) != null
+ ? `${num(details.commit_count_90d)} commits/90d`
+ : null,
+ pct(num(details.primary_owner_share)) != null
+ ? `top share ${pct(num(details.primary_owner_share))}${owner ? ` (${owner})` : ""}`
+ : null,
+ );
+ break;
+ }
+ case "knowledge_loss": {
+ const primary = str(details.primary_owner);
+ const recent = str(details.recent_owner);
+ line = joinStats(
+ num(details.bus_factor) != null
+ ? `bus factor ${num(details.bus_factor)}`
+ : null,
+ primary ? `primary ${primary}` : null,
+ recent
+ ? `recent ${recent}${
+ pct(num(details.recent_owner_share))
+ ? ` (${pct(num(details.recent_owner_share))})`
+ : ""
+ }`
+ : "no recent owner",
+ );
+ break;
+ }
+ case "ownership_risk":
+ line = joinStats(
+ num(details.minor_contributors) != null &&
+ num(details.contributor_count) != null
+ ? `${num(details.minor_contributors)} minor of ${num(details.contributor_count)} authors`
+ : null,
+ pct(num(details.top_owner_share)) != null
+ ? `top share ${pct(num(details.top_owner_share))}`
+ : null,
+ num(details.total_commits) != null
+ ? `${num(details.total_commits)} commits`
+ : null,
+ );
+ break;
+ case "churn_risk": {
+ const added = num(details.lines_added_90d);
+ const deleted = num(details.lines_deleted_90d);
+ line = joinStats(
+ num(details.relative_churn) != null
+ ? `relative churn ${num(details.relative_churn)?.toFixed(1)}×`
+ : null,
+ added != null || deleted != null
+ ? `+${added ?? 0}/−${deleted ?? 0} lines/90d`
+ : null,
+ num(details.commit_count_90d) != null
+ ? `${num(details.commit_count_90d)} commits`
+ : null,
+ );
+ break;
+ }
+ case "change_entropy": {
+ const p = num(details.change_entropy_pct);
+ line = joinStats(
+ p != null ? `top ${Math.max(0, Math.round((1 - p) * 100))}% entropy` : null,
+ num(details.commit_count_90d) != null
+ ? `${num(details.commit_count_90d)} commits/90d`
+ : null,
+ );
+ break;
+ }
+ case "co_change_scatter":
+ line = joinStats(
+ num(details.scatter) != null
+ ? `co-changes with ${num(details.scatter)} files`
+ : null,
+ num(details.commit_count_90d) != null
+ ? `${num(details.commit_count_90d)} commits/90d`
+ : null,
+ );
+ break;
+ case "prior_defect": {
+ const count = num(details.prior_defect_count);
+ const windowDays = num(details.window_days);
+ line =
+ count == null
+ ? null
+ : `${count} bug ${count === 1 ? "fix" : "fixes"}${
+ windowDays != null ? ` in ${windowDays}d` : ""
+ }`;
+ break;
+ }
+ case "large_assertion_block": {
+ const fn = str(details.function);
+ const count = num(details.assertion_count);
+ line =
+ count == null
+ ? null
+ : `${fn ? `${fn}: ` : ""}${count} assertions in one block`;
+ break;
+ }
+ case "error_handling": {
+ const kind = str(details.kind);
+ line = kind ? ERROR_HANDLING_KIND_LABEL[kind] ?? kind.replace(/_/g, " ") : null;
+ break;
+ }
+ case "stale_governance": {
+ const title = str(details.decision_title);
+ const staleness = num(details.staleness_score);
+ line = joinStats(
+ title ? `decision “${title}”` : null,
+ staleness != null ? `staleness ${staleness.toFixed(2)}` : null,
+ );
+ break;
+ }
+ case "contradictory_decision": {
+ const src = str(details.src_title);
+ const dst = str(details.dst_title);
+ line =
+ src && dst ? `“${src}” contradicts “${dst}”` : dst ? `contradicts “${dst}”` : null;
+ break;
+ }
+ default:
+ line = null;
}
- return null;
+ if (!line) return null;
+ return <StatLine>{line}</StatLine>;
}
diff --git a/packages/ui/src/health/biomarker-glossary.ts b/packages/ui/src/health/biomarker-glossary.ts
index c9253830d..0fd8b6b23 100644
--- a/packages/ui/src/health/biomarker-glossary.ts
+++ b/packages/ui/src/health/biomarker-glossary.ts
@@ -13,6 +13,8 @@ export type BiomarkerCategory =
| "duplication"
| "test_coverage"
| "test_coverage_gradient"
+ | "test_quality"
+ | "error_handling"
| "organizational";
export interface BiomarkerInfo {
@@ -27,6 +29,8 @@ export const CATEGORY_LABEL: Record<BiomarkerCategory, string> = {
duplication: "Duplication",
test_coverage: "Test coverage",
test_coverage_gradient: "Coverage gradient",
+ test_quality: "Test quality",
+ error_handling: "Error handling",
organizational: "Organizational",
};
@@ -37,6 +41,8 @@ export const CATEGORY_CAP: Record<BiomarkerCategory, number> = {
test_coverage_gradient: 2.0,
size_and_complexity: 1.5,
duplication: 1.0,
+ test_quality: 0.5,
+ error_handling: 0.5,
};
export const BIOMARKER_GLOSSARY: Record<string, BiomarkerInfo> = {
@@ -136,6 +142,84 @@ export const BIOMARKER_GLOSSARY: Record<string, BiomarkerInfo> = {
description:
"A long-stable function (median line age ≥ 1 year) that has suddenly started moving again. This edit profile is one of the strongest empirical predictors of regressions.",
},
+ low_cohesion: {
+ label: "Low cohesion",
+ category: "structural_complexity",
+ description:
+ "A class whose methods split into multiple disconnected groups (LCOM4 > 1). The groups share a namespace but not a responsibility — usually two classes living in one.",
+ },
+ god_class: {
+ label: "God class",
+ category: "structural_complexity",
+ description:
+ "A very large class with many methods including at least one brain method. It accumulates responsibilities until every change routes through it.",
+ },
+ ownership_risk: {
+ label: "Ownership risk",
+ category: "organizational",
+ description:
+ "Many minor contributors with no dominant owner. Fragmented ownership is a calibrated defect predictor — nobody holds the full picture of the file.",
+ },
+ churn_risk: {
+ label: "Churn risk",
+ category: "organizational",
+ description:
+ "Lines added and deleted at a rate far above the repo norm for the file's size. Relative churn is a classic defect-density predictor.",
+ },
+ change_entropy: {
+ label: "Change entropy",
+ category: "organizational",
+ description:
+ "Changes scattered across many unrelated commits rather than focused work. High entropy in the change history is a strong history-based fault predictor.",
+ },
+ co_change_scatter: {
+ label: "Co-change scatter",
+ category: "organizational",
+ description:
+ "Editing this file tends to ripple across many other files in the same commits (shotgun surgery). The strongest calibrated predictor in the score.",
+ },
+ prior_defect: {
+ label: "Prior defects",
+ category: "organizational",
+ description:
+ "Bug-fix commits touched this file repeatedly in the recent window. Recent defect history is the most cost-effective predictor of further defects.",
+ },
+ large_assertion_block: {
+ label: "Large assertion block",
+ category: "test_quality",
+ description:
+ "A test function running a long unbroken run of assertions. When one fails, the rest never execute — split into focused cases.",
+ },
+ duplicated_assertion_block: {
+ label: "Duplicated assertions",
+ category: "test_quality",
+ description:
+ "An assertion block copy-pasted across test files. Behaviour changes now require synchronized edits, and drift produces misleading green runs.",
+ },
+ error_handling: {
+ label: "Error handling",
+ category: "error_handling",
+ description:
+ "Swallowed exceptions, bare excepts, unsafe unwraps, or discarded error returns. An advisory maintainability flag — failures here vanish silently.",
+ },
+ ungoverned_hotspot: {
+ label: "Ungoverned hotspot",
+ category: "organizational",
+ description:
+ "A churn hotspot with no governing architectural decision on record. High-traffic code evolving without documented intent.",
+ },
+ stale_governance: {
+ label: "Stale governance",
+ category: "organizational",
+ description:
+ "The architectural decision governing this file has gone stale — the code has moved on since the decision was last confirmed.",
+ },
+ contradictory_decision: {
+ label: "Contradictory decision",
+ category: "organizational",
+ description:
+ "Two governing decisions on record contradict each other. The file is caught between conflicting documented intents.",
+ },
};
export function biomarkerInfo(name: string): BiomarkerInfo {
diff --git a/packages/ui/src/health/biomarker-list.tsx b/packages/ui/src/health/biomarker-list.tsx
index dae416cc5..fae46b6c1 100644
--- a/packages/ui/src/health/biomarker-list.tsx
+++ b/packages/ui/src/health/biomarker-list.tsx
@@ -2,6 +2,7 @@
import { useState } from "react";
import { ChevronDown, ChevronRight } from "lucide-react";
+import { InfoTip } from "../shared/info-tip";
import { biomarkerLabel, biomarkerInfo, CATEGORY_LABEL } from "./biomarker-glossary";
import { BiomarkerDetails, type BiomarkerDetailsRecord } from "./biomarker-details";
import { SEVERITY_CHIP, SEVERITY_LABEL, SEVERITY_ORDER, type Severity } from "./tokens";
@@ -130,6 +131,9 @@ function BiomarkerGroup({
<span className="text-sm font-medium text-[var(--color-text-primary)]">
{info.label}
</span>
+ {info.description ? (
+ <InfoTip content={info.description} label={`About ${info.label}`} />
+ ) : null}
<span className="text-xs text-[var(--color-text-tertiary)]">
{CATEGORY_LABEL[info.category]}
</span>
@@ -198,11 +202,17 @@ function FindingRow({
{SEVERITY_LABEL[f.severity]}
</span>
{!hideBiomarker ? (
- <span className="text-xs font-medium text-[var(--color-text-primary)]">
+ <span className="inline-flex items-center gap-1 text-xs font-medium text-[var(--color-text-primary)]">
{biomarkerLabel(f.biomarker_type)}
+ {biomarkerInfo(f.biomarker_type).description ? (
+ <InfoTip
+ content={biomarkerInfo(f.biomarker_type).description}
+ label={`About ${biomarkerLabel(f.biomarker_type)}`}
+ />
+ ) : null}
</span>
) : null}
- <span className="ml-auto text-xs tabular-nums text-red-500">
+ <span className="ml-auto text-xs tabular-nums text-[var(--color-error)]">
−{f.health_impact.toFixed(2)}
</span>
</div>
diff --git a/packages/ui/src/health/coverage-bar.tsx b/packages/ui/src/health/coverage-bar.tsx
index c5a31504c..6ffd47eb5 100644
--- a/packages/ui/src/health/coverage-bar.tsx
+++ b/packages/ui/src/health/coverage-bar.tsx
@@ -1,16 +1,11 @@
+import { coverageColor as color } from "./tokens";
+
export interface CoverageBarProps {
value: number | null | undefined;
label?: string;
size?: "sm" | "md";
}
-function color(pct: number): string {
- if (pct < 30) return "bg-red-500";
- if (pct < 60) return "bg-amber-500";
- if (pct < 80) return "bg-yellow-400";
- return "bg-emerald-500";
-}
-
export function CoverageBar({ value, label, size = "md" }: CoverageBarProps) {
const pct = value == null ? 0 : Math.max(0, Math.min(100, value));
const has = value != null;
diff --git a/packages/ui/src/health/defect-accuracy-card.tsx b/packages/ui/src/health/defect-accuracy-card.tsx
index 641332f28..dd15fbb4e 100644
--- a/packages/ui/src/health/defect-accuracy-card.tsx
+++ b/packages/ui/src/health/defect-accuracy-card.tsx
@@ -1,7 +1,7 @@
"use client";
import { useState } from "react";
-import { Check, Minus, Target, HelpCircle } from "lucide-react";
+import { Check, ChevronDown, ChevronRight, Minus, Target, HelpCircle } from "lucide-react";
import { Card } from "../ui/card";
export interface DefectAccuracyFile {
@@ -44,8 +44,16 @@ export interface DefectAccuracy {
* lacks enough files or defect history to be honest, in which case the
* caller should render nothing.
*/
-export function DefectAccuracyCard({ data }: { data: DefectAccuracy }) {
+export function DefectAccuracyCard({
+ data,
+ collapsible = false,
+}: {
+ data: DefectAccuracy;
+ /** Start as a one-line "can you trust this score?" row that expands on click. */
+ collapsible?: boolean;
+}) {
const [open, setOpen] = useState(false);
+ const [expanded, setExpanded] = useState(!collapsible);
const months = Math.max(1, Math.round(data.window_days / 30));
const windowLabel = months === 1 ? "month" : `${months} months`;
@@ -54,13 +62,47 @@ export function DefectAccuracyCard({ data }: { data: DefectAccuracy }) {
const concPct = Math.round(data.concentration_defect_share * 100);
const concFilePct = Math.round(data.concentration_file_fraction * 100);
+ if (!expanded) {
+ return (
+ <Card className="p-0">
+ <button
+ type="button"
+ onClick={() => setExpanded(true)}
+ aria-expanded={false}
+ className="flex w-full flex-wrap items-center gap-2 px-4 py-3 text-left hover:bg-[var(--color-bg-elevated)] transition-colors rounded-lg"
+ >
+ <ChevronRight className="h-4 w-4 shrink-0 text-[var(--color-text-tertiary)]" aria-hidden />
+ <Target className="h-4 w-4 shrink-0 text-[var(--color-accent-primary)]" aria-hidden />
+ <span className="text-sm font-medium text-[var(--color-text-primary)]">
+ Can you trust this score?
+ </span>
+ <span className="text-xs text-[var(--color-text-secondary)]">
+ {data.hits}/{data.k} lowest-health files were bug-fixed in the last {windowLabel}
+ {data.lift != null ? ` — ${data.lift}× the ${basePct}% baseline` : ""}
+ </span>
+ </button>
+ </Card>
+ );
+ }
+
return (
<Card className="p-4">
<div className="flex items-start justify-between gap-3">
<div className="flex items-center gap-2">
+ {collapsible ? (
+ <button
+ type="button"
+ onClick={() => setExpanded(false)}
+ aria-label="Collapse"
+ aria-expanded
+ className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
+ >
+ <ChevronDown className="h-4 w-4" aria-hidden />
+ </button>
+ ) : null}
<Target className="h-4 w-4 text-[var(--color-accent-primary)]" aria-hidden />
<h3 className="text-sm font-medium text-[var(--color-text-primary)]">
- Does the health score find the bugs?
+ {collapsible ? "Can you trust this score?" : "Does the health score find the bugs?"}
</h3>
</div>
<button
diff --git a/packages/ui/src/health/file-table.tsx b/packages/ui/src/health/file-table.tsx
index 88f3bc0c2..adce687ae 100644
--- a/packages/ui/src/health/file-table.tsx
+++ b/packages/ui/src/health/file-table.tsx
@@ -1,6 +1,11 @@
"use client";
-import { ArrowDown, ArrowUp, FileText } from "lucide-react";
+import { FileText } from "lucide-react";
+import { EmptyState } from "../shared/empty-state";
+import {
+ ResponsiveTable,
+ type ResponsiveColumn,
+} from "../shared/responsive-table";
import { scoreBadgeClass } from "./tokens";
export interface HealthFileRow {
@@ -34,24 +39,13 @@ export interface HealthFileTableProps {
emptyMessage?: string;
}
-interface ColDef {
- key: FileSortField | "tests";
- label: string;
- align: "left" | "right" | "center";
- sortable: boolean;
- className?: string;
+function num(value: number): string {
+ return String(value);
}
-const COLS: ColDef[] = [
- { key: "file_path", label: "File", align: "left", sortable: true },
- { key: "score", label: "Score", align: "right", sortable: true },
- { key: "max_ccn", label: "CCN", align: "right", sortable: true },
- { key: "max_nesting", label: "Nest", align: "right", sortable: true },
- { key: "nloc", label: "NLOC", align: "right", sortable: true },
- { key: "duplication_pct", label: "Dup %", align: "right", sortable: true },
- { key: "line_coverage_pct", label: "Cov", align: "right", sortable: true },
- { key: "tests", label: "Tests", align: "center", sortable: false },
-];
+function pct(value: number | null | undefined): string {
+ return value == null ? "—" : `${value.toFixed(0)}%`;
+}
export function HealthFileTable({
files,
@@ -62,91 +56,113 @@ export function HealthFileTable({
selectedPath,
emptyMessage,
}: HealthFileTableProps) {
- if (files.length === 0) {
- return (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-6 text-sm text-[var(--color-text-secondary)]">
- {emptyMessage ?? "No files match the current filters."}
- </div>
- );
- }
+ const columns: ResponsiveColumn<HealthFileRow>[] = [
+ {
+ key: "file_path",
+ header: "File",
+ priority: 1,
+ sortable: true,
+ cellClassName: "text-[var(--color-text-primary)] font-mono text-xs max-w-[440px]",
+ render: (f) => (
+ <span className="flex items-center gap-1.5 min-w-0">
+ <FileText className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />
+ <span className="truncate" title={f.file_path}>
+ {f.file_path}
+ </span>
+ </span>
+ ),
+ },
+ {
+ key: "score",
+ header: "Score",
+ align: "right",
+ priority: 1,
+ sortable: true,
+ render: (f) => (
+ <span
+ className={`inline-block rounded px-2 py-0.5 text-xs font-semibold tabular-nums ${scoreBadgeClass(f.score)}`}
+ >
+ {f.score.toFixed(1)}
+ </span>
+ ),
+ },
+ {
+ key: "max_ccn",
+ header: "CCN",
+ align: "right",
+ priority: 2,
+ sortable: true,
+ cellClassName: "tabular-nums text-[var(--color-text-secondary)]",
+ render: (f) => num(f.max_ccn),
+ },
+ {
+ key: "max_nesting",
+ header: "Nest",
+ align: "right",
+ priority: 3,
+ sortable: true,
+ cellClassName: "tabular-nums text-[var(--color-text-secondary)]",
+ render: (f) => num(f.max_nesting),
+ },
+ {
+ key: "nloc",
+ header: "NLOC",
+ align: "right",
+ priority: 3,
+ sortable: true,
+ cellClassName: "tabular-nums text-[var(--color-text-secondary)]",
+ render: (f) => num(f.nloc),
+ },
+ {
+ key: "duplication_pct",
+ header: "Dup %",
+ mobileLabel: "Dup",
+ align: "right",
+ priority: 2,
+ sortable: true,
+ cellClassName: "tabular-nums text-[var(--color-text-secondary)]",
+ render: (f) => pct(f.duplication_pct),
+ },
+ {
+ key: "line_coverage_pct",
+ header: "Cov",
+ align: "right",
+ priority: 2,
+ sortable: true,
+ cellClassName: "tabular-nums text-[var(--color-text-secondary)]",
+ render: (f) => pct(f.line_coverage_pct),
+ },
+ {
+ key: "tests",
+ header: "Tests",
+ align: "center",
+ priority: 3,
+ cellClassName: "text-xs",
+ render: (f) =>
+ f.has_test_file ? (
+ <span className="text-[var(--color-success)]">✓</span>
+ ) : (
+ <span className="text-[var(--color-text-tertiary)]">—</span>
+ ),
+ },
+ ];
+
return (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] overflow-hidden">
- <table className="w-full text-sm">
- <thead className="bg-[var(--color-bg-elevated)] text-[var(--color-text-tertiary)] text-xs uppercase tracking-wider sticky top-0">
- <tr>
- {COLS.map((c) => {
- const isActive = c.sortable && c.key === sortField;
- const alignCls =
- c.align === "right" ? "text-right" : c.align === "center" ? "text-center" : "text-left";
- return (
- <th
- key={c.key}
- className={`px-3 py-2 font-medium ${alignCls} ${c.sortable ? "cursor-pointer select-none" : ""}`}
- onClick={c.sortable && onSort ? () => onSort(c.key as FileSortField) : undefined}
- >
- <span className="inline-flex items-center gap-1">
- {c.label}
- {isActive ? (
- sortOrder === "asc" ? (
- <ArrowUp className="h-3 w-3" />
- ) : (
- <ArrowDown className="h-3 w-3" />
- )
- ) : null}
- </span>
- </th>
- );
- })}
- </tr>
- </thead>
- <tbody>
- {files.map((f) => {
- const isSelected = selectedPath === f.file_path;
- const rowCls = `border-t border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)] ${
- isSelected ? "bg-[var(--color-accent-muted)]/30" : ""
- } ${onSelect ? "cursor-pointer" : ""}`;
- return (
- <tr
- key={f.file_path}
- className={rowCls}
- onClick={onSelect ? () => onSelect(f) : undefined}
- >
- <td className="px-3 py-2 text-[var(--color-text-primary)] font-mono text-xs truncate max-w-[440px]">
- <span className="inline-flex items-center gap-1.5">
- <FileText className="h-3 w-3 text-[var(--color-text-tertiary)]" />
- <span className="truncate" title={f.file_path}>
- {f.file_path}
- </span>
- </span>
- </td>
- <td className="px-3 py-2 text-right">
- <span
- className={`inline-block rounded px-2 py-0.5 text-xs font-semibold tabular-nums ${scoreBadgeClass(f.score)}`}
- >
- {f.score.toFixed(1)}
- </span>
- </td>
- <td className="px-3 py-2 text-right tabular-nums text-[var(--color-text-secondary)]">{f.max_ccn}</td>
- <td className="px-3 py-2 text-right tabular-nums text-[var(--color-text-secondary)]">{f.max_nesting}</td>
- <td className="px-3 py-2 text-right tabular-nums text-[var(--color-text-secondary)]">{f.nloc}</td>
- <td className="px-3 py-2 text-right tabular-nums text-[var(--color-text-secondary)]">
- {f.duplication_pct == null ? "—" : `${f.duplication_pct.toFixed(0)}%`}
- </td>
- <td className="px-3 py-2 text-right tabular-nums text-[var(--color-text-secondary)]">
- {f.line_coverage_pct == null ? "—" : `${f.line_coverage_pct.toFixed(0)}%`}
- </td>
- <td className="px-3 py-2 text-center text-xs">
- {f.has_test_file ? (
- <span className="text-emerald-500">✓</span>
- ) : (
- <span className="text-[var(--color-text-tertiary)]">—</span>
- )}
- </td>
- </tr>
- );
- })}
- </tbody>
- </table>
- </div>
+ <ResponsiveTable
+ columns={columns}
+ rows={files}
+ rowKey={(f) => f.file_path}
+ onRowClick={onSelect}
+ selectedKey={selectedPath ?? null}
+ sortField={sortField}
+ sortOrder={sortOrder}
+ onSort={onSort ? (key) => onSort(key as FileSortField) : undefined}
+ empty={
+ <EmptyState
+ title="No files match"
+ description={emptyMessage ?? "No files match the current filters."}
+ />
+ }
+ />
);
}
diff --git a/packages/ui/src/health/health-badge.tsx b/packages/ui/src/health/health-badge.tsx
index 286cede98..598766d5c 100644
--- a/packages/ui/src/health/health-badge.tsx
+++ b/packages/ui/src/health/health-badge.tsx
@@ -1,21 +1,17 @@
+import { scoreSoftBadgeClass } from "./tokens";
+
export interface HealthBadgeProps {
score: number | null | undefined;
size?: "xs" | "sm";
}
-function scoreColor(score: number): string {
- if (score < 4) return "bg-red-500/15 text-red-500";
- if (score < 6) return "bg-amber-500/15 text-amber-500";
- if (score < 8) return "bg-yellow-500/15 text-yellow-500";
- return "bg-emerald-500/15 text-emerald-500";
-}
-
/** Compact health-score pill, designed to inline next to a file path
* on Hotspot / Ownership / Graph rows without changing those shared
- * components' shapes. Renders nothing when the score is missing. */
+ * components' shapes. Renders nothing when the score is missing.
+ * Colors come from the shared score-band helper in tokens.ts. */
export function HealthBadge({ score, size = "xs" }: HealthBadgeProps) {
if (score == null) return null;
- const cls = scoreColor(score);
+ const cls = scoreSoftBadgeClass(score);
const sizing =
size === "xs"
? "text-[10px] px-1.5 py-0.5"
diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsx
index 7ebaf9448..cd2d02cb4 100644
--- a/packages/ui/src/health/health-file-drawer.tsx
+++ b/packages/ui/src/health/health-file-drawer.tsx
@@ -1,7 +1,9 @@
"use client";
-import { useEffect } from "react";
-import { ExternalLink, X } from "lucide-react";
+import { useState } from "react";
+import { ExternalLink } from "lucide-react";
+import { AdaptivePanel } from "../shared/adaptive-panel";
+import { InfoTip } from "../shared/info-tip";
import { biomarkerLabel, biomarkerInfo, CATEGORY_LABEL } from "./biomarker-glossary";
import { BiomarkerDetails, type BiomarkerDetailsRecord } from "./biomarker-details";
import { ScoreBreakdown, type ScoreBreakdownCategory } from "./score-breakdown";
@@ -55,8 +57,19 @@ export interface HealthFileDrawerProps {
permalinkHref?: string;
onPartnerSelect?: ((path: string) => void) | undefined;
onPartnerHref?: ((path: string) => string) | undefined;
+ /** Triage callback — PATCH the finding status. Buttons hide when absent. */
+ onFindingStatusChange?:
+ | ((findingId: string, status: string) => Promise<void> | void)
+ | undefined;
}
+const TRIAGE_STATUSES: { value: string; label: string }[] = [
+ { value: "open", label: "Open" },
+ { value: "acknowledged", label: "Acknowledged" },
+ { value: "resolved", label: "Resolved" },
+ { value: "false_positive", label: "False positive" },
+];
+
export function HealthFileDrawer({
open,
onClose,
@@ -70,57 +83,41 @@ export function HealthFileDrawer({
permalinkHref,
onPartnerSelect,
onPartnerHref,
+ onFindingStatusChange,
}: HealthFileDrawerProps) {
- // ESC to close
- useEffect(() => {
- if (!open) return;
- const handler = (e: KeyboardEvent) => {
- if (e.key === "Escape") onClose();
- };
- window.addEventListener("keydown", handler);
- return () => window.removeEventListener("keydown", handler);
- }, [open, onClose]);
-
- if (!open) return null;
+ const [statusOverride, setStatusOverride] = useState<Record<string, string>>({});
+ const [savingId, setSavingId] = useState<string | null>(null);
+ const setStatus = async (id: string, status: string) => {
+ if (!onFindingStatusChange) return;
+ setSavingId(id);
+ try {
+ await onFindingStatusChange(id, status);
+ setStatusOverride((m) => ({ ...m, [id]: status }));
+ } finally {
+ setSavingId(null);
+ }
+ };
return (
- <div className="fixed inset-0 z-50 flex" role="dialog" aria-modal="true">
- <button
- type="button"
- aria-label="Close drawer"
- onClick={onClose}
- className="flex-1 bg-black/50 backdrop-blur-[1px]"
- />
- <aside className="w-full max-w-[640px] bg-[var(--color-bg-surface)] border-l border-[var(--color-border-default)] overflow-y-auto shadow-xl">
- <header className="sticky top-0 z-10 flex items-start justify-between gap-3 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-4 py-3">
- <div className="min-w-0 flex-1">
- <p className="text-xs uppercase tracking-wider text-[var(--color-text-tertiary)]">File health</p>
- <p className="font-mono text-sm text-[var(--color-text-primary)] truncate" title={metric?.file_path}>
- {metric?.file_path ?? "Loading…"}
- </p>
- </div>
- <div className="flex items-center gap-2 shrink-0">
- {permalinkHref ? (
- <a
- href={permalinkHref}
- className="text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] inline-flex items-center gap-1"
- title="Open as a shareable page"
- >
- <ExternalLink className="h-3.5 w-3.5" />
- Permalink
- </a>
- ) : null}
- <button
- type="button"
- onClick={onClose}
- aria-label="Close"
- className="rounded p-1 text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
- >
- <X className="h-4 w-4" />
- </button>
- </div>
- </header>
-
+ <AdaptivePanel
+ open={open}
+ onOpenChange={(next) => {
+ if (!next) onClose();
+ }}
+ eyebrow="File health"
+ title={metric?.file_path ?? "Loading…"}
+ widthClassName="md:max-w-[640px]"
+ >
<div className="px-4 py-4 space-y-5">
+ {permalinkHref ? (
+ <a
+ href={permalinkHref}
+ className="inline-flex items-center gap-1 text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
+ title="Open as a shareable page"
+ >
+ <ExternalLink className="h-3.5 w-3.5" />
+ Open full page
+ </a>
+ ) : null}
{loading ? (
<div className="text-sm text-[var(--color-text-tertiary)]">Loading…</div>
) : !metric ? (
@@ -193,8 +190,14 @@ export function HealthFileDrawer({
<span className={`inline-block rounded px-1.5 py-px text-[10px] uppercase font-semibold ${SEVERITY_CHIP[f.severity]}`}>
{SEVERITY_LABEL[f.severity]}
</span>
- <span className="text-xs font-semibold text-[var(--color-text-primary)]">
+ <span className="inline-flex items-center gap-1 text-xs font-semibold text-[var(--color-text-primary)]">
{biomarkerLabel(f.biomarker_type)}
+ {info.description ? (
+ <InfoTip
+ content={info.description}
+ label={`About ${biomarkerLabel(f.biomarker_type)}`}
+ />
+ ) : null}
</span>
<span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
{CATEGORY_LABEL[info.category]}
@@ -220,7 +223,7 @@ export function HealthFileDrawer({
</span>
);
})() : null}
- <span className="ml-auto text-xs tabular-nums text-red-500">−{f.health_impact.toFixed(2)}</span>
+ <span className="ml-auto text-xs tabular-nums text-[var(--color-error)]">−{f.health_impact.toFixed(2)}</span>
</div>
<p className="text-xs text-[var(--color-text-secondary)]">{f.reason}</p>
<BiomarkerDetails
@@ -234,6 +237,28 @@ export function HealthFileDrawer({
{suggestions[f.biomarker_type]}
</p>
) : null}
+ {onFindingStatusChange ? (
+ <div className="flex flex-wrap items-center gap-1.5 pt-1">
+ {TRIAGE_STATUSES.map((opt) => {
+ const current = statusOverride[f.id] ?? f.status ?? "open";
+ return (
+ <button
+ key={opt.value}
+ type="button"
+ disabled={savingId === f.id || current === opt.value}
+ onClick={() => setStatus(f.id, opt.value)}
+ className={`rounded border px-1.5 py-0.5 text-[10px] transition-colors ${
+ current === opt.value
+ ? "border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"
+ : "border-[var(--color-border-default)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"
+ }`}
+ >
+ {opt.label}
+ </button>
+ );
+ })}
+ </div>
+ ) : null}
</li>
);
})}
@@ -243,8 +268,7 @@ export function HealthFileDrawer({
</>
)}
</div>
- </aside>
- </div>
+ </AdaptivePanel>
);
}
diff --git a/packages/ui/src/health/health-tabs.tsx b/packages/ui/src/health/health-tabs.tsx
index 1656c8bf3..c7ab91a46 100644
--- a/packages/ui/src/health/health-tabs.tsx
+++ b/packages/ui/src/health/health-tabs.tsx
@@ -40,7 +40,7 @@ export function HealthTabs({ repoId, active, basePath, renderLink }: HealthTabsP
const baseCls =
"inline-flex items-center gap-1.5 px-3 py-2 text-sm font-medium border-b-2 transition-colors";
const activeCls = isActive
- ? "border-emerald-500 text-[var(--color-text-primary)]"
+ ? "border-[var(--color-accent-primary)] text-[var(--color-text-primary)]"
: "border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-default)]";
const icon = <t.Icon className="h-4 w-4" />;
if (renderLink) {
diff --git a/packages/ui/src/health/hot-functions-panel.tsx b/packages/ui/src/health/hot-functions-panel.tsx
index e81f24029..b2e6a7511 100644
--- a/packages/ui/src/health/hot-functions-panel.tsx
+++ b/packages/ui/src/health/hot-functions-panel.tsx
@@ -15,6 +15,8 @@ export interface HotFunctionFinding {
health_impact: number;
reason: string;
details?: BiomarkerDetailsRecord | null;
+ /** Matching symbol id (server join); enables the symbol-page link. */
+ symbol_id?: string | null;
}
export interface HotFunctionsPanelProps {
@@ -23,6 +25,8 @@ export interface HotFunctionsPanelProps {
limit?: number;
/** Click → open file drawer (and ideally scroll to the function). */
onSelect?: ((f: HotFunctionFinding) => void) | undefined;
+ /** Href for the function name → canonical symbol page. */
+ symbolHrefFor?: ((f: HotFunctionFinding) => string | undefined) | undefined;
}
const HOT_FUNCTION_BIOMARKERS = new Set([
@@ -83,6 +87,7 @@ export function HotFunctionsPanel({
findings,
limit = 15,
onSelect,
+ symbolHrefFor,
}: HotFunctionsPanelProps) {
const rows = aggregate(findings).slice(0, limit);
if (rows.length === 0) return null;
@@ -90,7 +95,7 @@ export function HotFunctionsPanel({
return (
<section className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">
<header className="flex items-center gap-2 px-4 py-3 border-b border-[var(--color-border-default)]">
- <Flame className="h-4 w-4 text-amber-500" aria-hidden="true" />
+ <Flame className="h-4 w-4 text-[var(--color-warning)]" aria-hidden="true" />
<h2 className="text-sm font-medium text-[var(--color-text-primary)]">
Hot functions
</h2>
@@ -116,14 +121,30 @@ export function HotFunctionsPanel({
>
{SEVERITY_LABEL[row.worst_severity]}
</span>
- <span className="text-xs font-mono text-[var(--color-text-primary)]">
- {row.function_name}
- </span>
+ {(() => {
+ const href = symbolHrefFor
+ ? symbolHrefFor(row.representative)
+ : undefined;
+ return href ? (
+ <a
+ href={href}
+ onClick={(e) => e.stopPropagation()}
+ className="text-xs font-mono text-[var(--color-accent-primary)] hover:underline"
+ title="Open symbol page"
+ >
+ {row.function_name}
+ </a>
+ ) : (
+ <span className="text-xs font-mono text-[var(--color-text-primary)]">
+ {row.function_name}
+ </span>
+ );
+ })()}
<span className="text-[11px] font-mono text-[var(--color-text-tertiary)] truncate">
{row.file_path}
</span>
<span className="ml-auto inline-flex items-center gap-2">
- <span className="text-xs tabular-nums text-red-500">
+ <span className="text-xs tabular-nums text-[var(--color-error)]">
−{row.total_impact.toFixed(2)}
</span>
{interactive ? (
diff --git a/packages/ui/src/health/impact-effort-quadrant.tsx b/packages/ui/src/health/impact-effort-quadrant.tsx
index e488521f0..12704e4c9 100644
--- a/packages/ui/src/health/impact-effort-quadrant.tsx
+++ b/packages/ui/src/health/impact-effort-quadrant.tsx
@@ -71,10 +71,10 @@ export function ImpactEffortQuadrant({
</div>
<div className="relative">
<svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} role="img" aria-label="Impact vs effort scatter plot">
- <rect x={padL} y={padT} width={midX - padL} height={midY - padT} fill="currentColor" className="text-emerald-500/8" />
- <rect x={midX} y={padT} width={W - padR - midX} height={midY - padT} fill="currentColor" className="text-amber-500/5" />
- <rect x={padL} y={midY} width={midX - padL} height={H - padB - midY} fill="currentColor" className="text-yellow-500/5" />
- <rect x={midX} y={midY} width={W - padR - midX} height={H - padB - midY} fill="currentColor" className="text-red-500/5" />
+ <rect x={padL} y={padT} width={midX - padL} height={midY - padT} fill="currentColor" className="text-[var(--color-success)]/8" />
+ <rect x={midX} y={padT} width={W - padR - midX} height={midY - padT} fill="currentColor" className="text-[var(--color-warning)]/5" />
+ <rect x={padL} y={midY} width={midX - padL} height={H - padB - midY} fill="currentColor" className="text-[var(--color-caution)]/5" />
+ <rect x={midX} y={midY} width={W - padR - midX} height={H - padB - midY} fill="currentColor" className="text-[var(--color-error)]/5" />
<line x1={padL} y1={padT} x2={padL} y2={H - padB} stroke="currentColor" strokeOpacity={0.2} />
<line x1={padL} y1={H - padB} x2={W - padR} y2={H - padB} stroke="currentColor" strokeOpacity={0.2} />
@@ -103,7 +103,14 @@ export function ImpactEffortQuadrant({
const cx = baseX + jitter(p.file_path);
const cy = yScale(p.total_impact);
const isHovered = hovered?.file_path === p.file_path;
- const fillCls = p.score < 4 ? "fill-red-500" : p.score < 7 ? "fill-amber-500" : "fill-emerald-500";
+ const fillCls =
+ p.score < 4
+ ? "fill-[var(--color-error)]"
+ : p.score < 6
+ ? "fill-[var(--color-warning)]"
+ : p.score < 8
+ ? "fill-[var(--color-caution)]"
+ : "fill-[var(--color-success)]";
return (
<circle
key={p.file_path}
diff --git a/packages/ui/src/health/kpi-cards.tsx b/packages/ui/src/health/kpi-cards.tsx
index ab70c1f03..97f70ee09 100644
--- a/packages/ui/src/health/kpi-cards.tsx
+++ b/packages/ui/src/health/kpi-cards.tsx
@@ -1,4 +1,5 @@
import { formatNumber } from "../lib/format";
+import { InfoTip } from "../shared/info-tip";
import { scoreTextColor, formatDelta, deltaColor } from "./tokens";
import { Sparkline } from "./sparkline";
import { SeverityDistribution, type SeverityBreakdown } from "./severity-distribution";
@@ -50,7 +51,7 @@ export function HealthKpiCards({
label="Hotspot Health"
sparkline={hotspotHistory}
delta={hotspotDelta}
- hint="NLOC-weighted score over the repo's high-churn files."
+ hint="The health score averaged over the repo's churn hotspots only (NLOC-weighted). Not a hotspot count — it answers “how healthy is the code you touch most?”"
>
<p
className={`text-2xl font-bold tabular-nums ${scoreTextColor(summary.hotspot_health ?? null)}`}
@@ -103,13 +104,11 @@ function Card({
hint?: string | undefined;
}) {
return (
- <div
- className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4"
- title={hint}
- >
+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">
<div className="flex items-start justify-between gap-2 mb-1">
- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
+ <p className="inline-flex items-center gap-1 text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
{label}
+ {hint ? <InfoTip content={hint} label={`About ${label}`} /> : null}
</p>
{sparkline && sparkline.length > 0 ? (
<div className="text-[var(--color-text-tertiary)]">
diff --git a/packages/ui/src/health/refactoring-card.tsx b/packages/ui/src/health/refactoring-card.tsx
index 152905dd5..4d001ee97 100644
--- a/packages/ui/src/health/refactoring-card.tsx
+++ b/packages/ui/src/health/refactoring-card.tsx
@@ -2,7 +2,8 @@
import { useState } from "react";
import { ArrowUpRight, ChevronDown, ChevronRight, Sparkles } from "lucide-react";
-import { biomarkerLabel } from "./biomarker-glossary";
+import { InfoTip } from "../shared/info-tip";
+import { biomarkerInfo, biomarkerLabel } from "./biomarker-glossary";
import type { BiomarkerDetailsRecord } from "./biomarker-details";
import { SEVERITY_CHIP, SEVERITY_LABEL, type Severity } from "./tokens";
@@ -50,6 +51,8 @@ export interface RefactoringCardProps {
onStatusChange?: ((findingId: string, status: FindingStatus) => void) | undefined;
onGeneratePrompt?: ((target: RefactoringTarget) => void) | undefined;
expandable?: boolean;
+ /** Flash-highlight the card (e.g. after a quadrant dot click scrolled to it). */
+ highlighted?: boolean;
}
const effortLabel: Record<EffortBucket, string> = {
@@ -60,10 +63,10 @@ const effortLabel: Record<EffortBucket, string> = {
};
const effortColor: Record<EffortBucket, string> = {
- S: "bg-emerald-500/15 text-emerald-500",
- M: "bg-yellow-500/15 text-yellow-600",
- L: "bg-amber-500/15 text-amber-500",
- XL: "bg-red-500/15 text-red-500",
+ S: "bg-[var(--color-success)]/15 text-[var(--color-success)]",
+ M: "bg-[var(--color-caution)]/15 text-[var(--color-caution)]",
+ L: "bg-[var(--color-warning)]/15 text-[var(--color-warning)]",
+ XL: "bg-[var(--color-error)]/15 text-[var(--color-error)]",
};
export function RefactoringCard({
@@ -72,10 +75,18 @@ export function RefactoringCard({
onStatusChange,
onGeneratePrompt,
expandable = true,
+ highlighted = false,
}: RefactoringCardProps) {
const [expanded, setExpanded] = useState(false);
return (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] overflow-hidden">
+ <div
+ data-refactoring-card={target.file_path}
+ className={`rounded-lg border bg-[var(--color-bg-surface)] overflow-hidden transition-colors ${
+ highlighted
+ ? "border-[var(--color-accent-primary)] ring-1 ring-[var(--color-accent-primary)]/40"
+ : "border-[var(--color-border-default)]"
+ }`}
+ >
<div className="p-4 space-y-2">
<div className="flex items-center gap-2 flex-wrap">
<span
@@ -83,8 +94,14 @@ export function RefactoringCard({
>
{SEVERITY_LABEL[target.primary_severity]}
</span>
- <span className="text-xs font-semibold text-[var(--color-text-primary)]">
+ <span className="inline-flex items-center gap-1 text-xs font-semibold text-[var(--color-text-primary)]">
{biomarkerLabel(target.primary_biomarker)}
+ {biomarkerInfo(target.primary_biomarker).description ? (
+ <InfoTip
+ content={biomarkerInfo(target.primary_biomarker).description}
+ label={`About ${biomarkerLabel(target.primary_biomarker)}`}
+ />
+ ) : null}
</span>
{target.module ? (
<span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)] rounded px-1.5 py-0.5 border border-[var(--color-border-default)]">
@@ -97,7 +114,7 @@ export function RefactoringCard({
>
{target.effort_bucket}
</span>
- <span className="ml-auto text-xs tabular-nums text-red-500" title="Total health impact across this file's findings">
+ <span className="ml-auto text-xs tabular-nums text-[var(--color-error)]" title="Total health impact across this file's findings">
−{target.total_impact.toFixed(2)}
</span>
</div>
@@ -142,7 +159,7 @@ export function RefactoringCard({
e.stopPropagation();
onGeneratePrompt(target);
}}
- className="group/ai inline-flex items-center gap-1.5 rounded-md border border-emerald-500/40 bg-emerald-500/10 px-2.5 py-1 text-xs font-semibold text-emerald-600 hover:bg-emerald-500/20 hover:border-emerald-500/60 transition-colors"
+ className="group/ai inline-flex items-center gap-1.5 rounded-md border border-[var(--color-success)]/40 bg-[var(--color-success)]/10 px-2.5 py-1 text-xs font-semibold text-[var(--color-success)] hover:bg-[var(--color-success)]/20 hover:border-[var(--color-success)]/60 transition-colors"
title="Generate a ready-to-paste prompt for an AI coding agent"
>
<Sparkles className="h-3.5 w-3.5 transition-transform group-hover/ai:rotate-12" />
@@ -177,7 +194,7 @@ export function RefactoringCard({
{f.function_name ? (
<span className="text-xs font-mono text-[var(--color-text-tertiary)]">{f.function_name}</span>
) : null}
- <span className="ml-auto text-[11px] tabular-nums text-red-500">
+ <span className="ml-auto text-[11px] tabular-nums text-[var(--color-error)]">
−{f.health_impact.toFixed(2)}
</span>
</div>
diff --git a/packages/ui/src/health/refactoring-target-list.tsx b/packages/ui/src/health/refactoring-target-list.tsx
index d15328d6a..68f647f18 100644
--- a/packages/ui/src/health/refactoring-target-list.tsx
+++ b/packages/ui/src/health/refactoring-target-list.tsx
@@ -6,6 +6,8 @@ export interface RefactoringTargetListProps {
onStatusChange?: ((findingId: string, status: FindingStatus) => void) | undefined;
onGeneratePrompt?: ((target: RefactoringTarget) => void) | undefined;
emptyMessage?: string;
+ /** File path of the card to flash-highlight (quadrant click). */
+ highlightedPath?: string | null | undefined;
}
export function RefactoringTargetList({
@@ -14,6 +16,7 @@ export function RefactoringTargetList({
onStatusChange,
onGeneratePrompt,
emptyMessage = "No refactoring targets match the current filters.",
+ highlightedPath,
}: RefactoringTargetListProps) {
if (targets.length === 0) {
return (
@@ -31,6 +34,7 @@ export function RefactoringTargetList({
onSelect={onSelect}
onStatusChange={onStatusChange}
onGeneratePrompt={onGeneratePrompt}
+ highlighted={highlightedPath === t.file_path}
/>
))}
</div>
diff --git a/packages/ui/src/health/risk-coverage-scatter.tsx b/packages/ui/src/health/risk-coverage-scatter.tsx
index 2ece43952..ea4e5a07d 100644
--- a/packages/ui/src/health/risk-coverage-scatter.tsx
+++ b/packages/ui/src/health/risk-coverage-scatter.tsx
@@ -78,10 +78,10 @@ export function RiskCoverageScatter({
<div className="relative">
<svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} role="img" aria-label="Risk vs coverage scatter plot">
{/* Quadrant tinting */}
- <rect x={padL} y={padT} width={midX - padL} height={midY - padT} fill="currentColor" className="text-amber-500/5" />
- <rect x={midX} y={padT} width={W - padR - midX} height={midY - padT} fill="currentColor" className="text-emerald-500/5" />
- <rect x={padL} y={midY} width={midX - padL} height={H - padB - midY} fill="currentColor" className="text-red-500/8" />
- <rect x={midX} y={midY} width={W - padR - midX} height={H - padB - midY} fill="currentColor" className="text-yellow-500/5" />
+ <rect x={padL} y={padT} width={midX - padL} height={midY - padT} fill="currentColor" className="text-[var(--color-warning)]/5" />
+ <rect x={midX} y={padT} width={W - padR - midX} height={midY - padT} fill="currentColor" className="text-[var(--color-success)]/5" />
+ <rect x={padL} y={midY} width={midX - padL} height={H - padB - midY} fill="currentColor" className="text-[var(--color-error)]/8" />
+ <rect x={midX} y={midY} width={W - padR - midX} height={H - padB - midY} fill="currentColor" className="text-[var(--color-caution)]/5" />
{/* Axes */}
<line x1={padL} y1={padT} x2={padL} y2={H - padB} stroke="currentColor" strokeOpacity={0.2} />
@@ -122,7 +122,14 @@ export function RiskCoverageScatter({
const cx = xScale(p.line_coverage_pct ?? 0);
const cy = yScale(p.health_score);
const isHovered = hovered?.file_path === p.file_path;
- const fillCls = p.health_score < 4 ? "fill-red-500" : p.health_score < 7 ? "fill-amber-500" : "fill-emerald-500";
+ const fillCls =
+ p.health_score < 4
+ ? "fill-[var(--color-error)]"
+ : p.health_score < 6
+ ? "fill-[var(--color-warning)]"
+ : p.health_score < 8
+ ? "fill-[var(--color-caution)]"
+ : "fill-[var(--color-success)]";
return (
<circle
key={p.file_path}
diff --git a/packages/ui/src/health/score-breakdown.tsx b/packages/ui/src/health/score-breakdown.tsx
index b8940bda1..bf1259dfd 100644
--- a/packages/ui/src/health/score-breakdown.tsx
+++ b/packages/ui/src/health/score-breakdown.tsx
@@ -79,12 +79,12 @@ export function ScoreBreakdown({
</span>
<span className="tabular-nums text-[var(--color-text-tertiary)]">
−{c.applied_deduction.toFixed(2)} / cap −{cap.toFixed(1)}
- {c.capped ? <span className="ml-1 text-amber-500" title="Capped">(capped)</span> : null}
+ {c.capped ? <span className="ml-1 text-[var(--color-warning)]" title="Capped">(capped)</span> : null}
</span>
</div>
<div className="mt-1.5 h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-muted)]">
<div
- className="h-full bg-red-500/70"
+ className="h-full bg-[var(--color-error)]/70"
style={{ width: `${pct}%` }}
/>
</div>
@@ -108,7 +108,7 @@ export function ScoreBreakdown({
{f.function_name}
</span>
) : null}
- <span className="ml-auto tabular-nums text-red-500">
+ <span className="ml-auto tabular-nums text-[var(--color-error)]">
−{f.applied_impact.toFixed(2)}
</span>
</li>
diff --git a/packages/ui/src/health/tokens.ts b/packages/ui/src/health/tokens.ts
index 6759d04c9..7b8eb81b3 100644
--- a/packages/ui/src/health/tokens.ts
+++ b/packages/ui/src/health/tokens.ts
@@ -3,6 +3,8 @@
*
* Single source of truth so the score pill on a file row, the severity
* chip on a finding card, and the KPI card text colors all agree.
+ * All colors come from the semantic CSS tokens (--color-error/warning/
+ * caution/success) so the surface themes correctly in both modes.
*/
export type Severity = "critical" | "high" | "medium" | "low";
@@ -22,42 +24,89 @@ export const SEVERITY_LABEL: Record<Severity, string> = {
};
export const SEVERITY_CHIP: Record<Severity, string> = {
- critical: "bg-red-500/15 text-red-500 border border-red-500/30",
- high: "bg-amber-500/15 text-amber-500 border border-amber-500/30",
- medium: "bg-yellow-500/15 text-yellow-600 border border-yellow-500/30",
- low: "bg-zinc-500/15 text-zinc-500 border border-zinc-500/30",
+ critical:
+ "bg-[var(--color-error)]/15 text-[var(--color-error)] border border-[var(--color-error)]/30",
+ high: "bg-[var(--color-warning)]/15 text-[var(--color-warning)] border border-[var(--color-warning)]/30",
+ medium:
+ "bg-[var(--color-caution)]/15 text-[var(--color-caution)] border border-[var(--color-caution)]/30",
+ low: "bg-[var(--color-text-tertiary)]/15 text-[var(--color-text-tertiary)] border border-[var(--color-text-tertiary)]/30",
};
export const SEVERITY_BAR: Record<Severity, string> = {
- critical: "bg-red-500",
- high: "bg-amber-500",
- medium: "bg-yellow-500",
- low: "bg-zinc-500",
+ critical: "bg-[var(--color-error)]",
+ high: "bg-[var(--color-warning)]",
+ medium: "bg-[var(--color-caution)]",
+ low: "bg-[var(--color-text-tertiary)]",
+};
+
+/**
+ * The ONE score→band mapping. Every score color in the app derives from
+ * this: <4 critical, <6 poor, <8 fair, >=8 good.
+ */
+export type ScoreBand = "critical" | "poor" | "fair" | "good";
+
+export function scoreBand(score: number): ScoreBand {
+ if (score < 4) return "critical";
+ if (score < 6) return "poor";
+ if (score < 8) return "fair";
+ return "good";
+}
+
+export const SCORE_BAND_LABEL: Record<ScoreBand, string> = {
+ critical: "Critical",
+ poor: "Poor",
+ fair: "Fair",
+ good: "Good",
+};
+
+/* Literal class strings per band so Tailwind's static scanner sees them. */
+const BAND_TEXT: Record<ScoreBand, string> = {
+ critical: "text-[var(--color-error)]",
+ poor: "text-[var(--color-warning)]",
+ fair: "text-[var(--color-caution)]",
+ good: "text-[var(--color-success)]",
+};
+
+const BAND_BADGE: Record<ScoreBand, string> = {
+ critical:
+ "bg-[var(--color-error)]/15 text-[var(--color-error)] border border-[var(--color-error)]/30",
+ poor: "bg-[var(--color-warning)]/15 text-[var(--color-warning)] border border-[var(--color-warning)]/30",
+ fair: "bg-[var(--color-caution)]/15 text-[var(--color-caution)] border border-[var(--color-caution)]/30",
+ good: "bg-[var(--color-success)]/15 text-[var(--color-success)] border border-[var(--color-success)]/30",
+};
+
+const BAND_BADGE_SOFT: Record<ScoreBand, string> = {
+ critical: "bg-[var(--color-error)]/15 text-[var(--color-error)]",
+ poor: "bg-[var(--color-warning)]/15 text-[var(--color-warning)]",
+ fair: "bg-[var(--color-caution)]/15 text-[var(--color-caution)]",
+ good: "bg-[var(--color-success)]/15 text-[var(--color-success)]",
};
export function scoreTextColor(score: number | null | undefined): string {
if (score == null) return "text-[var(--color-text-primary)]";
- if (score < 4) return "text-red-500";
- if (score < 7) return "text-amber-500";
- return "text-emerald-500";
+ return BAND_TEXT[scoreBand(score)];
}
+/** Bordered score pill (file table, KPI badges). */
export function scoreBadgeClass(score: number): string {
- if (score < 4) return "bg-red-500/15 text-red-500 border border-red-500/30";
- if (score < 7) return "bg-amber-500/15 text-amber-500 border border-amber-500/30";
- return "bg-emerald-500/15 text-emerald-500 border border-emerald-500/30";
+ return BAND_BADGE[scoreBand(score)];
+}
+
+/** Borderless compact variant (inline HealthBadge next to file paths). */
+export function scoreSoftBadgeClass(score: number): string {
+ return BAND_BADGE_SOFT[scoreBand(score)];
}
export function coverageColor(pct: number): string {
- if (pct < 30) return "bg-red-500";
- if (pct < 60) return "bg-amber-500";
- if (pct < 80) return "bg-yellow-400";
- return "bg-emerald-500";
+ if (pct < 30) return "bg-[var(--color-error)]";
+ if (pct < 60) return "bg-[var(--color-warning)]";
+ if (pct < 80) return "bg-[var(--color-caution)]";
+ return "bg-[var(--color-success)]";
}
export function deltaColor(delta: number | null | undefined): string {
if (delta == null || delta === 0) return "text-[var(--color-text-tertiary)]";
- return delta > 0 ? "text-emerald-500" : "text-red-500";
+ return delta > 0 ? "text-[var(--color-success)]" : "text-[var(--color-error)]";
}
export function formatDelta(delta: number | null | undefined): string {
diff --git a/packages/ui/src/health/trend-chart.tsx b/packages/ui/src/health/trend-chart.tsx
index 6506c4430..be0304684 100644
--- a/packages/ui/src/health/trend-chart.tsx
+++ b/packages/ui/src/health/trend-chart.tsx
@@ -53,9 +53,9 @@ export function TrendChart({ history, height = 220 }: TrendChartProps) {
KPI trend
</h3>
<div className="flex items-center gap-3 text-[11px] text-[var(--color-text-tertiary)]">
- <Legend dot="bg-emerald-500" label="Average" />
- <Legend dot="bg-amber-500" label="Hotspot" />
- <Legend dot="bg-red-500" label="Worst" />
+ <Legend dot="bg-[var(--color-success)]" label="Average" />
+ <Legend dot="bg-[var(--color-warning)]" label="Hotspot" />
+ <Legend dot="bg-[var(--color-error)]" label="Worst" />
</div>
</div>
<svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} role="img" aria-label="Health KPI trend">
diff --git a/packages/ui/src/modules/module-health-detail.tsx b/packages/ui/src/modules/module-health-detail.tsx
index fb16bc5d2..682d99537 100644
--- a/packages/ui/src/modules/module-health-detail.tsx
+++ b/packages/ui/src/modules/module-health-detail.tsx
@@ -210,15 +210,20 @@ export function ModuleHealthDetailView({
</CardTitle>
</CardHeader>
<CardContent className="pt-0 space-y-1">
- {module.governing_decisions.map((id) => (
- <button
- key={id}
- onClick={() => onSelectDecision?.(id)}
- className="block w-full truncate rounded px-2 py-1 text-left text-[11px] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
- >
- {id.slice(0, 16)}…
- </button>
- ))}
+ {module.governing_decisions.map((d) => {
+ const id = typeof d === "string" ? d : d.id;
+ const label = typeof d === "string" ? `${d.slice(0, 16)}…` : d.title;
+ return (
+ <button
+ key={id}
+ onClick={() => onSelectDecision?.(id)}
+ title={typeof d === "string" ? undefined : `${d.title} (${d.status})`}
+ className="block w-full truncate rounded px-2 py-1 text-left text-[11px] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ >
+ {label}
+ </button>
+ );
+ })}
</CardContent>
</Card>
)}
diff --git a/packages/ui/src/owners/owner-profile.tsx b/packages/ui/src/owners/owner-profile.tsx
index 96253a269..6d26d0cb9 100644
--- a/packages/ui/src/owners/owner-profile.tsx
+++ b/packages/ui/src/owners/owner-profile.tsx
@@ -10,6 +10,7 @@ import {
Users,
Folder,
TrendingUp,
+ Bot,
} from "lucide-react";
import type {
OwnerProfile,
@@ -19,6 +20,11 @@ import type {
} from "@repowise-dev/types/owners";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { Badge } from "../ui/badge";
+import { EmptyState } from "../shared/empty-state";
+import {
+ ResponsiveTable,
+ type ResponsiveColumn,
+} from "../shared/responsive-table";
import { cn } from "../lib/cn";
import { truncatePath } from "../lib/format";
import { OwnerAvatar } from "./owner-avatar";
@@ -100,8 +106,13 @@ export function OwnerProfileView({
<div className="flex flex-wrap items-start gap-5">
<OwnerAvatar name={owner.name} email={owner.email} size="lg" />
<div className="flex-1 min-w-0">
- <h1 className="text-2xl font-bold text-[var(--color-text-primary)]">
+ <h1 className="flex flex-wrap items-center gap-2 text-2xl font-bold text-[var(--color-text-primary)]">
{owner.name}
+ {tenureDays !== null && tenureDays < 90 && (
+ <Badge variant="outline" className="text-[10px] font-medium">
+ new to this repo
+ </Badge>
+ )}
</h1>
{owner.email && (
<a
@@ -193,11 +204,18 @@ export function OwnerProfileView({
{owner.modules.slice(0, 12).map((m) => (
<ModuleRow key={m.module_path} mod={m} onClick={() => onSelectModule?.(m.module_path)} />
))}
- {owner.modules.length === 0 && (
- <p className="py-6 text-center text-xs text-[var(--color-text-tertiary)]">
- No module attribution yet.
+ {owner.modules.length > 12 && (
+ <p className="px-2 pt-1 text-[10px] text-[var(--color-text-tertiary)]">
+ +{owner.modules.length - 12} more modules not shown
</p>
)}
+ {owner.modules.length === 0 && (
+ <EmptyState
+ className="p-6"
+ title="No module attribution yet"
+ description="Module ownership appears after the next git sync."
+ />
+ )}
</CardContent>
</Card>
@@ -212,6 +230,12 @@ export function OwnerProfileView({
</CardHeader>
<CardContent className="pt-0">
<FileTable files={owner.top_files} onSelectFile={onSelectFile} />
+ {(owner.files_touched_total ?? 0) > Math.min(owner.top_files.length, 20) && (
+ <p className="pt-2 text-[10px] text-[var(--color-text-tertiary)]">
+ +{(owner.files_touched_total ?? 0) - Math.min(owner.top_files.length, 20)}{" "}
+ more files touched, not shown
+ </p>
+ )}
</CardContent>
</Card>
</div>
@@ -225,6 +249,16 @@ export function OwnerProfileView({
<p className="text-xs text-[var(--color-text-tertiary)]">
People who edit the same files. Strong overlap = natural reviewer.
</p>
+ {owner.co_authors.filter((c) => c.co_change_strength >= 0.3).length > 0 && (
+ <p className="text-[10px] text-[var(--color-text-secondary)]">
+ Would review well for this person&apos;s changes:{" "}
+ {owner.co_authors
+ .filter((c) => c.co_change_strength >= 0.3)
+ .slice(0, 2)
+ .map((c) => c.name)
+ .join(", ")}
+ </p>
+ )}
</CardHeader>
<CardContent className="pt-0 space-y-1.5">
{owner.co_authors.slice(0, 10).map((c) => (
@@ -251,14 +285,74 @@ export function OwnerProfileView({
</div>
</button>
))}
- {owner.co_authors.length === 0 && (
- <p className="py-4 text-center text-xs text-[var(--color-text-tertiary)]">
- No co-authors detected.
+ {(owner.co_authors_total ?? owner.co_authors.length) >
+ Math.min(owner.co_authors.length, 10) && (
+ <p className="px-2 pt-1 text-[10px] text-[var(--color-text-tertiary)]">
+ +
+ {(owner.co_authors_total ?? owner.co_authors.length) -
+ Math.min(owner.co_authors.length, 10)}{" "}
+ more co-authors not shown
</p>
)}
+ {owner.co_authors.length === 0 && (
+ <EmptyState
+ className="p-6"
+ title="No co-authors detected"
+ description="Nobody else edits the files this person owns."
+ />
+ )}
</CardContent>
</Card>
+ {owner.agent_collab && owner.agent_collab.agent_commit_count > 0 && (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm flex items-center gap-1.5">
+ <Bot className="h-4 w-4" /> Agent collaboration
+ </CardTitle>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Coding-agent activity on the files this person owns.
+ </p>
+ </CardHeader>
+ <CardContent className="pt-0 space-y-2 text-xs">
+ <div className="flex items-center justify-between">
+ <span className="text-[var(--color-text-secondary)]">
+ Agent-attributed commits
+ </span>
+ <span className="tabular-nums font-medium text-[var(--color-text-primary)]">
+ {owner.agent_collab.agent_commit_count}
+ {owner.agent_collab.agent_share_pct != null &&
+ ` (${Math.round(owner.agent_collab.agent_share_pct)}%)`}
+ </span>
+ </div>
+ <div className="flex items-center justify-between">
+ <span className="text-[var(--color-text-secondary)]">
+ Owned files with agent commits
+ </span>
+ <span className="tabular-nums font-medium text-[var(--color-text-primary)]">
+ {owner.agent_collab.files_with_agent_commits}
+ </span>
+ </div>
+ {Object.keys(owner.agent_collab.tier_counts).length > 0 && (
+ <div className="flex flex-wrap gap-1.5 pt-1">
+ {Object.entries(owner.agent_collab.tier_counts)
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([tier, n]) => (
+ <Badge key={tier} variant="outline" className="text-[10px]">
+ {tier === "1"
+ ? "autonomous"
+ : tier === "2"
+ ? "agent"
+ : "assisted"}
+ : {n}
+ </Badge>
+ ))}
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ )}
+
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm">Commit mix</CardTitle>
@@ -268,9 +362,11 @@ export function OwnerProfileView({
</CardHeader>
<CardContent className="pt-0">
{categories.length === 0 ? (
- <p className="py-4 text-center text-xs text-[var(--color-text-tertiary)]">
- No category data.
- </p>
+ <EmptyState
+ className="p-6"
+ title="No category data"
+ description="Commit classification runs during indexing."
+ />
) : (
<div className="space-y-2">
{categories.map(([cat, n]) => (
@@ -399,7 +495,7 @@ function ModuleRow({
<div
className={cn(
"h-full",
- share > 80 ? "bg-amber-500" : "bg-[var(--color-accent-primary)]",
+ share > 80 ? "bg-[var(--color-warning)]" : "bg-[var(--color-accent-primary)]",
)}
style={{ width: `${share}%` }}
/>
@@ -411,6 +507,54 @@ function ModuleRow({
);
}
+const FILE_COLUMNS: ResponsiveColumn<OwnerFileEntry>[] = [
+ {
+ key: "file_path",
+ header: "File",
+ priority: 1,
+ cellClassName: "max-w-[320px]",
+ render: (f) => (
+ <span className="flex items-center gap-1.5 truncate font-mono text-[11px] text-[var(--color-text-primary)]">
+ {f.is_hotspot && <Flame className="h-3 w-3 shrink-0 text-[var(--color-warning)]" />}
+ {truncatePath(f.file_path, 48)}
+ </span>
+ ),
+ },
+ {
+ key: "commit_count_90d",
+ header: "Commits / 90d",
+ mobileLabel: "Commits",
+ align: "right",
+ priority: 2,
+ cellClassName: "tabular-nums",
+ render: (f) => f.commit_count_90d,
+ },
+ {
+ key: "churn",
+ header: "Churn",
+ align: "right",
+ priority: 2,
+ cellClassName: "tabular-nums",
+ render: (f) => <ChurnPill value={f.churn_percentile} />,
+ },
+ {
+ key: "bus",
+ header: "Bus",
+ align: "right",
+ priority: 3,
+ cellClassName: "tabular-nums",
+ render: (f) => <BusBadge bf={f.bus_factor} />,
+ },
+ {
+ key: "touched",
+ header: "Touched",
+ align: "right",
+ priority: 3,
+ cellClassName: "text-[10px] text-[var(--color-text-tertiary)]",
+ render: (f) => timeAgo(f.last_commit_at),
+ },
+];
+
function FileTable({
files,
onSelectFile,
@@ -418,63 +562,32 @@ function FileTable({
files: OwnerFileEntry[];
onSelectFile?: ((path: string) => void) | undefined;
}) {
- if (files.length === 0) {
- return (
- <p className="py-4 text-center text-xs text-[var(--color-text-tertiary)]">
- No file attribution.
- </p>
- );
- }
return (
- <div className="overflow-x-auto">
- <table className="w-full text-xs">
- <thead className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
- <tr>
- <th className="py-1.5 px-2 text-left font-medium">File</th>
- <th className="py-1.5 px-2 text-right font-medium">Commits / 90d</th>
- <th className="py-1.5 px-2 text-right font-medium">Churn</th>
- <th className="py-1.5 px-2 text-right font-medium">Bus</th>
- <th className="py-1.5 px-2 text-right font-medium">Touched</th>
- </tr>
- </thead>
- <tbody>
- {files.slice(0, 20).map((f) => (
- <tr
- key={f.file_path}
- onClick={() => onSelectFile?.(f.file_path)}
- className={cn(
- "border-t border-[var(--color-border-default)]/40",
- onSelectFile && "cursor-pointer hover:bg-[var(--color-bg-elevated)]",
- )}
- >
- <td className="py-1.5 px-2 max-w-[320px]">
- <span className="flex items-center gap-1.5 truncate font-mono text-[11px] text-[var(--color-text-primary)]">
- {f.is_hotspot && <Flame className="h-3 w-3 shrink-0 text-orange-400" />}
- {truncatePath(f.file_path, 48)}
- </span>
- </td>
- <td className="py-1.5 px-2 text-right tabular-nums">{f.commit_count_90d}</td>
- <td className="py-1.5 px-2 text-right tabular-nums">
- <ChurnPill value={f.churn_percentile} />
- </td>
- <td className="py-1.5 px-2 text-right tabular-nums">
- <BusBadge bf={f.bus_factor} />
- </td>
- <td className="py-1.5 px-2 text-right text-[10px] text-[var(--color-text-tertiary)]">
- {timeAgo(f.last_commit_at)}
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
+ <ResponsiveTable
+ columns={FILE_COLUMNS}
+ rows={files.slice(0, 20)}
+ rowKey={(f) => f.file_path}
+ onRowClick={onSelectFile ? (f) => onSelectFile(f.file_path) : undefined}
+ bare
+ empty={
+ <EmptyState
+ className="p-6"
+ title="No file attribution"
+ description="File-level ownership appears after the next git sync."
+ />
+ }
+ />
);
}
function ChurnPill({ value }: { value: number }) {
const v = Math.round(value);
const color =
- v >= 80 ? "bg-red-500/20 text-red-300" : v >= 50 ? "bg-amber-500/20 text-amber-300" : "bg-[var(--color-bg-inset)] text-[var(--color-text-tertiary)]";
+ v >= 80
+ ? "bg-[var(--color-error)]/20 text-[var(--color-error)]"
+ : v >= 50
+ ? "bg-[var(--color-warning)]/20 text-[var(--color-warning)]"
+ : "bg-[var(--color-bg-inset)] text-[var(--color-text-tertiary)]";
return (
<span className={cn("inline-block rounded px-1.5 py-0.5 text-[10px] tabular-nums", color)}>
{v}
diff --git a/packages/ui/src/shared/adaptive-panel.tsx b/packages/ui/src/shared/adaptive-panel.tsx
new file mode 100644
index 000000000..255bbce9e
--- /dev/null
+++ b/packages/ui/src/shared/adaptive-panel.tsx
@@ -0,0 +1,144 @@
+"use client";
+
+import * as React from "react";
+import * as DialogPrimitive from "@radix-ui/react-dialog";
+import { X } from "lucide-react";
+import { cn } from "../lib/cn";
+
+/**
+ * AdaptivePanel — one overlay surface for entity context everywhere.
+ *
+ * Desktop (md+): right-side slide-in panel.
+ * Mobile: bottom sheet with a drag handle; swipe down past the threshold to
+ * dismiss.
+ *
+ * Header is optional — pass `title` for the standard header with a close
+ * button, or render your own header inside `children` and set
+ * `hideCloseButton`. A DialogTitle is always emitted for screen readers.
+ */
+export interface AdaptivePanelProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ /** Accessible name for the panel; rendered in the header unless `hideHeader`. */
+ title: React.ReactNode;
+ /** Small uppercase label rendered above the title (e.g. entity kind). */
+ eyebrow?: React.ReactNode | undefined;
+ children: React.ReactNode;
+ /** Desktop width classes. Default: `md:max-w-[520px]`. */
+ widthClassName?: string | undefined;
+ /** Mobile sheet max height. Default: `max-h-[85dvh]`. */
+ sheetHeightClassName?: string | undefined;
+ hideHeader?: boolean | undefined;
+ /**
+ * When false, the page stays interactive behind the panel on desktop
+ * (no focus trap, overlay only on mobile). Default true.
+ */
+ modal?: boolean | undefined;
+ className?: string | undefined;
+}
+
+const SWIPE_DISMISS_PX = 80;
+
+export function AdaptivePanel({
+ open,
+ onOpenChange,
+ title,
+ eyebrow,
+ children,
+ widthClassName = "md:max-w-[520px]",
+ sheetHeightClassName = "max-h-[85dvh]",
+ hideHeader,
+ modal = true,
+ className,
+}: AdaptivePanelProps) {
+ const contentRef = React.useRef<HTMLDivElement>(null);
+ const dragStartY = React.useRef<number | null>(null);
+
+ const onTouchStart = (e: React.TouchEvent) => {
+ dragStartY.current = e.touches[0]?.clientY ?? null;
+ };
+ const onTouchMove = (e: React.TouchEvent) => {
+ if (dragStartY.current == null || !contentRef.current) return;
+ const delta = (e.touches[0]?.clientY ?? 0) - dragStartY.current;
+ if (delta > 0) {
+ contentRef.current.style.transform = `translateY(${delta}px)`;
+ contentRef.current.style.transition = "none";
+ }
+ };
+ const onTouchEnd = (e: React.TouchEvent) => {
+ if (dragStartY.current == null || !contentRef.current) return;
+ const delta = (e.changedTouches[0]?.clientY ?? 0) - dragStartY.current;
+ contentRef.current.style.transform = "";
+ contentRef.current.style.transition = "";
+ dragStartY.current = null;
+ if (delta > SWIPE_DISMISS_PX) onOpenChange(false);
+ };
+
+ return (
+ <DialogPrimitive.Root open={open} onOpenChange={onOpenChange} modal={modal}>
+ <DialogPrimitive.Portal>
+ {modal ? (
+ <DialogPrimitive.Overlay className="fixed inset-0 z-[var(--z-modal)] bg-black/40 backdrop-blur-[1px] data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0" />
+ ) : (
+ open && (
+ <div
+ className="fixed inset-0 z-[var(--z-modal)] bg-black/40 backdrop-blur-[1px] md:hidden"
+ onClick={() => onOpenChange(false)}
+ aria-hidden
+ />
+ )
+ )}
+ <DialogPrimitive.Content
+ ref={contentRef}
+ aria-describedby={undefined}
+ className={cn(
+ "fixed z-[var(--z-modal)] flex flex-col bg-[var(--color-bg-surface)] shadow-2xl",
+ "data-[state=open]:animate-in data-[state=closed]:animate-out",
+ // Mobile: bottom sheet.
+ "inset-x-0 bottom-0 rounded-t-2xl border-t border-[var(--color-border-default)]",
+ "data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
+ sheetHeightClassName,
+ // Desktop: right panel.
+ "md:inset-y-0 md:bottom-auto md:left-auto md:right-0 md:h-full md:max-h-none md:w-full",
+ "md:rounded-none md:border-t-0 md:border-l",
+ "md:data-[state=closed]:slide-out-to-right md:data-[state=open]:slide-in-from-right",
+ widthClassName,
+ className,
+ )}
+ >
+ <div
+ className="flex justify-center py-2 md:hidden"
+ onTouchStart={onTouchStart}
+ onTouchMove={onTouchMove}
+ onTouchEnd={onTouchEnd}
+ >
+ <div className="h-1 w-10 rounded-full bg-[var(--color-border-hover)]" aria-hidden />
+ </div>
+ {hideHeader ? (
+ <DialogPrimitive.Title className="sr-only">{title}</DialogPrimitive.Title>
+ ) : (
+ <header className="flex items-start justify-between gap-3 border-b border-[var(--color-border-default)] px-4 pb-3 md:pt-3">
+ <div className="min-w-0">
+ {eyebrow && (
+ <p className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ {eyebrow}
+ </p>
+ )}
+ <DialogPrimitive.Title className="mt-0.5 break-all font-mono text-[12px] leading-snug text-[var(--color-text-primary)]">
+ {title}
+ </DialogPrimitive.Title>
+ </div>
+ <DialogPrimitive.Close
+ aria-label="Close panel"
+ className="shrink-0 rounded-md p-1.5 text-[var(--color-text-tertiary)] transition hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ >
+ <X className="h-4 w-4" />
+ </DialogPrimitive.Close>
+ </header>
+ )}
+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto">{children}</div>
+ </DialogPrimitive.Content>
+ </DialogPrimitive.Portal>
+ </DialogPrimitive.Root>
+ );
+}
diff --git a/packages/ui/src/shared/api-error.tsx b/packages/ui/src/shared/api-error.tsx
index 20beccf38..724a98146 100644
--- a/packages/ui/src/shared/api-error.tsx
+++ b/packages/ui/src/shared/api-error.tsx
@@ -14,8 +14,8 @@ export function ApiError({
}: ApiErrorProps) {
return (
<div className="flex flex-col items-center justify-center gap-3 py-12 text-center">
- <div className="flex h-10 w-10 items-center justify-center rounded-full bg-red-500/10">
- <AlertTriangle className="h-5 w-5 text-red-500" />
+ <div className="flex h-10 w-10 items-center justify-center rounded-full bg-[var(--color-error)]/10">
+ <AlertTriangle className="h-5 w-5 text-[var(--color-error)]" />
</div>
<div>
<p className="text-sm font-medium text-[var(--color-text-primary)]">{title}</p>
diff --git a/packages/ui/src/shared/context-drawer/drawer.tsx b/packages/ui/src/shared/context-drawer/drawer.tsx
index 682bfb23b..ba54e35d8 100644
--- a/packages/ui/src/shared/context-drawer/drawer.tsx
+++ b/packages/ui/src/shared/context-drawer/drawer.tsx
@@ -1,19 +1,18 @@
"use client";
import * as React from "react";
-import * as DialogPrimitive from "@radix-ui/react-dialog";
-import { X } from "lucide-react";
-import { cn } from "../../lib/cn";
+import { AdaptivePanel } from "../adaptive-panel";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../ui/tabs";
import { ENTITY_KIND_LABEL } from "../entity/routes";
import type { EntityRef } from "../entity/types";
import { useContextDrawer } from "./store";
/**
- * Right-side slide-in drawer that any EntityLink can open. Tab content is
- * provided by the host application as render functions — this keeps the
- * drawer in `packages/ui` (presentational) while letting `packages/web`
- * supply data fetching for each tab.
+ * Entity context drawer that any EntityLink can open: a right-side panel on
+ * desktop, a swipe-dismissable bottom sheet on mobile (via AdaptivePanel).
+ * Tab content is provided by the host application as render functions — this
+ * keeps the drawer in `packages/ui` (presentational) while letting
+ * `packages/web` supply data fetching for each tab.
*/
export type ContextDrawerTabId =
| "overview"
@@ -75,63 +74,36 @@ export function ContextDrawer({ tabs, defaultTab = "overview" }: ContextDrawerPr
}, [tabs]);
return (
- <DialogPrimitive.Root open={open} onOpenChange={(o) => (!o ? close() : undefined)}>
- <DialogPrimitive.Portal>
- <DialogPrimitive.Overlay className="fixed inset-0 z-40 bg-black/40 backdrop-blur-[1px] data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0" />
- <DialogPrimitive.Content
- className={cn(
- "fixed right-0 top-0 z-50 flex h-full w-full max-w-[520px] flex-col",
- "border-l border-[var(--color-border-default)] bg-[var(--color-bg-surface)] shadow-2xl",
- "data-[state=open]:animate-in data-[state=closed]:animate-out",
- "data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right",
- )}
- aria-describedby={undefined}
+ <AdaptivePanel
+ open={open}
+ onOpenChange={(o) => (!o ? close() : undefined)}
+ eyebrow={entity ? ENTITY_KIND_LABEL[entity.kind] : undefined}
+ title={entity ? entity.id : ""}
+ >
+ {entity && (
+ <Tabs
+ value={activeTab}
+ onValueChange={(v) => setActiveTab(v as ContextDrawerTabId)}
+ className="flex min-h-0 flex-1 flex-col"
>
- {entity && (
- <>
- <header className="flex items-start justify-between gap-3 border-b border-[var(--color-border-default)] px-4 py-3">
- <div className="min-w-0">
- <p className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
- {ENTITY_KIND_LABEL[entity.kind]}
- </p>
- <DialogPrimitive.Title className="mt-0.5 break-all font-mono text-[12px] leading-snug text-[var(--color-text-primary)]">
- {entity.id}
- </DialogPrimitive.Title>
- </div>
- <DialogPrimitive.Close
- aria-label="Close drawer"
- className="shrink-0 rounded-md p-1.5 text-[var(--color-text-tertiary)] transition hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
- >
- <X className="h-4 w-4" />
- </DialogPrimitive.Close>
- </header>
+ <TabsList className="flex-wrap gap-0.5 mx-3 mt-3 h-auto justify-start">
+ {orderedTabs.map((tab) => (
+ <TabsTrigger key={tab.id} value={tab.id} className="text-xs">
+ {tab.label}
+ </TabsTrigger>
+ ))}
+ </TabsList>
- <Tabs
- value={activeTab}
- onValueChange={(v) => setActiveTab(v as ContextDrawerTabId)}
- className="flex min-h-0 flex-1 flex-col"
- >
- <TabsList className="flex-wrap gap-0.5 mx-3 mt-3 h-auto justify-start">
- {orderedTabs.map((tab) => (
- <TabsTrigger key={tab.id} value={tab.id} className="text-xs">
- {tab.label}
- </TabsTrigger>
- ))}
- </TabsList>
-
- <div className="min-h-0 flex-1 overflow-y-auto px-4 py-3">
- {orderedTabs.map((tab) => (
- <TabsContent key={tab.id} value={tab.id} className="mt-0">
- {tab.render(entity)}
- </TabsContent>
- ))}
- </div>
- </Tabs>
- </>
- )}
- </DialogPrimitive.Content>
- </DialogPrimitive.Portal>
- </DialogPrimitive.Root>
+ <div className="min-h-0 flex-1 overflow-y-auto px-4 py-3">
+ {orderedTabs.map((tab) => (
+ <TabsContent key={tab.id} value={tab.id} className="mt-0">
+ {tab.render(entity)}
+ </TabsContent>
+ ))}
+ </div>
+ </Tabs>
+ )}
+ </AdaptivePanel>
);
}
diff --git a/packages/ui/src/shared/entity/index.ts b/packages/ui/src/shared/entity/index.ts
index 7a494a113..9c2f4add6 100644
--- a/packages/ui/src/shared/entity/index.ts
+++ b/packages/ui/src/shared/entity/index.ts
@@ -3,6 +3,9 @@ export { EntityHoverCard } from "./entity-hover-card";
export {
resolveEntityHref,
defaultEntityLabel,
+ encodeFilePath,
+ fileEntityPath,
+ symbolEntityPath,
ENTITY_KIND_LABEL,
} from "./routes";
export type {
diff --git a/packages/ui/src/shared/entity/routes.ts b/packages/ui/src/shared/entity/routes.ts
index d37d1b569..cd9ba5ddc 100644
--- a/packages/ui/src/shared/entity/routes.ts
+++ b/packages/ui/src/shared/entity/routes.ts
@@ -1,5 +1,20 @@
import type { EntityKind, EntityRef } from "./types";
+/** Encode a repo-relative file path for use inside a route, keeping slashes. */
+export function encodeFilePath(path: string): string {
+ return path.split("/").map(encodeURIComponent).join("/");
+}
+
+/** Canonical file entity page path (relative to the repo link prefix). */
+export function fileEntityPath(prefix: string, filePath: string): string {
+ return `${prefix}/files/${encodeFilePath(filePath)}`;
+}
+
+/** Canonical symbol entity page path (relative to the repo link prefix). */
+export function symbolEntityPath(prefix: string, symbolId: string): string {
+ return `${prefix}/symbols/${encodeURIComponent(symbolId)}`;
+}
+
/**
* Resolve the canonical href for an entity. Centralizing this here keeps every
* link consistent and makes the route map auditable in one place.
@@ -16,19 +31,18 @@ export function resolveEntityHref(ref: EntityRef): string {
switch (kind) {
case "file":
- return `/repos/${repoId}/wiki/${encodeURI(id)}`;
+ return fileEntityPath(`/repos/${repoId}`, id);
case "symbol":
- return `/repos/${repoId}/symbols?symbol=${encodeURIComponent(id)}`;
+ return symbolEntityPath(`/repos/${repoId}`, id);
case "decision":
return `/repos/${repoId}/decisions/${encodeURIComponent(id)}`;
case "owner":
- // No dedicated owner page yet — deep-link into the Risk page heatmap.
return repoId
- ? `/repos/${repoId}/risk?owner=${encodeURIComponent(id)}`
+ ? `/repos/${repoId}/owners/${encodeURIComponent(id)}`
: `#owner:${encodeURIComponent(id)}`;
case "commit":
return repoId
- ? `/repos/${repoId}/risk?commit=${encodeURIComponent(id)}`
+ ? `/repos/${repoId}/commits?commit=${encodeURIComponent(id)}`
: `#commit:${encodeURIComponent(id)}`;
}
}
diff --git a/packages/ui/src/shared/error-boundary.tsx b/packages/ui/src/shared/error-boundary.tsx
new file mode 100644
index 000000000..7ec08cebf
--- /dev/null
+++ b/packages/ui/src/shared/error-boundary.tsx
@@ -0,0 +1,51 @@
+"use client";
+
+import * as React from "react";
+import { ApiError } from "./api-error";
+
+/**
+ * ErrorBoundary — catches render errors in a subtree and shows a recoverable
+ * fallback instead of blanking the page. Default fallback is ApiError with a
+ * retry that re-mounts the subtree.
+ */
+export interface ErrorBoundaryProps {
+ children: React.ReactNode;
+ /** Custom fallback; receives the error and a reset callback. */
+ fallback?: ((error: Error, reset: () => void) => React.ReactNode) | undefined;
+ /** Forwarded to the default ApiError fallback. */
+ title?: string | undefined;
+ onError?: ((error: Error, info: React.ErrorInfo) => void) | undefined;
+}
+
+interface ErrorBoundaryState {
+ error: Error | null;
+}
+
+export class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
+ override state: ErrorBoundaryState = { error: null };
+
+ static getDerivedStateFromError(error: Error): ErrorBoundaryState {
+ return { error };
+ }
+
+ override componentDidCatch(error: Error, info: React.ErrorInfo) {
+ this.props.onError?.(error, info);
+ }
+
+ reset = () => this.setState({ error: null });
+
+ override render() {
+ const { error } = this.state;
+ if (error) {
+ if (this.props.fallback) return this.props.fallback(error, this.reset);
+ return (
+ <ApiError
+ title={this.props.title ?? "Something went wrong"}
+ message={error.message}
+ onRetry={this.reset}
+ />
+ );
+ }
+ return this.props.children;
+ }
+}
diff --git a/packages/ui/src/shared/index.ts b/packages/ui/src/shared/index.ts
index f564b0cb2..607f3977f 100644
--- a/packages/ui/src/shared/index.ts
+++ b/packages/ui/src/shared/index.ts
@@ -1,7 +1,20 @@
export * from "./api-error";
+export {
+ AdaptivePanel,
+ type AdaptivePanelProps,
+} from "./adaptive-panel";
export { BrandMark, type BrandMarkProps } from "./brand-mark";
+export { ErrorBoundary, type ErrorBoundaryProps } from "./error-boundary";
+export {
+ ResponsiveTable,
+ type ResponsiveColumn,
+ type ResponsiveTableProps,
+ type ColumnPriority,
+} from "./responsive-table";
+export { Toaster, toast, type ToasterProps } from "./toast";
export * from "./breadcrumb";
export * from "./empty-state";
+export { InfoTip, type InfoTipProps } from "./info-tip";
export { OwlLoader, type OwlLoaderProps } from "./owl-loader";
export * from "./stat-card";
export * from "./results-footer";
diff --git a/packages/ui/src/shared/info-tip.tsx b/packages/ui/src/shared/info-tip.tsx
new file mode 100644
index 000000000..523c33f13
--- /dev/null
+++ b/packages/ui/src/shared/info-tip.tsx
@@ -0,0 +1,48 @@
+"use client";
+
+import { Info } from "lucide-react";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "../ui/tooltip";
+import { cn } from "../lib/cn";
+
+export interface InfoTipProps {
+ /** Tooltip body — plain text or rich content. */
+ content: React.ReactNode;
+ /** Optional accessible label; defaults to "More info". */
+ label?: string;
+ className?: string;
+ side?: "top" | "right" | "bottom" | "left";
+}
+
+/**
+ * A small inline info icon with a hover/focus tooltip. Click also toggles it,
+ * so the explanation is reachable on touch devices where hover never fires.
+ */
+export function InfoTip({ content, label = "More info", className, side }: InfoTipProps) {
+ return (
+ <TooltipProvider delayDuration={150}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ aria-label={label}
+ onClick={(e) => e.stopPropagation()}
+ className={cn(
+ "inline-flex shrink-0 items-center text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] rounded-sm",
+ className,
+ )}
+ >
+ <Info className="h-3 w-3" aria-hidden="true" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side={side ?? "top"} className="max-w-[280px] whitespace-normal">
+ {content}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+}
diff --git a/packages/ui/src/shared/responsive-table/index.ts b/packages/ui/src/shared/responsive-table/index.ts
new file mode 100644
index 000000000..12cffb1f0
--- /dev/null
+++ b/packages/ui/src/shared/responsive-table/index.ts
@@ -0,0 +1,6 @@
+export {
+ ResponsiveTable,
+ type ResponsiveColumn,
+ type ResponsiveTableProps,
+ type ColumnPriority,
+} from "./responsive-table";
diff --git a/packages/ui/src/shared/responsive-table/responsive-table.tsx b/packages/ui/src/shared/responsive-table/responsive-table.tsx
new file mode 100644
index 000000000..ee59bd3fe
--- /dev/null
+++ b/packages/ui/src/shared/responsive-table/responsive-table.tsx
@@ -0,0 +1,225 @@
+"use client";
+
+import * as React from "react";
+import { ArrowDown, ArrowUp } from "lucide-react";
+import { cn } from "../../lib/cn";
+
+/**
+ * ResponsiveTable — shared table primitive with a column-priority API.
+ *
+ * Every column declares a `priority`:
+ * 1 — always visible (identity / primary metric columns)
+ * 2 — hidden below `md` (768px)
+ * 3 — hidden below `lg` (1024px)
+ *
+ * The wrapper always provides `overflow-x-auto` as a fallback so nothing is
+ * ever clipped. With `stacked`, the table additionally collapses to a
+ * stacked card list below the given breakpoint: the first priority-1 column
+ * renders as the card title and the remaining columns render as label/value
+ * rows (via `mobileRender` when provided, else `render`).
+ *
+ * Purely presentational: rows in, callbacks out. No routing, no data fetching.
+ */
+
+export type ColumnPriority = 1 | 2 | 3;
+
+export interface ResponsiveColumn<T> {
+ /** Stable identifier; doubles as the sort key passed to `onSort`. */
+ key: string;
+ header: React.ReactNode;
+ /** Short label used in stacked-card mode; falls back to `header` when it is a string. */
+ mobileLabel?: string | undefined;
+ align?: "left" | "right" | "center" | undefined;
+ priority?: ColumnPriority | undefined;
+ sortable?: boolean | undefined;
+ headerClassName?: string | undefined;
+ cellClassName?: string | undefined;
+ render: (row: T) => React.ReactNode;
+ /** Override rendering inside stacked cards (e.g. drop icons, shorten text). */
+ mobileRender?: ((row: T) => React.ReactNode) | undefined;
+ /** Skip this column entirely in stacked-card mode. */
+ hideInCard?: boolean | undefined;
+}
+
+export interface ResponsiveTableProps<T> {
+ columns: ResponsiveColumn<T>[];
+ rows: T[];
+ rowKey: (row: T) => string;
+ onRowClick?: ((row: T) => void) | undefined;
+ selectedKey?: string | null | undefined;
+ sortField?: string | undefined;
+ sortOrder?: "asc" | "desc" | undefined;
+ onSort?: ((key: string) => void) | undefined;
+ /** Rendered instead of the table when `rows` is empty (use EmptyState). */
+ empty?: React.ReactNode | undefined;
+ /** Collapse to stacked cards below this breakpoint. Default: no collapse. */
+ stacked?: "sm" | "md" | undefined;
+ /** Extra classes on the outer wrapper. */
+ className?: string | undefined;
+ /** Omit the default rounded border + surface background. */
+ bare?: boolean | undefined;
+}
+
+const PRIORITY_CELL_CLS: Record<ColumnPriority, string> = {
+ 1: "",
+ 2: "max-md:hidden",
+ 3: "max-lg:hidden",
+};
+
+const STACKED_TABLE_CLS: Record<NonNullable<ResponsiveTableProps<unknown>["stacked"]>, string> = {
+ sm: "max-sm:hidden",
+ md: "max-md:hidden",
+};
+
+const STACKED_CARDS_CLS: Record<NonNullable<ResponsiveTableProps<unknown>["stacked"]>, string> = {
+ sm: "sm:hidden",
+ md: "md:hidden",
+};
+
+function alignCls(align?: "left" | "right" | "center"): string {
+ return align === "right" ? "text-right" : align === "center" ? "text-center" : "text-left";
+}
+
+export function ResponsiveTable<T>({
+ columns,
+ rows,
+ rowKey,
+ onRowClick,
+ selectedKey,
+ sortField,
+ sortOrder = "desc",
+ onSort,
+ empty,
+ stacked,
+ className,
+ bare,
+}: ResponsiveTableProps<T>) {
+ if (rows.length === 0 && empty) {
+ return <>{empty}</>;
+ }
+
+ const table = (
+ <div className={cn("overflow-x-auto", stacked && STACKED_TABLE_CLS[stacked])}>
+ <table className="w-full text-sm">
+ <thead className="bg-[var(--color-bg-elevated)] text-[var(--color-text-tertiary)] text-xs uppercase tracking-wider sticky top-0 z-10">
+ <tr>
+ {columns.map((c) => {
+ const isActive = c.sortable && c.key === sortField;
+ return (
+ <th
+ key={c.key}
+ className={cn(
+ "px-3 py-2 font-medium whitespace-nowrap",
+ alignCls(c.align),
+ PRIORITY_CELL_CLS[c.priority ?? 1],
+ c.sortable && onSort && "cursor-pointer select-none",
+ c.headerClassName,
+ )}
+ onClick={c.sortable && onSort ? () => onSort(c.key) : undefined}
+ aria-sort={
+ isActive ? (sortOrder === "asc" ? "ascending" : "descending") : undefined
+ }
+ >
+ <span className="inline-flex items-center gap-1">
+ {c.header}
+ {isActive ? (
+ sortOrder === "asc" ? (
+ <ArrowUp className="h-3 w-3" />
+ ) : (
+ <ArrowDown className="h-3 w-3" />
+ )
+ ) : null}
+ </span>
+ </th>
+ );
+ })}
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map((row) => {
+ const key = rowKey(row);
+ const isSelected = selectedKey != null && selectedKey === key;
+ return (
+ <tr
+ key={key}
+ className={cn(
+ "border-t border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)]",
+ isSelected && "bg-[var(--color-accent-muted)]/30",
+ onRowClick && "cursor-pointer",
+ )}
+ onClick={onRowClick ? () => onRowClick(row) : undefined}
+ >
+ {columns.map((c) => (
+ <td
+ key={c.key}
+ className={cn(
+ "px-3 py-2",
+ alignCls(c.align),
+ PRIORITY_CELL_CLS[c.priority ?? 1],
+ c.cellClassName,
+ )}
+ >
+ {c.render(row)}
+ </td>
+ ))}
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ );
+
+ const cards = stacked ? (
+ <ul className={cn("divide-y divide-[var(--color-border-default)]", STACKED_CARDS_CLS[stacked])}>
+ {rows.map((row) => {
+ const key = rowKey(row);
+ const isSelected = selectedKey != null && selectedKey === key;
+ const [titleCol, ...rest] = columns.filter((c) => !c.hideInCard);
+ if (!titleCol) return null;
+ return (
+ <li
+ key={key}
+ className={cn(
+ "px-3 py-2.5",
+ isSelected && "bg-[var(--color-accent-muted)]/30",
+ onRowClick && "cursor-pointer hover:bg-[var(--color-bg-elevated)]",
+ )}
+ onClick={onRowClick ? () => onRowClick(row) : undefined}
+ >
+ <div className="text-sm text-[var(--color-text-primary)]">
+ {(titleCol.mobileRender ?? titleCol.render)(row)}
+ </div>
+ <dl className="mt-1.5 flex flex-wrap gap-x-4 gap-y-1">
+ {rest.map((c) => {
+ const value = (c.mobileRender ?? c.render)(row);
+ if (value == null || value === "") return null;
+ return (
+ <div key={c.key} className="flex items-baseline gap-1.5 text-xs">
+ <dt className="text-[var(--color-text-tertiary)]">
+ {c.mobileLabel ?? (typeof c.header === "string" ? c.header : c.key)}
+ </dt>
+ <dd className="text-[var(--color-text-secondary)] tabular-nums">{value}</dd>
+ </div>
+ );
+ })}
+ </dl>
+ </li>
+ );
+ })}
+ </ul>
+ ) : null;
+
+ return (
+ <div
+ className={cn(
+ !bare &&
+ "rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]",
+ className,
+ )}
+ >
+ {table}
+ {cards}
+ </div>
+ );
+}
diff --git a/packages/ui/src/shared/toast.tsx b/packages/ui/src/shared/toast.tsx
new file mode 100644
index 000000000..1ace21d28
--- /dev/null
+++ b/packages/ui/src/shared/toast.tsx
@@ -0,0 +1,32 @@
+"use client";
+
+import { Toaster as SonnerToaster, toast } from "sonner";
+
+/**
+ * Token-themed sonner toaster. Framework-neutral: the host app passes the
+ * resolved theme (e.g. from next-themes) instead of this component reading it.
+ * Mount once at the app shell level; fire toasts via the re-exported `toast`.
+ */
+export interface ToasterProps {
+ theme?: "light" | "dark" | undefined;
+ position?: React.ComponentProps<typeof SonnerToaster>["position"] | undefined;
+}
+
+export function Toaster({ theme = "dark", position = "bottom-right" }: ToasterProps) {
+ return (
+ <SonnerToaster
+ theme={theme}
+ position={position}
+ style={{ zIndex: "var(--z-toast)" } as React.CSSProperties}
+ toastOptions={{
+ style: {
+ background: "var(--color-bg-elevated)",
+ border: "1px solid var(--color-border-default)",
+ color: "var(--color-text-primary)",
+ },
+ }}
+ />
+ );
+}
+
+export { toast };
diff --git a/packages/ui/src/symbols/index.ts b/packages/ui/src/symbols/index.ts
index a8f88e640..e17469f33 100644
--- a/packages/ui/src/symbols/index.ts
+++ b/packages/ui/src/symbols/index.ts
@@ -1,3 +1,4 @@
+export * from "./symbol-page";
export * from "./symbol-table";
export * from "./symbol-drawer";
export * from "./symbol-graph-panel";
diff --git a/packages/ui/src/symbols/symbol-page.tsx b/packages/ui/src/symbols/symbol-page.tsx
new file mode 100644
index 000000000..54dbedd81
--- /dev/null
+++ b/packages/ui/src/symbols/symbol-page.tsx
@@ -0,0 +1,259 @@
+import { ArrowDownLeft, ArrowUpRight, Flame } from "lucide-react";
+import { Badge } from "../ui/badge";
+import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
+import { scoreBadgeClass } from "../health/tokens";
+import { fileEntityPath, symbolEntityPath } from "../shared/entity/routes";
+import { truncatePath } from "../lib/format";
+import type { SymbolCallEntry, SymbolDetailResponse } from "@repowise-dev/types/symbols";
+
+export interface SymbolPageProps {
+ data: SymbolDetailResponse;
+ repoId: string;
+ linkPrefix?: string;
+}
+
+function ageDays(medianAuthorTime: number | null | undefined): number | null {
+ if (!medianAuthorTime) return null;
+ return Math.max(0, Math.round((Date.now() / 1000 - medianAuthorTime) / 86400));
+}
+
+function CallList({
+ title,
+ icon,
+ entries,
+ symbolHref,
+}: {
+ title: string;
+ icon: React.ReactNode;
+ entries: SymbolCallEntry[];
+ symbolHref: (id: string) => string;
+}) {
+ return (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium flex items-center gap-2">
+ {icon}
+ {title}
+ <span className="text-[10px] font-normal text-[var(--color-text-tertiary)] tabular-nums">
+ {entries.length}
+ </span>
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ {entries.length === 0 ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">None in the indexed graph.</p>
+ ) : (
+ <ul className="space-y-1">
+ {entries.map((e) => (
+ <li key={`${e.symbol_id}-${e.edge_type}`}>
+ <a
+ href={symbolHref(e.symbol_id)}
+ className="flex items-center gap-2 -mx-2 px-2 py-0.5 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"
+ >
+ <span className="text-[11px] font-mono text-[var(--color-text-primary)] truncate">
+ {e.name}
+ </span>
+ <span className="text-[10px] text-[var(--color-text-tertiary)] truncate flex-1 min-w-0">
+ {truncatePath(e.file, 36)}
+ </span>
+ <span className="text-[10px] text-[var(--color-text-tertiary)] shrink-0">
+ {e.edge_type}
+ </span>
+ </a>
+ </li>
+ ))}
+ </ul>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
+
+/**
+ * The canonical symbol page: signature + docstring, function blame (churn,
+ * age, owner), callers/callees linking to sibling symbol pages, governing
+ * decisions, and the parent-file context. Purely presentational.
+ */
+export function SymbolPage({ data, repoId, linkPrefix }: SymbolPageProps) {
+ const prefix = linkPrefix ?? `/repos/${repoId}`;
+ const s = data.symbol;
+ const symbolHref = (id: string) => symbolEntityPath(prefix, id);
+ const fileHref = fileEntityPath(prefix, data.file_context.file_path);
+ const age = ageDays(s.blame_median_author_time);
+
+ return (
+ <div className="space-y-4">
+ {/* ── Header ── */}
+ <div className="space-y-2">
+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">
+ <h1 className="font-mono text-lg text-[var(--color-text-primary)] break-all">
+ {s.name}
+ </h1>
+ <Badge variant="outline" className="text-[10px] h-5">
+ {s.kind}
+ </Badge>
+ {s.is_async && (
+ <Badge variant="outline" className="text-[10px] h-5">
+ async
+ </Badge>
+ )}
+ <Badge variant="outline" className="text-[10px] h-5 capitalize">
+ {s.visibility}
+ </Badge>
+ {s.file_is_hotspot && (
+ <Badge variant="outline" className="text-[10px] h-5 text-[var(--color-error)] border-[var(--color-error)]/30">
+ <Flame className="h-2.5 w-2.5" /> hot file
+ </Badge>
+ )}
+ </div>
+ <a
+ href={fileHref}
+ className="inline-block text-xs font-mono text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:underline break-all"
+ >
+ {s.file_path}:{s.start_line}
+ </a>
+ {data.governing_decisions.length > 0 && (
+ <div className="flex flex-wrap items-center gap-1.5">
+ <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ Governed by
+ </span>
+ {data.governing_decisions.map((d) => (
+ <a
+ key={d.id}
+ href={`${prefix}/decisions/${d.id}`}
+ className="rounded border border-[var(--color-border-default)] px-1.5 py-0.5 text-[11px] text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:border-[var(--color-accent-primary)] transition-colors"
+ >
+ {d.title}
+ </a>
+ ))}
+ </div>
+ )}
+ </div>
+
+ {/* ── Signature + docstring ── */}
+ {s.signature && (
+ <pre className="overflow-x-auto rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-3 text-xs font-mono text-[var(--color-text-primary)]">
+ {s.signature}
+ </pre>
+ )}
+ {s.docstring && (
+ <p className="text-xs text-[var(--color-text-secondary)] whitespace-pre-wrap leading-relaxed">
+ {s.docstring}
+ </p>
+ )}
+
+ {/* ── Signals strip ── */}
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4 lg:grid-cols-6">
+ <Stat
+ label="Importance"
+ value={s.importance_score != null ? s.importance_score.toFixed(3) : "—"}
+ />
+ <Stat label="Complexity" value={String(s.complexity_estimate)} />
+ <Stat label="Callers" value={String(data.graph.in_degree)} />
+ <Stat label="Callees" value={String(data.graph.out_degree)} />
+ <Stat
+ label="Modifications"
+ value={s.blame_mod_count != null ? String(s.blame_mod_count) : "—"}
+ hint={
+ s.blame_recent_mod_count != null
+ ? `${s.blame_recent_mod_count} recent`
+ : undefined
+ }
+ />
+ <Stat label="Median age" value={age != null ? `${age}d` : "—"} />
+ </div>
+
+ {(s.blame_owner_name || data.file_context.primary_owner) && (
+ <p className="text-xs text-[var(--color-text-secondary)]">
+ {s.blame_owner_name ? (
+ <>
+ Blame owner{" "}
+ <a
+ href={`${prefix}/owners/${encodeURIComponent(s.blame_owner_name)}`}
+ className="font-medium hover:text-[var(--color-accent-primary)] hover:underline"
+ >
+ {s.blame_owner_name}
+ </a>
+ {s.blame_owner_line_pct != null &&
+ ` (${Math.round(s.blame_owner_line_pct * 100)}% of lines)`}
+ </>
+ ) : (
+ <>
+ File owner{" "}
+ <a
+ href={`${prefix}/owners/${encodeURIComponent(data.file_context.primary_owner!)}`}
+ className="font-medium hover:text-[var(--color-accent-primary)] hover:underline"
+ >
+ {data.file_context.primary_owner}
+ </a>
+ </>
+ )}
+ </p>
+ )}
+
+ {/* ── Callers / callees ── */}
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
+ <CallList
+ title="Callers"
+ icon={<ArrowDownLeft className="h-4 w-4 text-[var(--color-text-secondary)]" />}
+ entries={data.graph.callers}
+ symbolHref={symbolHref}
+ />
+ <CallList
+ title="Callees"
+ icon={<ArrowUpRight className="h-4 w-4 text-[var(--color-text-secondary)]" />}
+ entries={data.graph.callees}
+ symbolHref={symbolHref}
+ />
+ </div>
+
+ {/* ── Parent file context ── */}
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">Parent file</CardTitle>
+ </CardHeader>
+ <CardContent className="flex flex-wrap items-center gap-3">
+ <a
+ href={fileHref}
+ className="text-xs font-mono text-[var(--color-accent-primary)] hover:underline break-all"
+ >
+ {data.file_context.file_path}
+ </a>
+ {data.file_context.health_score != null && (
+ <span
+ className={`inline-flex items-baseline rounded px-1.5 py-0.5 text-xs font-bold tabular-nums ${scoreBadgeClass(data.file_context.health_score)}`}
+ >
+ {data.file_context.health_score.toFixed(1)}
+ <span className="ml-0.5 text-[9px] font-normal opacity-70">/10</span>
+ </span>
+ )}
+ {data.file_context.language && (
+ <Badge variant="outline" className="text-[10px] h-5 capitalize">
+ {data.file_context.language}
+ </Badge>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
+
+function Stat({
+ label,
+ value,
+ hint,
+}: {
+ label: string;
+ value: string;
+ hint?: string | undefined;
+}) {
+ return (
+ <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-2.5">
+ <p className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)] mb-0.5">
+ {label}
+ </p>
+ <p className="text-sm font-semibold tabular-nums text-[var(--color-text-primary)]">{value}</p>
+ {hint && <p className="text-[10px] text-[var(--color-text-tertiary)]">{hint}</p>}
+ </div>
+ );
+}
diff --git a/packages/ui/src/symbols/symbol-table.tsx b/packages/ui/src/symbols/symbol-table.tsx
index 498709176..31f01abd2 100644
--- a/packages/ui/src/symbols/symbol-table.tsx
+++ b/packages/ui/src/symbols/symbol-table.tsx
@@ -359,7 +359,7 @@ export function SymbolTable({
{
icon: GitBranch,
label: "Graph",
- href: `${prefix}/graph?node=${encodeURIComponent(sym.file_path)}`,
+ href: `${prefix}/architecture?view=graph&node=${encodeURIComponent(sym.file_path)}`,
},
{
icon: BookOpen,
diff --git a/packages/ui/src/ui/tabs.tsx b/packages/ui/src/ui/tabs.tsx
index fa813f06c..f67195985 100644
--- a/packages/ui/src/ui/tabs.tsx
+++ b/packages/ui/src/ui/tabs.tsx
@@ -36,6 +36,25 @@ const TabsTrigger = React.forwardRef<
));
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
+/**
+ * A TabsList that scrolls horizontally instead of wrapping when the triggers
+ * overflow — the shared small-width pattern for sections with many tabs.
+ * Drop-in replacement for ``TabsList``.
+ */
+const ScrollableTabsList = React.forwardRef<
+ React.ElementRef<typeof TabsPrimitive.List>,
+ React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
+>(({ className, ...props }, ref) => (
+ <div className="overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden -mx-1 px-1">
+ <TabsList
+ ref={ref}
+ className={cn("w-max min-w-full justify-start", className)}
+ {...props}
+ />
+ </div>
+));
+ScrollableTabsList.displayName = "ScrollableTabsList";
+
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
@@ -51,4 +70,4 @@ const TabsContent = React.forwardRef<
));
TabsContent.displayName = TabsPrimitive.Content.displayName;
-export { Tabs, TabsList, TabsTrigger, TabsContent };
+export { Tabs, TabsList, ScrollableTabsList, TabsTrigger, TabsContent };
diff --git a/packages/ui/src/wiki/backlinks-panel.tsx b/packages/ui/src/wiki/backlinks-panel.tsx
index 3aa89c895..47741e3bd 100644
--- a/packages/ui/src/wiki/backlinks-panel.tsx
+++ b/packages/ui/src/wiki/backlinks-panel.tsx
@@ -6,7 +6,7 @@
* (graceful fallback for pages generated before interlinking shipped).
*/
-import Link from "next/link";
+import * as React from "react";
import { getPageTypeIcon, getPageTypeLabel } from "../lib/page-types";
import type { Backlink } from "./wiki-links-types";
@@ -19,6 +19,17 @@ export interface BacklinksPanelProps {
limit?: number;
/** Optional URL builder; defaults to ``/repos/{repoId}/wiki/{pageId}``. */
buildHref?: (repoId: string, pageId: string) => string;
+ /**
+ * Render-prop for the link element so the host can plug Next's `<Link>`
+ * (or any router link) without dragging a framework dep into ui/.
+ * Defaults to a plain `<a>`.
+ */
+ renderLink?: (props: {
+ href: string;
+ className: string;
+ title: string;
+ children: React.ReactNode;
+ }) => React.ReactNode;
}
const DEFAULT_LIMIT = 6;
@@ -29,11 +40,15 @@ function defaultHref(repoId: string, pageId: string): string {
return `/repos/${repoId}/wiki/${encodeURIComponent(pageId)}`;
}
+const LINK_CLASS =
+ "flex items-start gap-1.5 text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] transition-colors";
+
export function BacklinksPanel({
backlinks,
repoId,
limit = DEFAULT_LIMIT,
buildHref = defaultHref,
+ renderLink,
}: BacklinksPanelProps) {
if (!backlinks || backlinks.length === 0) {
return null;
@@ -50,18 +65,25 @@ export function BacklinksPanel({
<ul className="space-y-1.5">
{visible.map((bl) => {
const Icon = getPageTypeIcon(bl.source_page_type);
+ const href = buildHref(repoId, bl.source_page_id);
+ const title = getPageTypeLabel(bl.source_page_type);
+ const children = (
+ <>
+ <Icon className="h-3 w-3 mt-0.5 shrink-0 text-[var(--color-text-tertiary)]" />
+ <span className="truncate" title={bl.source_title}>
+ {bl.source_title}
+ </span>
+ </>
+ );
return (
<li key={bl.source_page_id} className="text-xs">
- <Link
- href={buildHref(repoId, bl.source_page_id)}
- className="flex items-start gap-1.5 text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] transition-colors"
- title={getPageTypeLabel(bl.source_page_type)}
- >
- <Icon className="h-3 w-3 mt-0.5 shrink-0 text-[var(--color-text-tertiary)]" />
- <span className="truncate" title={bl.source_title}>
- {bl.source_title}
- </span>
- </Link>
+ {renderLink ? (
+ renderLink({ href, className: LINK_CLASS, title, children })
+ ) : (
+ <a href={href} className={LINK_CLASS} title={title}>
+ {children}
+ </a>
+ )}
</li>
);
})}
diff --git a/packages/ui/src/workspace/co-change-table.tsx b/packages/ui/src/workspace/co-change-table.tsx
index de899b732..b4db9184b 100644
--- a/packages/ui/src/workspace/co-change-table.tsx
+++ b/packages/ui/src/workspace/co-change-table.tsx
@@ -1,6 +1,11 @@
"use client";
import { Badge } from "../ui/badge";
+import { EmptyState } from "../shared/empty-state";
+import {
+ ResponsiveTable,
+ type ResponsiveColumn,
+} from "../shared/responsive-table";
import type { WorkspaceCoChangeEntry } from "@repowise-dev/types/workspace";
interface CoChangeTableProps {
@@ -9,72 +14,92 @@ interface CoChangeTableProps {
}
export function CoChangeTable({ coChanges, compact }: CoChangeTableProps) {
- if (coChanges.length === 0) {
- return (
- <p className="text-sm text-[var(--color-text-tertiary)] py-4 text-center">
- No cross-repo co-changes detected.
- </p>
- );
- }
+ const columns: ResponsiveColumn<WorkspaceCoChangeEntry>[] = [
+ {
+ key: "source",
+ header: "Source",
+ priority: 1,
+ cellClassName: "min-w-[160px] max-w-[280px]",
+ render: (cc) => (
+ <div className="flex flex-col gap-0.5">
+ <Badge variant="default" className="w-fit text-[11px]">{cc.source_repo}</Badge>
+ <span className="text-xs font-mono text-[var(--color-text-secondary)] truncate block" title={cc.source_file}>
+ {cc.source_file}
+ </span>
+ </div>
+ ),
+ },
+ {
+ key: "target",
+ header: "Target",
+ priority: 1,
+ cellClassName: "min-w-[160px] max-w-[280px]",
+ render: (cc) => (
+ <div className="flex flex-col gap-0.5">
+ <Badge variant="default" className="w-fit text-[11px]">{cc.target_repo}</Badge>
+ <span className="text-xs font-mono text-[var(--color-text-secondary)] truncate block" title={cc.target_file}>
+ {cc.target_file}
+ </span>
+ </div>
+ ),
+ },
+ {
+ key: "strength",
+ header: "Strength",
+ priority: 2,
+ headerClassName: "w-32",
+ render: (cc) => (
+ <div className="flex items-center gap-2 min-w-[90px]">
+ <div className="h-1.5 flex-1 rounded-full bg-[var(--color-bg-inset)] overflow-hidden">
+ <div
+ className="h-full rounded-full bg-[var(--color-accent-primary)] transition-all"
+ style={{ width: `${Math.min(Math.round(cc.strength * 10), 100)}%` }}
+ />
+ </div>
+ <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums w-8 text-right">
+ {Math.round(cc.strength * 10) / 10}
+ </span>
+ </div>
+ ),
+ mobileRender: (cc) => Math.round(cc.strength * 10) / 10,
+ },
+ ...(compact
+ ? []
+ : ([
+ {
+ key: "frequency",
+ header: "Freq",
+ align: "right",
+ priority: 3,
+ cellClassName: "text-xs text-[var(--color-text-secondary)] tabular-nums",
+ render: (cc) => `${cc.frequency}x`,
+ },
+ {
+ key: "last",
+ header: "Last",
+ priority: 3,
+ cellClassName: "text-xs text-[var(--color-text-tertiary)]",
+ render: (cc) => (
+ <span title={cc.last_date ? new Date(cc.last_date).toLocaleString() : undefined}>
+ {cc.last_date ? new Date(cc.last_date).toLocaleDateString() : "—"}
+ </span>
+ ),
+ },
+ ] satisfies ResponsiveColumn<WorkspaceCoChangeEntry>[])),
+ ];
return (
- <div className="overflow-x-auto">
- <table className="w-full text-sm">
- <thead>
- <tr className="border-b border-[var(--color-border-default)] text-left text-xs text-[var(--color-text-tertiary)]">
- <th className="pb-2 pr-4 font-medium">Source</th>
- <th className="pb-2 pr-4 font-medium">Target</th>
- <th className="pb-2 pr-4 font-medium w-32">Strength</th>
- {!compact && <th className="pb-2 pr-4 font-medium">Freq</th>}
- {!compact && <th className="pb-2 font-medium">Last</th>}
- </tr>
- </thead>
- <tbody className="divide-y divide-[var(--color-border-default)]">
- {coChanges.map((cc) => (
- <tr key={`${cc.source_repo}|${cc.source_file}|${cc.target_repo}|${cc.target_file}`} className="hover:bg-[var(--color-bg-elevated)] transition-colors">
- <td className="py-2 pr-4 min-w-[160px] max-w-[280px]">
- <div className="flex flex-col gap-0.5">
- <Badge variant="default" className="w-fit text-[11px]">{cc.source_repo}</Badge>
- <span className="text-xs font-mono text-[var(--color-text-secondary)] truncate block" title={cc.source_file}>
- {cc.source_file}
- </span>
- </div>
- </td>
- <td className="py-2 pr-4 min-w-[160px] max-w-[280px]">
- <div className="flex flex-col gap-0.5">
- <Badge variant="default" className="w-fit text-[11px]">{cc.target_repo}</Badge>
- <span className="text-xs font-mono text-[var(--color-text-secondary)] truncate block" title={cc.target_file}>
- {cc.target_file}
- </span>
- </div>
- </td>
- <td className="py-2 pr-4">
- <div className="flex items-center gap-2">
- <div className="h-1.5 flex-1 rounded-full bg-[var(--color-bg-inset)] overflow-hidden">
- <div
- className="h-full rounded-full bg-[var(--color-accent-primary)] transition-all"
- style={{ width: `${Math.min(Math.round(cc.strength * 10), 100)}%` }}
- />
- </div>
- <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums w-8 text-right">
- {Math.round(cc.strength * 10) / 10}
- </span>
- </div>
- </td>
- {!compact && (
- <td className="py-2 pr-4 text-xs text-[var(--color-text-secondary)] tabular-nums text-right">
- {cc.frequency}x
- </td>
- )}
- {!compact && (
- <td className="py-2 text-xs text-[var(--color-text-tertiary)]" title={cc.last_date ? new Date(cc.last_date).toLocaleString() : undefined}>
- {cc.last_date ? new Date(cc.last_date).toLocaleDateString() : "—"}
- </td>
- )}
- </tr>
- ))}
- </tbody>
- </table>
- </div>
+ <ResponsiveTable
+ columns={columns}
+ rows={coChanges}
+ rowKey={(cc) => `${cc.source_repo}|${cc.source_file}|${cc.target_repo}|${cc.target_file}`}
+ bare
+ empty={
+ <EmptyState
+ title="No cross-repo co-changes"
+ description="No files in sibling repos have changed together yet."
+ />
+ }
+ />
);
}
diff --git a/packages/ui/src/workspace/contract-links-table.tsx b/packages/ui/src/workspace/contract-links-table.tsx
index 7dc5c3b6a..779ffac8d 100644
--- a/packages/ui/src/workspace/contract-links-table.tsx
+++ b/packages/ui/src/workspace/contract-links-table.tsx
@@ -1,89 +1,122 @@
"use client";
import { ContractTypeBadge } from "./contract-type-badge";
+import { EmptyState } from "../shared/empty-state";
+import {
+ ResponsiveTable,
+ type ResponsiveColumn,
+} from "../shared/responsive-table";
import type { WorkspaceContractLinkEntry } from "@repowise-dev/types/workspace";
interface ContractLinksTableProps {
links: WorkspaceContractLinkEntry[];
}
-export function ContractLinksTable({ links }: ContractLinksTableProps) {
- if (links.length === 0) {
- return (
- <p className="text-sm text-[var(--color-text-tertiary)] py-4 text-center">
- No matched contract links.
- </p>
- );
- }
+const COLUMNS: ResponsiveColumn<WorkspaceContractLinkEntry>[] = [
+ {
+ key: "contract",
+ header: "Contract",
+ priority: 1,
+ cellClassName: "min-w-[140px] max-w-[280px]",
+ render: (link) => (
+ <span
+ className="text-xs font-mono text-[var(--color-text-secondary)] [overflow-wrap:anywhere]"
+ title={link.contract_id}
+ >
+ {link.contract_id}
+ </span>
+ ),
+ },
+ {
+ key: "type",
+ header: "Type",
+ priority: 2,
+ render: (link) => <ContractTypeBadge type={link.contract_type} />,
+ },
+ {
+ key: "provider",
+ header: "Provider",
+ priority: 1,
+ render: (link) => (
+ <div className="flex flex-col gap-0.5">
+ <span className="text-xs font-medium text-[var(--color-text-primary)]">
+ {link.provider_repo}
+ </span>
+ <span
+ className="text-xs font-mono text-[var(--color-text-tertiary)] truncate min-w-[140px] max-w-[260px] block"
+ title={link.provider_file}
+ >
+ {link.provider_file}
+ </span>
+ </div>
+ ),
+ mobileRender: (link) => link.provider_repo,
+ },
+ {
+ key: "consumer",
+ header: "Consumer",
+ priority: 2,
+ render: (link) => (
+ <div className="flex flex-col gap-0.5">
+ <span className="text-xs font-medium text-[var(--color-text-primary)]">
+ {link.consumer_repo}
+ </span>
+ <span
+ className="text-xs font-mono text-[var(--color-text-tertiary)] truncate min-w-[140px] max-w-[260px] block"
+ title={link.consumer_file}
+ >
+ {link.consumer_file}
+ </span>
+ </div>
+ ),
+ mobileRender: (link) => link.consumer_repo,
+ },
+ {
+ key: "confidence",
+ header: "Confidence",
+ mobileLabel: "Conf",
+ priority: 3,
+ headerClassName: "w-20",
+ render: (link) => (
+ <div className="flex items-center gap-1.5">
+ <div className="h-1.5 w-12 rounded-full bg-[var(--color-bg-inset)] overflow-hidden">
+ <div
+ className="h-full rounded-full transition-all"
+ style={{
+ width: `${Math.round(link.confidence * 100)}%`,
+ backgroundColor:
+ link.confidence >= 0.8
+ ? "var(--color-confidence-fresh)"
+ : link.confidence >= 0.6
+ ? "var(--color-confidence-stale)"
+ : "var(--color-confidence-outdated)",
+ }}
+ />
+ </div>
+ <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums">
+ {Math.round(link.confidence * 100)}%
+ </span>
+ </div>
+ ),
+ mobileRender: (link) => `${Math.round(link.confidence * 100)}%`,
+ },
+];
+export function ContractLinksTable({ links }: ContractLinksTableProps) {
return (
- <div className="overflow-x-auto">
- <table className="w-full text-sm">
- <thead>
- <tr className="border-b border-[var(--color-border-default)] text-left text-xs text-[var(--color-text-tertiary)]">
- <th className="pb-2 pr-4 font-medium">Contract</th>
- <th className="pb-2 pr-4 font-medium">Type</th>
- <th className="pb-2 pr-4 font-medium">Provider</th>
- <th className="pb-2 pr-4 font-medium">Consumer</th>
- <th className="pb-2 font-medium w-20">Confidence</th>
- </tr>
- </thead>
- <tbody className="divide-y divide-[var(--color-border-default)]">
- {links.map((link, i) => (
- <tr key={i} className="hover:bg-[var(--color-bg-elevated)] transition-colors">
- <td className="py-2 pr-4 min-w-[140px] max-w-[280px]">
- <span className="text-xs font-mono text-[var(--color-text-secondary)] [overflow-wrap:anywhere]" title={link.contract_id}>
- {link.contract_id}
- </span>
- </td>
- <td className="py-2 pr-4">
- <ContractTypeBadge type={link.contract_type} />
- </td>
- <td className="py-2 pr-4">
- <div className="flex flex-col gap-0.5">
- <span className="text-xs font-medium text-[var(--color-text-primary)]">
- {link.provider_repo}
- </span>
- <span className="text-xs font-mono text-[var(--color-text-tertiary)] truncate min-w-[140px] max-w-[260px] block" title={link.provider_file}>
- {link.provider_file}
- </span>
- </div>
- </td>
- <td className="py-2 pr-4">
- <div className="flex flex-col gap-0.5">
- <span className="text-xs font-medium text-[var(--color-text-primary)]">
- {link.consumer_repo}
- </span>
- <span className="text-xs font-mono text-[var(--color-text-tertiary)] truncate min-w-[140px] max-w-[260px] block" title={link.consumer_file}>
- {link.consumer_file}
- </span>
- </div>
- </td>
- <td className="py-2">
- <div className="flex items-center gap-1.5">
- <div className="h-1.5 w-12 rounded-full bg-[var(--color-bg-inset)] overflow-hidden">
- <div
- className="h-full rounded-full transition-all"
- style={{
- width: `${Math.round(link.confidence * 100)}%`,
- backgroundColor:
- link.confidence >= 0.8
- ? "var(--color-confidence-fresh)"
- : link.confidence >= 0.6
- ? "var(--color-confidence-stale)"
- : "var(--color-confidence-outdated)",
- }}
- />
- </div>
- <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums">
- {Math.round(link.confidence * 100)}%
- </span>
- </div>
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
+ <ResponsiveTable
+ columns={COLUMNS}
+ rows={links}
+ rowKey={(link) =>
+ `${link.contract_id}|${link.provider_repo}|${link.provider_file}|${link.consumer_repo}|${link.consumer_file}`
+ }
+ bare
+ empty={
+ <EmptyState
+ title="No matched contract links"
+ description="No API contracts link providers and consumers across these repos yet."
+ />
+ }
+ />
);
}
diff --git a/packages/ui/src/workspace/package-deps-table.tsx b/packages/ui/src/workspace/package-deps-table.tsx
index 018bb35be..0b8f81dd2 100644
--- a/packages/ui/src/workspace/package-deps-table.tsx
+++ b/packages/ui/src/workspace/package-deps-table.tsx
@@ -1,53 +1,71 @@
import { Badge } from "../ui/badge";
+import { EmptyState } from "../shared/empty-state";
+import {
+ ResponsiveTable,
+ type ResponsiveColumn,
+} from "../shared/responsive-table";
import type { WorkspacePackageDepEntry } from "@repowise-dev/types/workspace";
interface PackageDepsTableProps {
deps: WorkspacePackageDepEntry[];
}
-export function PackageDepsTable({ deps }: PackageDepsTableProps) {
- if (deps.length === 0) {
- return (
- <p className="text-sm text-[var(--color-text-tertiary)] py-4 text-center">
- No cross-repo package dependencies detected.
- </p>
- );
- }
+const COLUMNS: ResponsiveColumn<WorkspacePackageDepEntry>[] = [
+ {
+ key: "source",
+ header: "Source",
+ priority: 1,
+ render: (d) => (
+ <Badge variant="default" className="text-[11px]">
+ {d.source_repo}
+ </Badge>
+ ),
+ },
+ {
+ key: "target",
+ header: "Target",
+ priority: 1,
+ render: (d) => (
+ <Badge variant="default" className="text-[11px]">
+ {d.target_repo}
+ </Badge>
+ ),
+ },
+ {
+ key: "manifest",
+ header: "Manifest",
+ priority: 2,
+ cellClassName: "font-mono text-xs text-[var(--color-text-secondary)] max-w-[280px]",
+ render: (d) => (
+ <span className="block truncate" title={d.source_manifest}>
+ {d.source_manifest}
+ </span>
+ ),
+ },
+ {
+ key: "kind",
+ header: "Kind",
+ priority: 2,
+ cellClassName: "text-xs text-[var(--color-text-secondary)]",
+ render: (d) => d.kind,
+ },
+];
+export function PackageDepsTable({ deps }: PackageDepsTableProps) {
return (
- <div className="overflow-x-auto">
- <table className="w-full text-sm">
- <thead>
- <tr className="border-b border-[var(--color-border-default)] text-left text-xs text-[var(--color-text-tertiary)]">
- <th className="pb-2 pr-4 font-medium">Source</th>
- <th className="pb-2 pr-4 font-medium">Target</th>
- <th className="pb-2 pr-4 font-medium">Manifest</th>
- <th className="pb-2 font-medium">Kind</th>
- </tr>
- </thead>
- <tbody className="divide-y divide-[var(--color-border-default)]">
- {deps.map((d, i) => (
- <tr
- key={`${d.source_repo}|${d.target_repo}|${d.source_manifest}|${i}`}
- className="hover:bg-[var(--color-bg-elevated)] transition-colors"
- >
- <td className="py-2 pr-4">
- <Badge variant="default" className="text-[11px]">{d.source_repo}</Badge>
- </td>
- <td className="py-2 pr-4">
- <Badge variant="default" className="text-[11px]">{d.target_repo}</Badge>
- </td>
- <td
- className="py-2 pr-4 font-mono text-xs text-[var(--color-text-secondary)] truncate max-w-[280px]"
- title={d.source_manifest}
- >
- {d.source_manifest}
- </td>
- <td className="py-2 text-xs text-[var(--color-text-secondary)]">{d.kind}</td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
+ <ResponsiveTable
+ columns={COLUMNS}
+ rows={deps}
+ rowKey={(d) =>
+ `${d.source_repo}|${d.target_repo}|${d.source_manifest}|${d.kind}`
+ }
+ bare
+ empty={
+ <EmptyState
+ title="No cross-repo package dependencies"
+ description="No manifest in this workspace depends on a sibling repo's package."
+ />
+ }
+ />
);
}
diff --git a/packages/ui/src/workspace/repo-card.tsx b/packages/ui/src/workspace/repo-card.tsx
index 40547e881..4df82f4ab 100644
--- a/packages/ui/src/workspace/repo-card.tsx
+++ b/packages/ui/src/workspace/repo-card.tsx
@@ -1,8 +1,18 @@
import { FileText, Flame, BarChart3, ChevronRight } from "lucide-react";
import { Card, CardContent } from "../ui/card";
import { Badge } from "../ui/badge";
-import type { RepoStats } from "@repowise-dev/types/workspace";
-import type { GitSummary } from "@repowise-dev/types/git";
+
+// Structural subsets of RepoStats / GitSummary — the card only renders these
+// three numbers, so callers without the full payloads (workspace mode) don't
+// have to fabricate zero-filled fields.
+interface RepoCardStats {
+ file_count: number;
+ doc_coverage_pct: number;
+}
+
+interface RepoCardGitSummary {
+ hotspot_count: number;
+}
interface RepoCardProps {
repoId: string;
@@ -11,8 +21,8 @@ interface RepoCardProps {
name: string;
path: string;
isPrimary: boolean;
- stats: RepoStats | null;
- gitSummary: GitSummary | null;
+ stats: RepoCardStats | null;
+ gitSummary: RepoCardGitSummary | null;
/** Workspace status — undefined in single-repo mode. */
status?: "indexed" | "needs_index" | "missing_dir" | null;
/** Reason docs were skipped (cost gate, no provider, index-only, etc.). */
diff --git a/packages/ui/styles/globals.css b/packages/ui/styles/globals.css
index 6280a8f90..dec74fb51 100644
--- a/packages/ui/styles/globals.css
+++ b/packages/ui/styles/globals.css
@@ -104,6 +104,7 @@
--color-warning: #9a6614;
--color-error: #b23a2e;
--color-info: #58436c;
+ --color-caution: #a8821f; /* between warning and success; medium severity / fair score band */
/* Aliases — short names used in component class strings. Keep in sync. */
--color-fresh: var(--color-confidence-fresh);
@@ -310,6 +311,7 @@
--color-warning: #f2a03d;
--color-error: #e06a5a;
--color-info: #a98fc4;
+ --color-caution: #d9b04a;
--color-node-undocumented: #6f6678;
--viz-node-stroke: rgba(222, 210, 235, 0.22);
diff --git a/packages/web/src/app/page.tsx b/packages/web/src/app/page.tsx
index e09a92548..4e803ecf9 100644
--- a/packages/web/src/app/page.tsx
+++ b/packages/web/src/app/page.tsx
@@ -18,11 +18,10 @@ import type { RepoStatsResponse, GitSummaryResponse } from "@/lib/api/types";
import { StatCard } from "@repowise-dev/ui/shared/stat-card";
import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
import { Badge } from "@repowise-dev/ui/ui/badge";
-import { ConfidenceBadge } from "@repowise-dev/ui/wiki/confidence-badge";
import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
import { formatRelativeTime, formatNumber } from "@repowise-dev/ui/lib/format";
-import { scoreToStatus } from "@repowise-dev/ui/lib/confidence";
import { DeleteRepoButton } from "@/components/repos/delete-repo-button";
+import { LiveJobProgress } from "@/components/jobs/live-job-progress";
export const metadata: Metadata = { title: "Dashboard" };
@@ -123,63 +122,86 @@ export default async function DashboardPage() {
</CardHeader>
<CardContent className="p-0">
{repoList.length === 0 ? (
- <div className="px-6 pb-6">
+ <div className="px-6 pb-6 space-y-2">
<EmptyState
title="No repositories yet"
description="Run repowise init on a repository to get started."
icon={<FileText className="h-8 w-8" />}
/>
+ <p className="text-center text-xs text-[var(--color-text-tertiary)]">
+ New here? See the{" "}
+ <a
+ href="https://github.com/repowise-dev/repowise#quick-start"
+ target="_blank"
+ rel="noreferrer"
+ className="text-[var(--color-accent-primary)] hover:underline"
+ >
+ setup guide
+ </a>
+ .
+ </p>
</div>
) : (
<ul className="divide-y divide-[var(--color-border-default)]">
- {repoList.map((repo) => (
- <li key={repo.id} className="group">
- <div className="flex items-start gap-3 px-6 py-3.5 transition-colors hover:bg-[var(--color-bg-elevated)]">
- <Link
- href={`/repos/${repo.id}`}
- className="flex items-start gap-3 flex-1 min-w-0"
- >
- <div className="mt-0.5 h-2 w-2 rounded-full bg-[var(--color-accent-primary)] shrink-0" />
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2">
- <p className="text-sm font-medium text-[var(--color-text-primary)] truncate group-hover:text-[var(--color-accent-primary)] transition-colors">
- {repo.name}
- </p>
- </div>
- <div className="flex items-center gap-2 mt-0.5">
- <p className="text-xs text-[var(--color-text-tertiary)] font-mono truncate" title={repo.local_path}>
- {repo.local_path}
- </p>
- </div>
- <div className="flex items-center gap-2 mt-1 flex-wrap">
- {repo.head_commit && (
- <span className="text-xs font-mono text-[var(--color-text-tertiary)]">
- {repo.head_commit.slice(0, 7)}
+ {repoList.map((repo) => {
+ const activeJob = jobList.find(
+ (j) =>
+ j.repository_id === repo.id &&
+ (j.status === "running" || j.status === "pending"),
+ );
+ const g = gitMap.get(repo.id);
+ return (
+ <li key={repo.id} className="group">
+ <div className="flex items-start gap-3 px-6 py-3.5 transition-colors hover:bg-[var(--color-bg-elevated)]">
+ <Link
+ href={`/repos/${repo.id}`}
+ className="flex items-start gap-3 flex-1 min-w-0"
+ >
+ <div className="mt-0.5 h-2 w-2 rounded-full bg-[var(--color-accent-primary)] shrink-0" />
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 flex-wrap">
+ <p
+ className="text-sm font-medium text-[var(--color-text-primary)] truncate group-hover:text-[var(--color-accent-primary)] transition-colors"
+ title={repo.head_commit ? `at ${repo.head_commit.slice(0, 7)}` : undefined}
+ >
+ {repo.name}
+ </p>
+ {/* Health signals lead; raw SHA demoted to the title tooltip. */}
+ {g && g.hotspot_count > 0 && (
+ <Badge variant="outdated">
+ {g.hotspot_count} hotspot{g.hotspot_count !== 1 ? "s" : ""}
+ </Badge>
+ )}
+ {g && g.stable_count > 0 && (
+ <Badge variant="fresh">{g.stable_count} stable</Badge>
+ )}
+ {activeJob && (
+ <span className="text-xs">
+ <LiveJobProgress
+ jobId={activeJob.id}
+ initialCompleted={activeJob.completed_pages}
+ initialTotal={activeJob.total_pages}
+ />
+ </span>
+ )}
+ </div>
+ <div className="flex items-center gap-2 mt-0.5">
+ <p className="text-xs text-[var(--color-text-tertiary)] font-mono truncate" title={repo.local_path}>
+ {repo.local_path}
+ </p>
+ </div>
+ <div className="flex items-center gap-2 mt-1 flex-wrap">
+ <span className="text-xs text-[var(--color-text-tertiary)]">
+ Updated {formatRelativeTime(repo.updated_at)}
</span>
- )}
- <span className="text-xs text-[var(--color-text-tertiary)]">
- Updated {formatRelativeTime(repo.updated_at)}
- </span>
- {gitMap.has(repo.id) && (() => {
- const g = gitMap.get(repo.id)!;
- return (
- <>
- {g.hotspot_count > 0 && (
- <Badge variant="outdated">{g.hotspot_count} hotspot{g.hotspot_count !== 1 ? "s" : ""}</Badge>
- )}
- {g.stable_count > 0 && (
- <Badge variant="fresh">{g.stable_count} stable</Badge>
- )}
- </>
- );
- })()}
+ </div>
</div>
- </div>
- </Link>
- <DeleteRepoButton repoId={repo.id} repoName={repo.name} />
- </div>
- </li>
- ))}
+ </Link>
+ <DeleteRepoButton repoId={repo.id} repoName={repo.name} />
+ </div>
+ </li>
+ );
+ })}
</ul>
)}
</CardContent>
@@ -211,10 +233,12 @@ export default async function DashboardPage() {
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-xs font-mono text-[var(--color-text-secondary)]">
- {job.status === "running" ? (
- <span className="text-[var(--color-accent-primary)]">
- {job.completed_pages}/{job.total_pages} pages
- </span>
+ {job.status === "running" || job.status === "pending" ? (
+ <LiveJobProgress
+ jobId={job.id}
+ initialCompleted={job.completed_pages}
+ initialTotal={job.total_pages}
+ />
) : (
`${job.total_pages} pages`
)}
diff --git a/packages/web/src/app/repos/[id]/c4/loading.tsx b/packages/web/src/app/repos/[id]/architecture/loading.tsx
similarity index 64%
rename from packages/web/src/app/repos/[id]/c4/loading.tsx
rename to packages/web/src/app/repos/[id]/architecture/loading.tsx
index cb1420a0f..82aefcc8a 100644
--- a/packages/web/src/app/repos/[id]/c4/loading.tsx
+++ b/packages/web/src/app/repos/[id]/architecture/loading.tsx
@@ -1,5 +1,5 @@
import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";
export default function Loading() {
- return <OwlLoader />;
+ return <OwlLoader label="Loading architecture…" />;
}
diff --git a/packages/web/src/app/repos/[id]/architecture/page.tsx b/packages/web/src/app/repos/[id]/architecture/page.tsx
new file mode 100644
index 000000000..3b2166634
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/architecture/page.tsx
@@ -0,0 +1,145 @@
+"use client";
+
+/**
+ * Architecture — `/repos/[id]/architecture`.
+ *
+ * One destination for "how is this built", with five modes behind `?view=`:
+ * - map — the constellation Knowledge Graph (community super-graph)
+ * - layers — the curated layered architecture view (tour, personas)
+ * - explore — the full / module dependency graph with dead/hot overlays
+ * - symbols — the searchable symbol index
+ * - deps — the third-party dependency registry
+ * The legacy C4 diagram stays reachable behind `?view=c4` until the layered
+ * view reaches full parity.
+ *
+ * Map and Explore share one canvas component (GraphFlow) and therefore one
+ * search, one path finder, one legend and one inspector; switching scope
+ * inside the canvas keeps `?view=` in sync without remounting.
+ */
+
+import { use, useCallback } from "react";
+import { useQueryState, parseAsStringLiteral } from "nuqs";
+import { Code2 } from "lucide-react";
+import { cn } from "@/lib/utils/cn";
+import { GraphView } from "@/components/architecture/graph-view";
+import { C4View } from "@/components/architecture/c4-view";
+import { DependenciesView } from "@/components/architecture/dependencies-view";
+import { SymbolTableWrapper as SymbolTable } from "@/components/symbols/symbol-table-wrapper";
+
+// "graph" and "c4" are accepted as legacy aliases from pre-merge URLs and
+// normalized below; only the five canonical views render switcher buttons.
+const VIEWS = ["map", "layers", "explore", "symbols", "deps", "graph", "c4"] as const;
+type ArchView = (typeof VIEWS)[number];
+
+const CANONICAL_VIEWS: ArchView[] = ["map", "layers", "explore", "symbols", "deps"];
+
+const VIEW_LABELS: Record<ArchView, string> = {
+ map: "Map",
+ layers: "Layers",
+ explore: "Explore",
+ symbols: "Symbols",
+ deps: "Dependencies",
+ graph: "Map",
+ c4: "C4 (legacy)",
+};
+
+const VIEW_HINTS: Record<string, string> = {
+ map: "Constellation of detected communities",
+ layers: "Curated layered view with a guided tour",
+ explore: "Full dependency graph with dead/hot overlays",
+ symbols: "Every function, class and export",
+ deps: "Declared third-party dependencies",
+};
+
+// Legacy ?view=graph deep links carried the graph scope in ?viewMode=. Scopes
+// that render file-level graphs map to Explore; the constellation maps to Map.
+const EXPLORE_VIEW_MODES = new Set(["module", "full", "dead", "hotfiles", "unified"]);
+
+export default function ArchitecturePage({
+ params,
+}: {
+ params: Promise<{ id: string }>;
+}) {
+ const { id: repoId } = use(params);
+ const [rawView, setView] = useQueryState(
+ "view",
+ parseAsStringLiteral(VIEWS).withDefault("map"),
+ );
+ const [viewModeParam] = useQueryState("viewMode");
+ const [modeParam] = useQueryState("mode");
+
+ // Normalize legacy aliases without a URL rewrite (cheap, shareable links
+ // keep working): graph → map/explore by scope; c4 + mode=architecture was
+ // the curated view (now Layers); c4 + mode=c4 stays the frozen legacy mode.
+ let view: ArchView = rawView;
+ if (rawView === "graph") {
+ view = EXPLORE_VIEW_MODES.has(viewModeParam ?? "") ? "explore" : "map";
+ } else if (rawView === "c4" && modeParam !== "c4") {
+ view = "layers";
+ }
+
+ const handleScopeViewChange = useCallback(
+ (next: "map" | "explore") => {
+ void setView(next);
+ },
+ [setView],
+ );
+
+ const isGraphCanvas = view === "map" || view === "explore";
+
+ return (
+ <div className="flex h-full flex-col">
+ {/* View switcher */}
+ <div className="flex shrink-0 items-center gap-1 border-b border-[var(--color-border-default)] px-4 py-2 sm:px-6 overflow-x-auto">
+ {CANONICAL_VIEWS.map((v) => (
+ <button
+ key={v}
+ onClick={() => void setView(v)}
+ title={VIEW_HINTS[v]}
+ className={cn(
+ "rounded-md px-3 py-1.5 text-xs font-medium whitespace-nowrap transition-colors",
+ view === v
+ ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"
+ : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]",
+ )}
+ >
+ {VIEW_LABELS[v]}
+ </button>
+ ))}
+ {view === "c4" && (
+ <span className="rounded-md bg-[var(--color-accent-muted)] px-3 py-1.5 text-xs font-medium text-[var(--color-accent-primary)] whitespace-nowrap">
+ C4 (legacy)
+ </span>
+ )}
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-auto">
+ {isGraphCanvas && (
+ <GraphView
+ repoId={repoId}
+ scope={view as "map" | "explore"}
+ onScopeViewChange={handleScopeViewChange}
+ />
+ )}
+ {(view === "layers" || view === "c4") && (
+ <C4View repoId={repoId} legacy={view === "c4"} />
+ )}
+ {view === "deps" && <DependenciesView repoId={repoId} />}
+ {view === "symbols" && (
+ <div className="max-w-[1600px] space-y-6 p-4 sm:p-6">
+ <div>
+ <h1 className="mb-1 flex items-center gap-2 text-xl font-semibold text-[var(--color-text-primary)]">
+ <Code2 className="h-5 w-5 text-[var(--color-accent-primary)]" />
+ Symbol Index
+ </h1>
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ Searchable index of all functions, classes, and exports.
+ </p>
+ </div>
+ <SymbolTable repoId={repoId} />
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/app/repos/[id]/blast-radius/page.tsx b/packages/web/src/app/repos/[id]/blast-radius/page.tsx
index e658a6646..5bb7bf800 100644
--- a/packages/web/src/app/repos/[id]/blast-radius/page.tsx
+++ b/packages/web/src/app/repos/[id]/blast-radius/page.tsx
@@ -1,211 +1,11 @@
-"use client";
-
-import { useState } from "react";
-import useSWR from "swr";
-import { useParams } from "next/navigation";
-import { Radar, Plus, Flame } from "lucide-react";
-import { RoutedToRiskBanner } from "@/components/risk/routed-to-risk-banner";
-import { Button } from "@repowise-dev/ui/ui/button";
-import { Card, CardHeader, CardTitle, CardContent } from "@repowise-dev/ui/ui/card";
-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-import { BlastRadiusResults } from "@repowise-dev/ui/blast-radius";
-import { ReviewerSuggestions } from "@repowise-dev/ui/git/reviewer-suggestions";
-import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";
-import { analyzeBlastRadius } from "@/lib/api/blast-radius";
-import { getHotspots, getReviewerSuggestions } from "@/lib/api/git";
-import { useRouter } from "next/navigation";
-
-export default function BlastRadiusPage() {
- const params = useParams<{ id: string }>();
- const repoId = params.id;
-
- const [files, setFiles] = useState("");
- const [maxDepth, setMaxDepth] = useState(3);
- const [loading, setLoading] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [result, setResult] = useState<BlastRadiusResponse | null>(null);
- const [analyzedPaths, setAnalyzedPaths] = useState<string[]>([]);
- const router = useRouter();
-
- // Reviewer suggestions key off the *most recently analyzed* paths so the
- // panel updates the moment the analyze button is hit.
- const reviewerKey = analyzedPaths.length
- ? `reviewer-suggestions:${repoId}:${analyzedPaths.join(",")}`
- : null;
- const { data: reviewerResp, isLoading: reviewerLoading } = useSWR(
- reviewerKey,
- () => getReviewerSuggestions(repoId, analyzedPaths),
- { revalidateOnFocus: false },
- );
-
- // Suggestions: top 8 hotspots so users can prefill with one click instead
- // of remembering paths. Falls back gracefully if the call fails.
- const { data: hotspotSuggestions, isLoading: hotspotSuggestionsLoading } = useSWR(
- repoId ? ["blast-radius-suggestions", repoId] : null,
- () => getHotspots(repoId, 8),
- );
-
- const addSuggestion = (path: string) => {
- setFiles((prev) => {
- const lines = prev.split("\n").map((l) => l.trim()).filter(Boolean);
- if (lines.includes(path)) return prev;
- return [...lines, path].join("\n");
- });
- };
-
- const useAllHotspots = () => {
- if (!hotspotSuggestions) return;
- setFiles(hotspotSuggestions.map((h) => h.file_path).join("\n"));
- };
-
- const clearFiles = () => setFiles("");
-
- const handleAnalyze = async () => {
- const changedFiles = files
- .split("\n")
- .map((l) => l.trim())
- .filter(Boolean);
-
- if (changedFiles.length === 0) {
- setError("Enter at least one file path.");
- return;
- }
-
- setLoading(true);
- setError(null);
- setResult(null);
-
- try {
- const data = await analyzeBlastRadius(repoId, {
- changed_files: changedFiles,
- max_depth: maxDepth,
- });
- setResult(data);
- setAnalyzedPaths(changedFiles);
- } catch (err) {
- setError(err instanceof Error ? err.message : "Analysis failed.");
- } finally {
- setLoading(false);
- }
- };
-
- return (
- <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">
- <RoutedToRiskBanner repoId={repoId} tab="impact" tabLabel="Impact analyzer" />
- {/* Header */}
- <div>
- <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 flex items-center gap-2">
- <Radar className="h-5 w-5 text-violet-500" />
- Blast Radius
- </h1>
- <p className="text-sm text-[var(--color-text-secondary)]">
- Estimate the impact of a proposed PR — direct risks, transitive effects, reviewer
- suggestions, and test gaps.
- </p>
- </div>
-
- {/* Input form */}
- <Card>
- <CardHeader className="pb-3">
- <CardTitle className="text-sm">Changed Files</CardTitle>
- </CardHeader>
- <CardContent className="pt-0 space-y-4">
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Paste a list of file paths (one per line) — typically the files in your PR diff.
- Don&apos;t know what to try? Click a hotspot below to prefill, or use{" "}
- <button
- type="button"
- onClick={useAllHotspots}
- className="underline underline-offset-2 hover:text-[var(--color-text-primary)]"
- disabled={!hotspotSuggestions || hotspotSuggestions.length === 0}
- >
- Use top hotspots
- </button>
- .
- </p>
-
- {hotspotSuggestionsLoading && !hotspotSuggestions && (
- <div className="flex flex-wrap gap-2">
- {Array.from({ length: 6 }).map((_, i) => (
- <Skeleton key={i} className="h-7 w-32 rounded-full" />
- ))}
- </div>
- )}
-
- {hotspotSuggestions && hotspotSuggestions.length > 0 && (
- <div className="flex flex-wrap gap-2">
- {hotspotSuggestions.map((h) => (
- <button
- key={h.file_path}
- type="button"
- onClick={() => addSuggestion(h.file_path)}
- className="inline-flex items-center gap-1 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2.5 py-1 text-[11px] font-mono text-[var(--color-text-secondary)] hover:border-[var(--color-accent-primary)] hover:text-[var(--color-text-primary)] transition-colors"
- title={h.file_path}
- aria-label={`Add ${h.file_path} to changed files`}
- >
- <Flame className="h-3 w-3 text-orange-500" />
- <span className="truncate max-w-[260px]">{h.file_path}</span>
- <Plus className="h-3 w-3 opacity-60" />
- </button>
- ))}
- </div>
- )}
-
- <label htmlFor="blast-radius-changed-files" className="sr-only">
- Changed file paths, one per line
- </label>
- <textarea
- id="blast-radius-changed-files"
- className="w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-2 text-xs font-mono text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] focus:outline-none focus:ring-1 focus:ring-[var(--color-accent-primary)] resize-y min-h-[120px]"
- placeholder={"src/auth/login.py\nsrc/models/user.py\n..."}
- value={files}
- onChange={(e) => setFiles(e.target.value)}
- aria-label="Changed file paths, one per line"
- />
- <div className="flex items-center gap-4 flex-wrap">
- <label className="flex items-center gap-2 text-xs text-[var(--color-text-secondary)]">
- Max depth
- <input
- type="number"
- min={1}
- max={10}
- value={maxDepth}
- onChange={(e) => setMaxDepth(Math.max(1, Math.min(10, Number(e.target.value))))}
- className="w-16 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-xs text-[var(--color-text-primary)] focus:outline-none focus:ring-1 focus:ring-[var(--color-accent-primary)]"
- aria-label="Maximum dependency depth (1–10)"
- />
- </label>
- <Button onClick={handleAnalyze} disabled={loading} size="sm">
- {loading ? "Analyzing…" : "Analyze"}
- </Button>
- {files && (
- <Button onClick={clearFiles} disabled={loading} size="sm" variant="outline">
- Clear
- </Button>
- )}
- </div>
- {error && <p className="text-xs text-red-500">{error}</p>}
- </CardContent>
- </Card>
-
- {result && (
- <div className="grid gap-4 lg:grid-cols-3">
- <div className="lg:col-span-2 space-y-4">
- <BlastRadiusResults result={result} />
- </div>
- <div className="space-y-4">
- <ReviewerSuggestions
- suggestions={reviewerResp?.suggestions ?? []}
- isLoading={reviewerLoading}
- subtitle={`Based on git history of ${analyzedPaths.length} touched ${analyzedPaths.length === 1 ? "path" : "paths"}.`}
- onSelect={(s) => {
- const k = s.email ?? `name:${s.name}`;
- router.push(`/repos/${repoId}/owners/${encodeURIComponent(k)}`);
- }}
- />
- </div>
- </div>
- )}
- </div>
- );
+import { redirect } from "next/navigation";
+
+/** Legacy route — redirects into the consolidated IA. */
+export default async function LegacyRedirect({
+ params,
+}: {
+ params: Promise<{ id: string }>;
+}) {
+ const { id } = await params;
+ redirect(`/repos/${id}/code-health?tab=impact`);
}
diff --git a/packages/web/src/app/repos/[id]/c4/page.tsx b/packages/web/src/app/repos/[id]/c4/page.tsx
index 2f0b28642..aa5e9da28 100644
--- a/packages/web/src/app/repos/[id]/c4/page.tsx
+++ b/packages/web/src/app/repos/[id]/c4/page.tsx
@@ -1,488 +1,22 @@
-"use client";
-
-/**
- * C4 / Architecture diagrams — `/repos/[id]/c4`.
- *
- * Supports two modes:
- * - mode=c4 — legacy C4 three-level diagram
- * - mode=architecture — new unified architecture view (default)
- *
- * URL params are synced bidirectionally with the Zustand store so that
- * refresh + share preserve the view state.
- */
-
-import { use, useCallback, useEffect, useRef } from "react";
-import { useQueryState, parseAsInteger, parseAsString, parseAsStringLiteral } from "nuqs";
-import {
- C4Diagram,
- type C4Level,
- useArchitectureStore,
- useArchitectureLayout,
- useArchitectureNavigation,
- archNodeTypes,
- archEdgeTypes,
- SearchBar,
- ArchBreadcrumb,
- ArchLegend,
- PersonaSelector,
- NodeTypeCategoryFilters,
- FilterPanel,
- CodeViewer,
- PathFinderModal,
- type Persona,
- KEYFRAMES,
-} from "@repowise-dev/ui/c4";
-import {
- Background,
- BackgroundVariant,
- Controls,
- MiniMap,
- ReactFlow,
- ReactFlowProvider,
- useReactFlow,
-} from "@xyflow/react";
-import "@xyflow/react/dist/style.css";
-import { useC4L1, useC4L2, useC4L3 } from "@/lib/hooks/use-c4";
-import { useArchitectureView } from "@/lib/hooks/use-architecture";
-import { useC4DocsPathSet } from "@/lib/hooks/use-c4-context";
-import { useRepo } from "@/lib/hooks/use-repo";
-import { getC4Mermaid } from "@/lib/api/c4";
-import { C4DetailPanelHost } from "@/components/c4/c4-detail-panel-host";
-import { ArchDetailPanelHost } from "@/components/c4/arch-detail-panel-host";
-import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
-import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";
-import { AlertTriangle } from "lucide-react";
-
-const MODE_VALUES = ["c4", "architecture"] as const;
-const VIEW_VALUES = ["overview", "groups", "detail"] as const;
-const PERSONA_VALUES = ["overview", "learn", "deep-dive"] as const;
-// Unified click grammar (kg-ux plan B5): single click = select + inspect on
-// every node kind. Only true non-entities stay unselectable — portals are
-// navigation stubs, the scope frame is a pointer-events-none underlay.
-const SYNTHETIC_NODE_TYPES = new Set(["portal", "scopeFrame"]);
-
-function clampLevel(n: number | null): C4Level {
- return n === 1 ? 1 : n === 3 ? 3 : 2;
-}
-
-export default function C4Page({ params }: { params: Promise<{ id: string }> }) {
- const { id: repoId } = use(params);
- const { repo } = useRepo(repoId);
-
- const [mode] = useQueryState(
- "mode",
- parseAsStringLiteral(MODE_VALUES).withDefault("architecture"),
- );
-
- return (
- <div className="flex flex-col h-full">
- {mode === "c4" ? (
- <LegacyC4View repoId={repoId} repoName={repo?.name ?? "System"} />
- ) : (
- <ArchitectureViewPage repoId={repoId} repoName={repo?.name ?? "System"} />
- )}
- </div>
- );
-}
-
-// ---------------------------------------------------------------------------
-// Architecture View (new)
-// ---------------------------------------------------------------------------
-
-function ArchitectureViewPage({ repoId, repoName }: { repoId: string; repoName: string }) {
- return (
- <ReactFlowProvider>
- <ArchitectureViewInner repoId={repoId} repoName={repoName} />
- </ReactFlowProvider>
- );
-}
-
-function ArchitectureViewInner({ repoId, repoName }: { repoId: string; repoName: string }) {
- const { view, error, isLoading } = useArchitectureView(repoId);
- const { fitView } = useReactFlow();
-
- const [, setViewParam] = useQueryState(
- "view",
- parseAsStringLiteral(VIEW_VALUES).withDefault("overview"),
- );
- const [layerParam, setLayerParam] = useQueryState("layer", parseAsString);
- const [groupParam, setGroupParam] = useQueryState("group", parseAsString);
- const [nodeParam, setNodeParam] = useQueryState("node", parseAsString);
- const [personaParam, setPersonaParam] = useQueryState(
- "persona",
- parseAsStringLiteral(PERSONA_VALUES).withDefault("overview"),
- );
-
- const setView = useArchitectureStore((s) => s.setView);
- const navigationLevel = useArchitectureStore((s) => s.navigationLevel);
- const activeLayerId = useArchitectureStore((s) => s.activeLayerId);
- const activeSubGroupId = useArchitectureStore((s) => s.activeSubGroupId);
- const selectedNodeId = useArchitectureStore((s) => s.selectedNodeId);
- const persona = useArchitectureStore((s) => s.persona);
- const drillIntoLayer = useArchitectureStore((s) => s.drillIntoLayer);
- const drillIntoSubGroup = useArchitectureStore((s) => s.drillIntoSubGroup);
- const selectNode = useArchitectureStore((s) => s.selectNode);
- const setPersona = useArchitectureStore((s) => s.setPersona);
- const setReactFlowInstance = useArchitectureStore((s) => s.setReactFlowInstance);
- const pathFinderOpen = useArchitectureStore((s) => s.pathFinderOpen);
-
- useEffect(() => {
- if (view) setView(view);
- }, [view, setView]);
-
- const initializedRef = useRef(false);
- useEffect(() => {
- if (!view || initializedRef.current) return;
- initializedRef.current = true;
-
- if (personaParam && personaParam !== "overview") {
- setPersona(personaParam as Persona);
- }
- if (layerParam) {
- drillIntoLayer(layerParam);
- }
- if (groupParam) {
- drillIntoSubGroup(groupParam);
- }
- if (nodeParam) {
- selectNode(nodeParam);
- }
- }, [view, layerParam, groupParam, nodeParam, personaParam,
- drillIntoLayer, drillIntoSubGroup, selectNode, setPersona]);
-
- const syncingRef = useRef(false);
- useEffect(() => {
- // Until the deep-link restore above has run, the store still holds its
- // default overview state — syncing that to the URL would null out the
- // very params the restore is about to read, so every shared link
- // snapped back to the overview.
- if (!initializedRef.current) return;
- if (syncingRef.current) return;
- syncingRef.current = true;
- void setViewParam(
- navigationLevel === "layer-detail"
- ? "detail"
- : navigationLevel === "layer-groups"
- ? "groups"
- : "overview",
- );
- void setLayerParam(activeLayerId);
- void setGroupParam(activeSubGroupId);
- void setNodeParam(selectedNodeId);
- void setPersonaParam(persona);
- syncingRef.current = false;
- }, [navigationLevel, activeLayerId, activeSubGroupId, selectedNodeId, persona,
- setViewParam, setLayerParam, setGroupParam, setNodeParam, setPersonaParam]);
-
- useArchitectureNavigation();
-
- const { nodes, edges, loading: layoutLoading, hiddenEdgeCount } = useArchitectureLayout();
-
- const pendingFitRef = useRef(false);
- const prevNavRef = useRef({ navigationLevel, activeLayerId });
- useEffect(() => {
- if (
- prevNavRef.current.navigationLevel !== navigationLevel ||
- prevNavRef.current.activeLayerId !== activeLayerId
- ) {
- pendingFitRef.current = true;
- prevNavRef.current = { navigationLevel, activeLayerId };
- }
- }, [navigationLevel, activeLayerId]);
-
- useEffect(() => {
- if (!pendingFitRef.current || nodes.length === 0) return;
- pendingFitRef.current = false;
- const raf = requestAnimationFrame(() => {
- fitView({ duration: 400, padding: 0.2 });
- });
- return () => cancelAnimationFrame(raf);
- }, [nodes, fitView]);
-
- // Camera ease on select (kg-ux plan B5): frame the selected node without
- // drilling. Eases once per selection — layout refreshes (dimming etc.)
- // never re-center a camera the user has panned away.
- const lastEasedRef = useRef<string | null>(null);
- useEffect(() => {
- if (!selectedNodeId) {
- lastEasedRef.current = null;
- return;
- }
- if (lastEasedRef.current === selectedNodeId) return;
- if (!nodes.some((n) => n.id === selectedNodeId)) return;
- lastEasedRef.current = selectedNodeId;
- const raf = requestAnimationFrame(() => {
- fitView({ nodes: [{ id: selectedNodeId }], duration: 250, padding: 0.4, maxZoom: 1.15 });
- });
- return () => cancelAnimationFrame(raf);
- }, [selectedNodeId, nodes, fitView]);
-
- const handleNodeClick = useCallback(
- (_: React.MouseEvent, node: { id: string; type?: string }) => {
- if (SYNTHETIC_NODE_TYPES.has(node.type ?? "")) return;
- selectNode(node.id);
- },
- [selectNode],
- );
-
- // Double click = drill (grammar): layer → groups/detail, group → detail,
- // folder → expand/collapse. (Drilling clears selection in the store.)
- const handleNodeDoubleClick = useCallback(
- (_: React.MouseEvent, node: { id: string; type?: string }) => {
- if (node.type === "layerCluster") {
- drillIntoLayer(node.id);
- } else if (node.type === "subGroupCluster") {
- useArchitectureStore.getState().drillIntoSubGroup(node.id);
- } else if (node.type === "archContainer") {
- useArchitectureStore.getState().toggleContainer(node.id);
- }
- },
- [drillIntoLayer],
- );
-
- const handlePaneClick = useCallback(() => {
- selectNode(null);
- }, [selectNode]);
-
- const fetchContent = useCallback(
- async (filePath: string) => {
- const apiBase =
- typeof window !== "undefined"
- ? (process.env.NEXT_PUBLIC_REPOWISE_API_URL ?? "")
- : "";
- const apiKey =
- typeof window !== "undefined"
- ? localStorage.getItem("repowise_api_key")
- : null;
- const res = await fetch(
- `${apiBase}/api/repos/${repoId}/file-content?` +
- new URLSearchParams({ file_path: filePath }).toString(),
- { headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : {} },
- );
- if (!res.ok) {
- throw new Error(`Failed to fetch file content (${res.status})`);
- }
- return res.text();
- },
- [repoId],
- );
-
- const anyLoading = isLoading || layoutLoading;
-
- return (
- <>
- <div className="shrink-0 px-4 sm:px-6 py-3 border-b border-[var(--color-border-default)]">
- <div className="flex items-center justify-between">
- <div>
- <h1 className="text-lg font-semibold text-[var(--color-text-primary)]">
- Knowledge Graph
- </h1>
- <p className="text-xs text-[var(--color-text-secondary)] mt-0.5">
- {repoName} — layers, nodes, and relationships.
- </p>
- </div>
- <div className="flex items-center gap-3">
- <PersonaSelector />
- <NodeTypeCategoryFilters />
- </div>
- </div>
- <div className="mt-2 flex items-center gap-4">
- <SearchBar />
- <ArchBreadcrumb />
- </div>
- </div>
-
- <style>{KEYFRAMES.accentPulse}{KEYFRAMES.edgeFlow}{`
- /* Zoom-into-tier feel: nodes glide to their next slot (plan D). */
- @media (prefers-reduced-motion: no-preference) {
- .react-flow__node { transition: transform 180ms ease; }
- }
- `}</style>
- <div className="flex-1 min-h-0 relative bg-[var(--color-bg-canvas)]">
- {error && (
- <div className="absolute inset-0 flex items-center justify-center z-10">
- <EmptyState
- icon={<AlertTriangle className="h-5 w-5" aria-hidden />}
- title="Couldn't load the knowledge graph"
- description={error.message}
- className="max-w-md p-8"
- />
- </div>
- )}
- {anyLoading && nodes.length === 0 && !error && (
- <div className="absolute inset-0 flex items-center justify-center z-10 pointer-events-none">
- <OwlLoader size={120} label="Loading knowledge graph…" className="min-h-0" />
- </div>
- )}
- {/* Re-layout feedback (B6): ELK stage-2 on big layers used to freeze
- silently — a small owl chip says the canvas is thinking. */}
- {anyLoading && nodes.length > 0 && !error && (
- <div className="absolute top-3 left-1/2 -translate-x-1/2 z-10 pointer-events-none rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/95 px-3 py-1 shadow-sm">
- <OwlLoader size={28} label="Laying out…" className="min-h-0 flex-row gap-2 text-[10px]" />
- </div>
- )}
-
- <ReactFlow
- nodes={nodes}
- edges={edges}
- nodeTypes={archNodeTypes}
- edgeTypes={archEdgeTypes}
- onNodeClick={handleNodeClick}
- onNodeDoubleClick={handleNodeDoubleClick}
- onPaneClick={handlePaneClick}
- onInit={setReactFlowInstance}
- fitView
- fitViewOptions={{ padding: 0.2 }}
- minZoom={0.1}
- maxZoom={3}
- proOptions={{ hideAttribution: true }}
- nodesDraggable={false}
- nodesConnectable={false}
- >
- {/* Blueprint graph paper: 24px line grid on the warm canvas, matching
- the mermaid container (kg-ux plan §2.1). */}
- <Background variant={BackgroundVariant.Lines} gap={24} size={1} color="var(--color-diagram-grid)" />
- <Controls showInteractive={false} />
- {/* maskColor comes from --xy-minimap-mask-background (theme-aware). */}
- <MiniMap pannable zoomable />
- </ReactFlow>
-
- {/* Orientation (plan C-1) and the tour player (C-2) render in the
- right Sidebar only — the floating left asides duplicated them
- (user feedback 2026-06-05: one place). */}
-
- {hiddenEdgeCount > 0 && (
- <div
- className="absolute bottom-4 left-14 z-10 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-secondary)]/90 px-3 py-1 text-xs text-[var(--color-text-secondary)]"
- title="Weakest aggregated connections are hidden to keep the view legible. Drill in to see them."
- >
- +{hiddenEdgeCount} weaker link{hiddenEdgeCount === 1 ? "" : "s"} hidden
- </div>
- )}
-
- {/* Decoder ring — collapsible, every tier (B6). */}
- <div className="absolute bottom-4 right-[224px] z-10">
- <ArchLegend />
- </div>
-
- <ArchDetailPanelHost repoId={repoId} />
-
- <FilterPanel />
-
- <CodeViewer fetchContent={fetchContent} />
-
- {pathFinderOpen && <PathFinderModal />}
- </div>
- </>
- );
-}
-
-// ---------------------------------------------------------------------------
-// Legacy C4 View (preserved for backward compat)
-// ---------------------------------------------------------------------------
-
-function LegacyC4View({ repoId, repoName }: { repoId: string; repoName: string }) {
- const [levelParam, setLevelParam] = useQueryState(
- "level",
- parseAsInteger.withDefault(2),
- );
- const [containerParam, setContainerParam] = useQueryState(
- "container",
- parseAsString,
- );
-
- const level = clampLevel(levelParam);
- const activeContainerId = containerParam || null;
-
- const { view: l1View, error: l1Err, isLoading: l1Loading } = useC4L1(level === 1 ? repoId : null);
- const { view: l2View, error: l2Err, isLoading: l2Loading } = useC4L2(level >= 2 ? repoId : null);
- const { view: l3View, error: l3Err, isLoading: l3Loading } = useC4L3(
- level === 3 ? repoId : null,
- level === 3 ? activeContainerId : null,
- );
-
- const setLevel = useCallback(
- (next: C4Level) => {
- void setLevelParam(next);
- if (next !== 3) void setContainerParam(null);
- },
- [setContainerParam, setLevelParam],
- );
-
- const drillInto = useCallback(
- (containerId: string) => {
- void setLevelParam(3);
- void setContainerParam(containerId);
- },
- [setContainerParam, setLevelParam],
- );
-
- const drillOut = useCallback(() => {
- if (level === 3) {
- void setLevelParam(2);
- void setContainerParam(null);
- } else if (level === 2) {
- void setLevelParam(1);
- }
- }, [level, setContainerParam, setLevelParam]);
-
- const loading = level === 1 ? l1Loading : level === 2 ? l2Loading : l3Loading;
- const error = level === 1 ? l1Err : level === 2 ? l2Err : l3Err;
-
- const { pathSet: docsPathSet, pageIdByPath } = useC4DocsPathSet(repoId);
-
- const fetchMermaid = useCallback(
- () => getC4Mermaid(repoId, level, activeContainerId),
- [activeContainerId, level, repoId],
- );
-
- return (
- <>
- <div className="shrink-0 px-4 sm:px-6 py-3 border-b border-[var(--color-border-default)]">
- <div className="flex items-center justify-between gap-4">
- <div>
- <h1 className="text-lg font-semibold text-[var(--color-text-primary)]">
- Knowledge Graph
- </h1>
- <p className="text-xs text-[var(--color-text-secondary)] mt-0.5">
- System context, containers, and components — drill in to navigate.
- </p>
- </div>
- {/* Legacy mode is frozen (locked decision 4) — point at the new view. */}
- <a
- href="?mode=architecture"
- className="shrink-0 rounded-full border border-[var(--color-accent-primary,#f59520)]/50 bg-[var(--color-accent-primary,#f59520)]/10 px-3 py-1 text-xs text-[var(--color-accent-primary,#f59520)] hover:bg-[var(--color-accent-primary,#f59520)]/20"
- >
- Try the new architecture view →
- </a>
- </div>
- </div>
- <div className="flex-1 min-h-0">
- <C4Diagram
- level={level}
- activeContainerId={activeContainerId}
- systemName={repoName}
- l1View={l1View}
- l2View={l2View}
- l3View={l3View}
- loading={loading}
- error={error}
- onLevelChange={setLevel}
- onDrillInto={drillInto}
- onDrillOut={drillOut}
- docsPathSet={docsPathSet}
- fetchMermaid={fetchMermaid}
- renderInspector={({ data, onClose, onDrillIn }) => (
- <C4DetailPanelHost
- repoId={repoId}
- data={data}
- pageIdByPath={pageIdByPath}
- onClose={onClose}
- onDrillIn={onDrillIn}
- />
- )}
- />
- </div>
- </>
- );
+import { redirect } from "next/navigation";
+
+/** Legacy route — the knowledge graph now lives under Architecture. */
+export default async function LegacyC4Redirect({
+ params,
+ searchParams,
+}: {
+ params: Promise<{ id: string }>;
+ searchParams: Promise<Record<string, string | string[] | undefined>>;
+}) {
+ const { id } = await params;
+ const sp = await searchParams;
+ const qs = new URLSearchParams({ view: "c4" });
+ for (const [key, value] of Object.entries(sp)) {
+ if (typeof value !== "string") continue;
+ // The c4 view's own "view" param (overview/groups/detail) was renamed to
+ // "c4view" when the page moved under Architecture.
+ if (key === "view") qs.set("c4view", value);
+ else qs.set(key, value);
+ }
+ redirect(`/repos/${id}/architecture?${qs.toString()}`);
}
diff --git a/packages/web/src/app/repos/[id]/chat/page.tsx b/packages/web/src/app/repos/[id]/chat/page.tsx
new file mode 100644
index 000000000..b92e99dd6
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/chat/page.tsx
@@ -0,0 +1,69 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { Hash } from "lucide-react";
+import { getRepo } from "@/lib/api/repos";
+import { Badge } from "@repowise-dev/ui/ui/badge";
+import { ChatInterface } from "@/components/chat/chat-interface";
+
+interface Props {
+ params: Promise<{ id: string }>;
+ searchParams: Promise<{ q?: string }>;
+}
+
+export async function generateMetadata({ params }: Props): Promise<Metadata> {
+ const { id } = await params;
+ try {
+ const repo = await getRepo(id);
+ return { title: `${repo.name} — Chat` };
+ } catch {
+ return { title: "Repository" };
+ }
+}
+
+export default async function RepoChatPage({ params, searchParams }: Props) {
+ const { id } = await params;
+ const { q } = await searchParams;
+
+ let repo;
+ try {
+ repo = await getRepo(id);
+ } catch {
+ notFound();
+ }
+
+ return (
+ <div className="flex flex-col h-full">
+ {/* Compact header */}
+ <div className="px-4 pt-3 pb-2 flex items-center justify-between shrink-0 border-b border-[var(--color-border-default)]">
+ <div className="min-w-0">
+ <h1 className="text-sm font-semibold text-[var(--color-text-primary)] truncate">
+ {repo.name}
+ </h1>
+ <p className="text-[10px] font-mono text-[var(--color-text-tertiary)] truncate">
+ {repo.local_path}
+ </p>
+ </div>
+ <div className="flex items-center gap-1.5 shrink-0 ml-3">
+ {repo.head_commit && (
+ <Badge variant="outline" className="text-[10px] h-5">
+ <Hash className="h-2.5 w-2.5" />
+ {repo.head_commit.slice(0, 7)}
+ </Badge>
+ )}
+ <Badge variant="outline" className="text-[10px] h-5">
+ {repo.default_branch}
+ </Badge>
+ </div>
+ </div>
+
+ {/* Chat interface fills remaining height */}
+ <div className="flex-1 min-h-0">
+ <ChatInterface
+ repoId={id}
+ repoName={repo.name}
+ {...(q ? { initialQuestion: q } : {})}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/app/repos/[id]/code-health/coverage/page.tsx b/packages/web/src/app/repos/[id]/code-health/coverage/page.tsx
new file mode 100644
index 000000000..c78aeef90
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/code-health/coverage/page.tsx
@@ -0,0 +1,11 @@
+import { redirect } from "next/navigation";
+
+/** Coverage is a tab of the consolidated Code Health section now. */
+export default async function LegacyRedirect({
+ params,
+}: {
+ params: Promise<{ id: string }>;
+}) {
+ const { id } = await params;
+ redirect(`/repos/${id}/code-health?tab=coverage`);
+}
diff --git a/packages/web/src/app/repos/[id]/code-health/page.tsx b/packages/web/src/app/repos/[id]/code-health/page.tsx
new file mode 100644
index 000000000..14f3b53a6
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/code-health/page.tsx
@@ -0,0 +1,156 @@
+"use client";
+
+/**
+ * Code Health — `/repos/[id]/code-health`.
+ *
+ * One "what do I fix next" section: Triage (the ranked fix-next queue),
+ * Hotspots & Churn (the only place called "hotspots"), Modules, Coverage,
+ * Dead code, Impact, Security, and Trend — one chrome, one tab row,
+ * URL-synced via `?tab=`.
+ */
+
+import { useParams, useRouter, useSearchParams } from "next/navigation";
+import { useCallback } from "react";
+import useSWR from "swr";
+import { HeartPulse, RotateCw } from "lucide-react";
+import {
+ Tabs,
+ TabsContent,
+ ScrollableTabsList,
+ TabsTrigger,
+} from "@repowise-dev/ui/ui/tabs";
+import { Button } from "@repowise-dev/ui/ui/button";
+import { TriageTab } from "@/components/code-health/triage-tab";
+import { CoverageTab } from "@/components/code-health/coverage-tab";
+import { TrendTab } from "@/components/code-health/trend-tab";
+import { HotspotsTab } from "@/components/risk/hotspots-tab";
+import { DeadCodeTab } from "@/components/risk/dead-code-tab";
+import { ImpactTab } from "@/components/risk/impact-tab";
+import { ModulesTab } from "@/components/risk/modules-tab";
+import { SecurityTab } from "@/components/risk/security-tab";
+import { RiskSummaryStrip } from "@/components/risk/risk-summary-strip";
+import {
+ getHealthOverview,
+ type HealthOverviewResponse,
+} from "@/lib/api/code-health";
+
+const TABS = [
+ "triage",
+ "hotspots",
+ "modules",
+ "coverage",
+ "dead-code",
+ "impact",
+ "security",
+ "trend",
+] as const;
+type TabId = (typeof TABS)[number];
+
+/** Legacy tab ids from the old /risk page → their new home. */
+const TAB_ALIASES: Record<string, TabId> = {
+ heatmap: "hotspots",
+};
+
+/** Tabs that came from the Risk page and share the summary strip. */
+const STRIP_TABS = new Set<TabId>(["hotspots", "modules", "dead-code", "impact", "security"]);
+
+export default function CodeHealthPage() {
+ const params = useParams<{ id: string }>();
+ const router = useRouter();
+ const searchParams = useSearchParams();
+ const repoId = params.id;
+
+ const rawTab = searchParams.get("tab");
+ const aliased = rawTab ? TAB_ALIASES[rawTab] : undefined;
+ const activeTab: TabId =
+ aliased ??
+ (rawTab && (TABS as readonly string[]).includes(rawTab) ? (rawTab as TabId) : "triage");
+
+ // Shares the SWR key with TriageTab — the meta line costs no extra request.
+ const { data: overview, mutate } = useSWR<HealthOverviewResponse>(
+ `code-health-overview:${repoId}`,
+ () => getHealthOverview(repoId, 25),
+ { revalidateOnFocus: false },
+ );
+ const meta = overview?.meta;
+
+ const setTab = useCallback(
+ (next: string) => {
+ const sp = new URLSearchParams(searchParams.toString());
+ if (next === "triage") sp.delete("tab");
+ else sp.set("tab", next);
+ const qs = sp.toString();
+ router.replace(qs ? `?${qs}` : "?", { scroll: false });
+ },
+ [router, searchParams],
+ );
+
+ return (
+ <div className="p-4 sm:p-6 space-y-4 max-w-[1600px]">
+ <header className="flex flex-wrap items-start gap-3">
+ <div className="min-w-0 flex-1 space-y-1">
+ <h1 className="flex items-center gap-2 text-lg font-semibold text-[var(--color-text-primary)]">
+ <HeartPulse className="h-5 w-5 text-[var(--color-success)]" />
+ Code Health
+ </h1>
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ Per-file health scores from complexity, duplication, coverage, churn,
+ and ownership biomarkers — ranked into a fix-next queue.
+ </p>
+ {meta ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ {meta.last_indexed_at
+ ? `Indexed ${new Date(meta.last_indexed_at).toLocaleString()}`
+ : "Not indexed yet"}
+ {meta.head_commit ? ` · ${meta.head_commit.slice(0, 8)}` : ""}
+ {` · ${meta.snapshot_count} snapshot${meta.snapshot_count === 1 ? "" : "s"}`}
+ </p>
+ ) : null}
+ </div>
+ <Button size="sm" variant="outline" onClick={() => mutate()}>
+ <RotateCw className="h-3.5 w-3.5 mr-1.5" /> Refresh
+ </Button>
+ </header>
+
+ <Tabs value={activeTab} onValueChange={setTab} className="space-y-4">
+ <ScrollableTabsList>
+ <TabsTrigger value="triage">Triage</TabsTrigger>
+ <TabsTrigger value="hotspots">Hotspots &amp; churn</TabsTrigger>
+ <TabsTrigger value="modules">Modules</TabsTrigger>
+ <TabsTrigger value="coverage">Coverage</TabsTrigger>
+ <TabsTrigger value="dead-code">Dead code</TabsTrigger>
+ <TabsTrigger value="impact">Impact</TabsTrigger>
+ <TabsTrigger value="security">Security</TabsTrigger>
+ <TabsTrigger value="trend">Trend</TabsTrigger>
+ </ScrollableTabsList>
+
+ {STRIP_TABS.has(activeTab) && <RiskSummaryStrip repoId={repoId} />}
+
+ <TabsContent value="triage" className="space-y-6">
+ <TriageTab repoId={repoId} />
+ </TabsContent>
+ <TabsContent value="hotspots" className="space-y-6">
+ <HotspotsTab repoId={repoId} />
+ </TabsContent>
+ <TabsContent value="modules" className="space-y-6">
+ <ModulesTab repoId={repoId} />
+ </TabsContent>
+ <TabsContent value="coverage" className="space-y-6">
+ <CoverageTab repoId={repoId} />
+ </TabsContent>
+ <TabsContent value="dead-code" className="space-y-6">
+ <DeadCodeTab repoId={repoId} />
+ </TabsContent>
+ <TabsContent value="impact" className="space-y-6">
+ <ImpactTab repoId={repoId} />
+ </TabsContent>
+ <TabsContent value="security" className="space-y-6">
+ <SecurityTab repoId={repoId} />
+ </TabsContent>
+ <TabsContent value="trend" className="space-y-6">
+ <TrendTab repoId={repoId} />
+ </TabsContent>
+ </Tabs>
+ </div>
+ );
+}
diff --git a/packages/web/src/app/repos/[id]/code-health/refactoring-targets/page.tsx b/packages/web/src/app/repos/[id]/code-health/refactoring-targets/page.tsx
new file mode 100644
index 000000000..4286dee69
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/code-health/refactoring-targets/page.tsx
@@ -0,0 +1,11 @@
+import { redirect } from "next/navigation";
+
+/** The refactoring-target ranking merged into the Triage fix-next queue. */
+export default async function LegacyRedirect({
+ params,
+}: {
+ params: Promise<{ id: string }>;
+}) {
+ const { id } = await params;
+ redirect(`/repos/${id}/code-health`);
+}
diff --git a/packages/web/src/app/repos/[id]/code-health/trend/page.tsx b/packages/web/src/app/repos/[id]/code-health/trend/page.tsx
new file mode 100644
index 000000000..fffdc28ca
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/code-health/trend/page.tsx
@@ -0,0 +1,11 @@
+import { redirect } from "next/navigation";
+
+/** Trend is a tab of the consolidated Code Health section now. */
+export default async function LegacyRedirect({
+ params,
+}: {
+ params: Promise<{ id: string }>;
+}) {
+ const { id } = await params;
+ redirect(`/repos/${id}/code-health?tab=trend`);
+}
diff --git a/packages/web/src/app/repos/[id]/costs/page.tsx b/packages/web/src/app/repos/[id]/costs/page.tsx
index 1ebb823e9..f9c70a0ed 100644
--- a/packages/web/src/app/repos/[id]/costs/page.tsx
+++ b/packages/web/src/app/repos/[id]/costs/page.tsx
@@ -15,9 +15,8 @@ import {
import { StatCard } from "@repowise-dev/ui/shared/stat-card";
import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-import { Tabs, TabsList, TabsTrigger, TabsContent } from "@repowise-dev/ui/ui/tabs";
+import { Tabs, ScrollableTabsList, TabsTrigger, TabsContent } from "@repowise-dev/ui/ui/tabs";
import {
- CacheHitRatioCard,
CostHeatmap,
DistillSavingsCard,
ProviderComparison,
@@ -30,7 +29,7 @@ import { formatCost, formatNumber, formatTokens } from "@repowise-dev/ui/lib/for
export default function CostsPage() {
const params = useParams<{ id: string }>();
const id = params.id;
- const [tab, setTab] = useState("operations");
+ const [tab, setTab] = useState("daily");
const { data: summary, isLoading: loadingSummary } = useSWR<CostSummary>(
`costs-summary:${id}`,
@@ -79,13 +78,13 @@ export default function CostsPage() {
<DistillSavingsCard data={distillSavings} />
<Tabs value={tab} onValueChange={setTab} className="w-full">
- <TabsList>
- <TabsTrigger value="operations">Spend by operation</TabsTrigger>
+ <ScrollableTabsList>
<TabsTrigger value="daily">Daily</TabsTrigger>
+ <TabsTrigger value="operations">Spend by operation</TabsTrigger>
<TabsTrigger value="providers">Providers</TabsTrigger>
<TabsTrigger value="hotspots">Hotspots</TabsTrigger>
- <TabsTrigger value="cache">Cache</TabsTrigger>
- </TabsList>
+ <TabsTrigger value="efficiency">Efficiency</TabsTrigger>
+ </ScrollableTabsList>
<TabsContent value="daily" className="mt-4">
<Card>
@@ -143,9 +142,11 @@ export default function CostsPage() {
</Card>
</TabsContent>
- <TabsContent value="cache" className="mt-4">
+ {/* Cache analytics aren't wired to real data yet — the placeholder
+ CacheHitRatioCard is cut rather than shown empty; the tab keeps
+ the real per-call efficiency numbers. */}
+ <TabsContent value="efficiency" className="mt-4">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
- <CacheHitRatioCard />
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm">Token efficiency</CardTitle>
diff --git a/packages/web/src/app/repos/[id]/dead-code/loading.tsx b/packages/web/src/app/repos/[id]/dead-code/loading.tsx
deleted file mode 100644
index e38e0ba07..000000000
--- a/packages/web/src/app/repos/[id]/dead-code/loading.tsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";
-
-export default function DeadCodeLoading() {
- return <OwlLoader />;
-}
diff --git a/packages/web/src/app/repos/[id]/dead-code/page.tsx b/packages/web/src/app/repos/[id]/dead-code/page.tsx
index b7dcd472e..8767d9f5a 100644
--- a/packages/web/src/app/repos/[id]/dead-code/page.tsx
+++ b/packages/web/src/app/repos/[id]/dead-code/page.tsx
@@ -1,86 +1,11 @@
-"use client";
-
-import { useState } from "react";
-import useSWR from "swr";
-import { useParams } from "next/navigation";
-import { Trash2 } from "lucide-react";
-import { RoutedToRiskBanner } from "@/components/risk/routed-to-risk-banner";
-import { toast } from "sonner";
-import { Button } from "@repowise-dev/ui/ui/button";
-import { SummaryBar } from "@repowise-dev/ui/dead-code/summary-bar";
-import { FindingsTable } from "@/components/dead-code/findings-table";
-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-import { getDeadCodeSummary, analyzeDeadCode } from "@/lib/api/dead-code";
-import type { DeadCodeSummaryResponse } from "@/lib/api/types";
-
-export default function DeadCodePage() {
- const params = useParams<{ id: string }>();
- const id = params.id;
- const [analyzing, setAnalyzing] = useState(false);
-
- const { data: summary, isLoading: loadingSummary, error: summaryError, mutate: mutateSummary } = useSWR<DeadCodeSummaryResponse>(
- `dead-code-summary:${id}`,
- () => getDeadCodeSummary(id),
- { revalidateOnFocus: false },
- );
-
- const handleAnalyze = async () => {
- setAnalyzing(true);
- try {
- await analyzeDeadCode(id);
- toast.success("Analysis started — results will appear shortly.");
- } catch (err) {
- toast.error(
- err instanceof Error ? `Couldn't start analysis: ${err.message}` : "Couldn't start analysis",
- );
- } finally {
- setAnalyzing(false);
- }
- };
-
- return (
- <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">
- <RoutedToRiskBanner repoId={id} tab="dead-code" />
- <div className="flex flex-wrap items-start justify-between gap-4">
- <div>
- <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 flex items-center gap-2">
- <Trash2 className="h-5 w-5 text-red-500" />
- Dead Code
- </h1>
- <p className="text-sm text-[var(--color-text-secondary)]">
- Unused files, exports, and zombie packages.
- </p>
- </div>
- <div className="flex items-center gap-3">
- <Button
- size="sm"
- variant="outline"
- onClick={handleAnalyze}
- disabled={analyzing}
- >
- {analyzing ? "Starting…" : "Analyze"}
- </Button>
- </div>
- </div>
-
- {loadingSummary ? (
- <div className="grid grid-cols-4 gap-3">
- {Array.from({ length: 4 }).map((_, i) => (
- <Skeleton key={i} className="h-24 w-full rounded-lg" />
- ))}
- </div>
- ) : summary ? (
- <SummaryBar summary={summary} />
- ) : summaryError ? (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)] flex items-center justify-between gap-2">
- <span>Couldn&apos;t load summary.</span>
- <Button size="sm" variant="outline" onClick={() => mutateSummary()}>
- Retry
- </Button>
- </div>
- ) : null}
-
- <FindingsTable repoId={id} />
- </div>
- );
+import { redirect } from "next/navigation";
+
+/** Legacy route — redirects into the consolidated IA. */
+export default async function LegacyRedirect({
+ params,
+}: {
+ params: Promise<{ id: string }>;
+}) {
+ const { id } = await params;
+ redirect(`/repos/${id}/code-health?tab=dead-code`);
}
diff --git a/packages/web/src/app/repos/[id]/decisions/page.tsx b/packages/web/src/app/repos/[id]/decisions/page.tsx
index 5aff49c78..91d19543a 100644
--- a/packages/web/src/app/repos/[id]/decisions/page.tsx
+++ b/packages/web/src/app/repos/[id]/decisions/page.tsx
@@ -34,8 +34,10 @@ export default async function DecisionsPage({ params }: Props) {
Why the codebase is built the way it is — constraints, tradeoffs, and rejected alternatives.
</p>
</div>
- <DecisionGraphWrapper repoId={repoId} />
+ {/* The table is the workhorse; the relationship graph is secondary and
+ collapsed below it. */}
<DecisionsTableWrapper repoId={repoId} initialData={decisions} />
+ <DecisionGraphWrapper repoId={repoId} />
</div>
);
}
diff --git a/packages/web/src/app/repos/[id]/docs/coverage/page.tsx b/packages/web/src/app/repos/[id]/docs/coverage/page.tsx
index 3a6111115..72913bf7e 100644
--- a/packages/web/src/app/repos/[id]/docs/coverage/page.tsx
+++ b/packages/web/src/app/repos/[id]/docs/coverage/page.tsx
@@ -9,7 +9,7 @@ import { StatCard } from "@repowise-dev/ui/shared/stat-card";
import { listPages } from "@/lib/api/pages";
import { formatNumber } from "@repowise-dev/ui/lib/format";
-export const metadata: Metadata = { title: "Coverage" };
+export const metadata: Metadata = { title: "Doc freshness" };
export default async function CoveragePage({
params,
diff --git a/packages/web/src/app/repos/[id]/files/[...path]/loading.tsx b/packages/web/src/app/repos/[id]/files/[...path]/loading.tsx
new file mode 100644
index 000000000..18ce2146f
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/files/[...path]/loading.tsx
@@ -0,0 +1,16 @@
+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+
+export default function FilePageLoading() {
+ return (
+ <div className="p-4 sm:p-6 max-w-[1200px] space-y-4">
+ <Skeleton className="h-6 w-2/3" />
+ <div className="flex gap-2">
+ <Skeleton className="h-6 w-14" />
+ <Skeleton className="h-6 w-20" />
+ <Skeleton className="h-6 w-24" />
+ </div>
+ <Skeleton className="h-9 w-96" />
+ <Skeleton className="h-96 w-full" />
+ </div>
+ );
+}
diff --git a/packages/web/src/app/repos/[id]/files/[...path]/page.tsx b/packages/web/src/app/repos/[id]/files/[...path]/page.tsx
new file mode 100644
index 000000000..30310b031
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/files/[...path]/page.tsx
@@ -0,0 +1,102 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { codeToHtml } from "shiki";
+import { getFileContent, getFileDetail } from "@/lib/api/files";
+import { WikiRenderer } from "@/components/wiki/wiki-renderer";
+import { FilePageHost } from "@/components/files/file-page-host";
+import { FILE_PAGE_TABS, type FilePageTab } from "@repowise-dev/ui/files";
+import type { FileDetailResponse } from "@repowise-dev/types/files";
+
+interface Props {
+ params: Promise<{ id: string; path: string[] }>;
+ searchParams: Promise<{ tab?: string }>;
+}
+
+export async function generateMetadata({ params }: Props): Promise<Metadata> {
+ const { path } = await params;
+ const filePath = path.map(decodeURIComponent).join("/");
+ return { title: filePath.split("/").pop() ?? filePath };
+}
+
+/** Best-effort shiki render of the file with per-line coverage attributes.
+ * Returns undefined when the source can't be fetched or highlighted —
+ * the Coverage tab falls back to the summary-only view. */
+async function renderCoverageCode(
+ repoId: string,
+ filePath: string,
+ detail: FileDetailResponse,
+): Promise<string | undefined> {
+ if (!detail.coverage || detail.coverage.covered_lines.length === 0) return undefined;
+ let content: string;
+ try {
+ content = await getFileContent(repoId, filePath);
+ } catch {
+ return undefined;
+ }
+ // Guard against pathological files: line-decorated shiki output for very
+ // large sources costs memory on every request.
+ if (content.length > 400_000) return undefined;
+ const covered = new Set(detail.coverage.covered_lines);
+ const lang = detail.graph?.language?.toLowerCase() || "text";
+ const highlight = (language: string) =>
+ codeToHtml(content, {
+ lang: language as Parameters<typeof codeToHtml>[1]["lang"],
+ themes: { light: "github-light", dark: "vesper" },
+ defaultColor: false,
+ transformers: [
+ {
+ line(node, line) {
+ if (covered.has(line)) node.properties["data-covered"] = "y";
+ },
+ },
+ ],
+ });
+ try {
+ return await highlight(lang);
+ } catch {
+ try {
+ return await highlight("text");
+ } catch {
+ return undefined;
+ }
+ }
+}
+
+export default async function FileEntityPage({ params, searchParams }: Props) {
+ const { id, path } = await params;
+ const { tab } = await searchParams;
+ const filePath = path.map(decodeURIComponent).join("/");
+
+ let detail: FileDetailResponse;
+ try {
+ detail = await getFileDetail(id, filePath);
+ } catch {
+ notFound();
+ }
+
+ const coverageCodeHtml = await renderCoverageCode(id, filePath, detail);
+ const initialTab =
+ tab && (FILE_PAGE_TABS as readonly string[]).includes(tab)
+ ? (tab as FilePageTab)
+ : undefined;
+
+ const docSlot = detail.wiki_page ? (
+ <WikiRenderer content={detail.wiki_page.content} repoId={id} />
+ ) : undefined;
+ const wikiHref = detail.wiki_page
+ ? `/repos/${id}/wiki/${encodeURIComponent(detail.wiki_page.id)}`
+ : undefined;
+
+ return (
+ <div className="p-4 sm:p-6 max-w-[1200px]">
+ <FilePageHost
+ repoId={id}
+ data={detail}
+ docSlot={docSlot}
+ coverageCodeHtml={coverageCodeHtml}
+ wikiHref={wikiHref}
+ initialTab={initialTab}
+ />
+ </div>
+ );
+}
diff --git a/packages/web/src/app/repos/[id]/graph/loading.tsx b/packages/web/src/app/repos/[id]/graph/loading.tsx
deleted file mode 100644
index 6fe318ef8..000000000
--- a/packages/web/src/app/repos/[id]/graph/loading.tsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";
-
-export default function GraphLoading() {
- return <OwlLoader />;
-}
diff --git a/packages/web/src/app/repos/[id]/graph/page.tsx b/packages/web/src/app/repos/[id]/graph/page.tsx
index 6b137e6d8..4c5af468a 100644
--- a/packages/web/src/app/repos/[id]/graph/page.tsx
+++ b/packages/web/src/app/repos/[id]/graph/page.tsx
@@ -1,149 +1,18 @@
-"use client";
+import { redirect } from "next/navigation";
-import { use, useCallback, useState } from "react";
-import useSWR from "swr";
-import { useQueryState } from "nuqs";
-import { useSearchParams } from "next/navigation";
-import { GraphFlow } from "@/components/graph/graph-flow";
-import { GraphDocPanel } from "@/components/graph/graph-doc-panel";
-import { GraphTruncationBanner } from "@repowise-dev/ui/graph/graph-truncation-banner";
-import { getGraph } from "@/lib/api/graph";
-import type { GraphExportResponse } from "@/lib/api/types";
-
-type ViewMode = "module" | "full" | "architecture" | "dead" | "hotfiles" | "unified";
-
-const VALID_VIEW_MODES = new Set<ViewMode>([
- "module",
- "full",
- "architecture",
- "dead",
- "hotfiles",
- "unified",
-]);
-
-// Scopes that render their own dedicated endpoint and therefore never touch the
-// capped full-graph endpoint (`/api/graph`). The constellation ("architecture")
-// and the module browser fetch their own graphs, so the page must NOT eagerly
-// fetch the full graph — nor show its truncation banner — for these scopes.
-const SCOPES_WITHOUT_FULL_GRAPH = new Set<ViewMode>(["architecture", "module"]);
-
-export default function GraphPage({
+/** Legacy route — the dependency graph now lives under Architecture. */
+export default async function LegacyGraphRedirect({
params,
+ searchParams,
}: {
params: Promise<{ id: string }>;
+ searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
- const { id: repoId } = use(params);
- const searchParams = useSearchParams();
-
- const viewModeParam = searchParams.get("viewMode");
- const initialViewMode = VALID_VIEW_MODES.has((viewModeParam ?? "") as ViewMode)
- ? (viewModeParam as ViewMode)
- : undefined;
- const initialNode = searchParams.get("node");
-
- const [, setSelectedNode] = useQueryState("node");
- const [docNodeId, setDocNodeId] = useState<string | null>(null);
- const [graphLimit, setGraphLimit] = useState<number | undefined>(undefined);
-
- // Track the live scope so we only fetch the capped full graph (and render its
- // truncation banner) for scopes that actually use it. Constellation
- // ("architecture") is the default, and — like "module" — fetches its own
- // endpoint inside GraphFlow, so the page must stay off /api/graph there.
- // A pinned node forces the "full" scope (see initialViewMode below).
- const [viewMode, setViewMode] = useState<ViewMode>(
- initialNode ? "full" : initialViewMode ?? "architecture",
- );
- const usesFullGraph = !SCOPES_WITHOUT_FULL_GRAPH.has(viewMode);
-
- const { data: graphData } = useSWR<GraphExportResponse>(
- usesFullGraph ? `graph:${repoId}:${graphLimit ?? "default"}` : null,
- () => getGraph(repoId, graphLimit),
- { revalidateOnFocus: false, revalidateOnReconnect: false },
- );
-
- // Click a file node → open doc panel
- const handleNodeClick = useCallback(
- (nodeId: string, nodeType: string) => {
- // Module clicks are handled inside GraphFlow (drill-down)
- // File clicks open the doc panel
- if (nodeType !== "moduleGroup") {
- setDocNodeId((prev) => (prev === nodeId ? null : nodeId));
- void setSelectedNode(nodeId);
- }
- },
- [setSelectedNode],
- );
-
- // Double click or context menu "View Docs"
- const handleNodeViewDocs = useCallback(
- (nodeId: string) => {
- setDocNodeId((prev) => (prev === nodeId ? null : nodeId));
- void setSelectedNode(nodeId);
- },
- [setSelectedNode],
- );
-
- // When the community panel opens from the legend, dismiss the doc panel
- // so the two never stack on the right rail. Single-sidebar UX.
- const handleCommunityPanelOpen = useCallback(() => {
- setDocNodeId(null);
- }, []);
-
- return (
- <div className="flex flex-col h-full">
- {/* 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)]">
- Dependency Graph
- </h1>
- <p className="text-xs text-[var(--color-text-secondary)] mt-0.5">
- Explore dependencies and trace paths between files
- </p>
- </div>
-
- {/* Truncation banner — shown only when the current scope renders the
- capped full graph and the server actually capped it. Constellation /
- module scopes use their own endpoints, so the banner stays hidden. */}
- {usesFullGraph && graphData?.truncated && graphData.total_node_count != null && (
- <div className="shrink-0 px-4 sm:px-6 pt-3">
- <GraphTruncationBanner
- shown={graphData.nodes.length}
- total={graphData.total_node_count}
- limit={graphLimit ?? graphData.nodes.length}
- onLoadMore={(nextLimit) => setGraphLimit(nextLimit)}
- onSwitchToArchitecture={() => {
- const url = new URL(window.location.href);
- url.searchParams.set("viewMode", "architecture");
- window.history.replaceState({}, "", url.toString());
- window.location.reload();
- }}
- />
- </div>
- )}
-
- {/* Graph area */}
- <div className="flex-1 overflow-hidden p-3">
- <div className="h-full w-full rounded-lg border border-[var(--color-border-default)] overflow-hidden relative">
- <GraphFlow
- repoId={repoId}
- initialViewMode={initialNode ? "full" : initialViewMode}
- initialSelectedNode={initialNode}
- onNodeClick={handleNodeClick}
- onNodeViewDocs={handleNodeViewDocs}
- onCommunityPanelOpen={handleCommunityPanelOpen}
- onViewModeChange={setViewMode}
- />
-
- {/* Doc panel — shows on file click. Single right-rail surface. */}
- {docNodeId && (
- <GraphDocPanel
- repoId={repoId}
- nodeId={docNodeId}
- onClose={() => setDocNodeId(null)}
- />
- )}
- </div>
- </div>
- </div>
- );
+ const { id } = await params;
+ const sp = await searchParams;
+ const qs = new URLSearchParams({ view: "graph" });
+ for (const [key, value] of Object.entries(sp)) {
+ if (typeof value === "string" && key !== "view") qs.set(key, value);
+ }
+ redirect(`/repos/${id}/architecture?${qs.toString()}`);
}
diff --git a/packages/web/src/app/repos/[id]/health/coverage/page.tsx b/packages/web/src/app/repos/[id]/health/coverage/page.tsx
index 09a06b2e9..2fb53aa5f 100644
--- a/packages/web/src/app/repos/[id]/health/coverage/page.tsx
+++ b/packages/web/src/app/repos/[id]/health/coverage/page.tsx
@@ -1,372 +1,11 @@
-"use client";
+import { redirect } from "next/navigation";
-import { useMemo, useState } from "react";
-import { ArrowUpRight, Sparkles, TestTubeDiagonal } from "lucide-react";
-import { useParams } from "next/navigation";
-import useSWR from "swr";
-
-import {
- AiPromptModal,
- CoverageBar,
- ModuleCoverageList,
- UntestedHotspotWarning,
- RiskCoverageScatter,
- buildCoverageAiPrompt,
- scoreBadgeClass,
- type CoverageFilePromptInput,
-} from "@repowise-dev/ui/health";
-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-
-import {
- getHealthCoverage,
- type HealthCoverageResponse,
- getHealthOverview,
- type HealthOverviewResponse,
-} from "@/lib/api/code-health";
-import { HealthPageChrome } from "@/components/health/health-page-chrome";
-import { HealthFileDrawerHost } from "@/components/health/health-file-drawer-host";
-
-export default function HealthCoveragePage() {
- const params = useParams<{ id: string }>();
- const id = params.id;
- const [selectedFile, setSelectedFile] = useState<string | null>(null);
- const [promptRow, setPromptRow] = useState<CoverageFilePromptInput | null>(null);
-
- const { data, isLoading, error } = useSWR<HealthCoverageResponse>(
- `code-health-coverage:${id}`,
- () => getHealthCoverage(id, { limit: 1000 }),
- { revalidateOnFocus: false },
- );
-
- const { data: overview } = useSWR<HealthOverviewResponse>(
- `code-health-overview:${id}`,
- () => getHealthOverview(id, 25),
- { revalidateOnFocus: false },
- );
-
- return (
- <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">
- <HealthPageChrome
- repoId={id}
- active="coverage"
- title="Test Coverage"
- icon={<TestTubeDiagonal className="h-5 w-5 text-emerald-500" />}
- subtitle={
- <>
- Ingest LCOV / Cobertura / Clover with{" "}
- <code className="px-1 rounded bg-[var(--color-bg-muted)]">
- repowise health --coverage &lt;path&gt;
- </code>
- </>
- }
- meta={overview?.meta}
- />
-
- {isLoading ? (
- <CoverageSkeleton />
- ) : error ? (
- <p className="text-sm text-red-500">Failed to load coverage data.</p>
- ) : !data || data.summary.file_count === 0 ? (
- <EmptyState />
- ) : (
- <CoverageView
- data={data}
- onSelect={(p) => setSelectedFile(p)}
- selectedFile={selectedFile}
- onGeneratePrompt={(r) => setPromptRow(r)}
- />
- )}
-
- <HealthFileDrawerHost
- repoId={id}
- filePath={selectedFile}
- onClose={() => setSelectedFile(null)}
- />
-
- <AiPromptModal
- open={promptRow !== null}
- onOpenChange={(open) => {
- if (!open) setPromptRow(null);
- }}
- filePath={promptRow?.file_path}
- title="AI test prompt"
- description="A ready-to-paste prompt that asks your AI coding agent to add tests for this file's uncovered lines and branches."
- getPrompt={
- promptRow
- ? (flavor) => buildCoverageAiPrompt({ row: promptRow, flavor })
- : null
- }
- />
- </div>
- );
-}
-
-function CoverageView({
- data,
- onSelect,
- selectedFile,
- onGeneratePrompt,
+/** Legacy route — redirects into the consolidated IA. */
+export default async function LegacyRedirect({
+ params,
}: {
- data: HealthCoverageResponse;
- onSelect: (path: string) => void;
- selectedFile: string | null;
- onGeneratePrompt: (row: CoverageFilePromptInput) => void;
+ params: Promise<{ id: string }>;
}) {
- const { summary, files, modules } = data;
- const [search, setSearch] = useState("");
-
- // Only flag a file as "untested hotspot" when it actually has coverage
- // data — defaulting missing coverage to 100% would hide the genuinely
- // uncovered files. We pair the health score and coverage so the chip
- // only fires on real risk-and-uncovered overlap.
- const untested = useMemo(
- () =>
- files
- .filter(
- (f) =>
- f.line_coverage_pct != null &&
- f.line_coverage_pct < 30 &&
- (f.health_score == null || f.health_score < 6),
- )
- .slice(0, 10)
- .map((f) => ({
- file_path: f.file_path,
- line_coverage_pct: f.line_coverage_pct,
- health_score: f.health_score,
- })),
- [files],
- );
-
- const scatterPoints = useMemo(
- () =>
- files
- .filter((f) => f.health_score != null && f.line_coverage_pct != null)
- .map((f) => ({
- file_path: f.file_path,
- health_score: f.health_score!,
- line_coverage_pct: f.line_coverage_pct,
- nloc: f.nloc ?? 0,
- })),
- [files],
- );
-
- const filteredFiles = useMemo(() => {
- if (!search) return files;
- const s = search.toLowerCase();
- return files.filter((f) => f.file_path.toLowerCase().includes(s));
- }, [files, search]);
-
- return (
- <div className="space-y-6">
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-4">
- <SummaryCard label="Files">
- <span className="text-2xl font-bold tabular-nums text-[var(--color-text-primary)]">
- {summary.file_count.toLocaleString()}
- </span>
- </SummaryCard>
- <SummaryCard label="Line coverage">
- <span className="text-2xl font-bold tabular-nums text-[var(--color-text-primary)]">
- {summary.line_coverage_pct == null
- ? "—"
- : `${summary.line_coverage_pct.toFixed(1)}%`}
- </span>
- <p className="text-xs text-[var(--color-text-tertiary)] mt-1 tabular-nums">
- {summary.covered_lines.toLocaleString()} /{" "}
- {summary.total_lines.toLocaleString()} lines
- </p>
- </SummaryCard>
- <SummaryCard label="Branch coverage">
- <span className="text-2xl font-bold tabular-nums text-[var(--color-text-primary)]">
- {summary.branch_coverage_pct == null
- ? "—"
- : `${summary.branch_coverage_pct.toFixed(1)}%`}
- </span>
- </SummaryCard>
- <SummaryCard label="Source">
- <span className="text-lg font-semibold text-[var(--color-text-primary)] uppercase">
- {summary.source_format ?? "—"}
- </span>
- <p className="text-xs text-[var(--color-text-tertiary)] mt-1">
- {summary.ingested_at ? new Date(summary.ingested_at).toLocaleString() : "never"}
- </p>
- </SummaryCard>
- </div>
-
- <RiskCoverageScatter points={scatterPoints} onSelect={(p) => onSelect(p.file_path)} />
-
- {untested.length > 0 ? <UntestedHotspotWarning entries={untested} /> : null}
-
- <section className="space-y-2">
- <h2 className="text-sm font-semibold text-[var(--color-text-primary)]">
- Module coverage ({modules.length})
- </h2>
- <ModuleCoverageList modules={modules} />
- </section>
-
- <section className="space-y-2">
- <div className="flex items-center gap-2">
- <h2 className="text-sm font-semibold text-[var(--color-text-primary)] mr-auto">
- Files ({filteredFiles.length.toLocaleString()})
- </h2>
- <input
- value={search}
- onChange={(e) => setSearch(e.target.value)}
- placeholder="Filter path…"
- className="text-xs px-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-56 focus:outline-none focus:border-[var(--color-border-strong)]"
- />
- </div>
- <FileCoverageTable
- files={filteredFiles}
- onSelect={onSelect}
- selectedFile={selectedFile}
- onGeneratePrompt={onGeneratePrompt}
- />
- </section>
- </div>
- );
-}
-
-function FileCoverageTable({
- files,
- onSelect,
- selectedFile,
- onGeneratePrompt,
-}: {
- files: HealthCoverageResponse["files"];
- onSelect: (path: string) => void;
- selectedFile: string | null;
- onGeneratePrompt: (row: CoverageFilePromptInput) => void;
-}) {
- return (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] overflow-hidden max-h-[600px] overflow-y-auto">
- <table className="w-full text-sm">
- <thead className="border-b border-[var(--color-border-default)] text-xs uppercase tracking-wide text-[var(--color-text-tertiary)] bg-[var(--color-bg-elevated)] sticky top-0">
- <tr>
- <th className="px-4 py-2 text-left font-medium">File</th>
- <th className="px-4 py-2 text-left font-medium w-64">Line coverage</th>
- <th className="px-4 py-2 text-right font-medium">Branch</th>
- <th className="px-4 py-2 text-right font-medium">Lines</th>
- <th className="px-4 py-2 text-right font-medium">Health</th>
- <th className="px-4 py-2 text-right font-medium w-12"></th>
- </tr>
- </thead>
- <tbody className="divide-y divide-[var(--color-border-default)]">
- {files.map((f) => {
- const isSelected = selectedFile === f.file_path;
- return (
- <tr
- key={f.file_path}
- className={`cursor-pointer hover:bg-[var(--color-bg-muted)] ${isSelected ? "bg-[var(--color-accent-muted)]/20" : ""}`}
- onClick={() => onSelect(f.file_path)}
- >
- <td className="px-4 py-2 font-mono text-xs text-[var(--color-text-primary)] truncate max-w-[480px]" title={f.file_path}>
- <span className="inline-flex items-center gap-1.5">
- <span className="truncate">{f.file_path}</span>
- <ArrowUpRight className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />
- </span>
- </td>
- <td className="px-4 py-2">
- <CoverageBar value={f.line_coverage_pct} size="sm" />
- </td>
- <td className="px-4 py-2 text-right tabular-nums text-[var(--color-text-secondary)]">
- {f.branch_coverage_pct == null
- ? "—"
- : `${f.branch_coverage_pct.toFixed(0)}%`}
- </td>
- <td className="px-4 py-2 text-right tabular-nums text-[var(--color-text-tertiary)]">
- {f.total_coverable_lines}
- </td>
- <td className="px-4 py-2 text-right tabular-nums">
- {f.health_score == null ? (
- <span className="text-[var(--color-text-tertiary)]">—</span>
- ) : (
- <span className={`inline-block rounded px-1.5 py-0.5 text-xs font-semibold ${scoreBadgeClass(f.health_score)}`}>
- {f.health_score.toFixed(1)}
- </span>
- )}
- </td>
- <td className="px-2 py-2 text-right">
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- onGeneratePrompt({
- file_path: f.file_path,
- line_coverage_pct: f.line_coverage_pct,
- branch_coverage_pct: f.branch_coverage_pct,
- total_coverable_lines: f.total_coverable_lines,
- covered_lines: f.covered_lines,
- source_format: f.source_format,
- health_score: f.health_score ?? null,
- nloc: f.nloc ?? null,
- });
- }}
- title="Generate AI test prompt for this file"
- className="inline-flex items-center justify-center rounded-md p-1 text-[var(--color-text-tertiary)] hover:text-emerald-500 hover:bg-emerald-500/10 transition-colors"
- >
- <Sparkles className="h-3.5 w-3.5" />
- </button>
- </td>
- </tr>
- );
- })}
- </tbody>
- </table>
- </div>
- );
-}
-
-function SummaryCard({
- label,
- children,
-}: {
- label: string;
- children: React.ReactNode;
-}) {
- return (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">
- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1">
- {label}
- </p>
- {children}
- </div>
- );
-}
-
-function EmptyState() {
- return (
- <div className="rounded-lg border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-8">
- <div className="max-w-xl mx-auto text-center space-y-3">
- <h2 className="text-base font-semibold text-[var(--color-text-primary)]">
- No coverage data ingested yet
- </h2>
- <p className="text-sm text-[var(--color-text-secondary)]">
- Run your test suite with coverage enabled, then ingest the report.
- You&apos;ll see a risk × coverage map, untested-hotspot warnings, and a
- per-module breakdown.
- </p>
- <pre className="inline-block px-4 py-2 rounded bg-[var(--color-bg-muted)] text-left text-xs font-mono">
- pytest --cov --cov-report=lcov{"\n"}
- repowise health --coverage coverage.lcov
- </pre>
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Supported formats: LCOV · Cobertura · Clover.
- </p>
- </div>
- </div>
- );
-}
-
-function CoverageSkeleton() {
- return (
- <div className="space-y-6">
- <div className="grid grid-cols-4 gap-3">
- {Array.from({ length: 4 }).map((_, i) => (
- <Skeleton key={i} className="h-24 w-full rounded-lg" />
- ))}
- </div>
- <Skeleton className="h-72 w-full rounded-lg" />
- <Skeleton className="h-48 w-full rounded-lg" />
- </div>
- );
+ const { id } = await params;
+ redirect(`/repos/${id}/code-health?tab=coverage`);
}
diff --git a/packages/web/src/app/repos/[id]/health/page.tsx b/packages/web/src/app/repos/[id]/health/page.tsx
index d33a70bd7..b7e9e81b4 100644
--- a/packages/web/src/app/repos/[id]/health/page.tsx
+++ b/packages/web/src/app/repos/[id]/health/page.tsx
@@ -1,335 +1,11 @@
-"use client";
+import { redirect } from "next/navigation";
-import { useMemo, useState } from "react";
-import useSWR from "swr";
-import { useParams } from "next/navigation";
-import { HeartPulse, RotateCw, Search } from "lucide-react";
-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-import { Button } from "@repowise-dev/ui/ui/button";
-import {
- HealthKpiCards,
- HealthFileTable,
- BiomarkerList,
- ModuleRollupList,
- HotFunctionsPanel,
- HiddenCouplingList,
- RecalibrationBanner,
- DefectAccuracyCard,
- type FileSortField,
- type Severity,
-} from "@repowise-dev/ui/health";
-import {
- getHealthOverview,
- getHealthTrend,
- listHealthFiles,
- listHealthFindings,
- type HealthFinding,
- type HealthOverviewResponse,
- type HealthTrendResponse,
- type HealthFilesResponse,
-} from "@/lib/api/code-health";
-import { HealthPageChrome } from "@/components/health/health-page-chrome";
-import { HealthFileDrawerHost } from "@/components/health/health-file-drawer-host";
-
-const PAGE_SIZE = 50;
-
-export default function HealthPage() {
- const params = useParams<{ id: string }>();
- const id = params.id;
-
- const { data: overview, isLoading, error, mutate } = useSWR<HealthOverviewResponse>(
- `code-health-overview:${id}`,
- () => getHealthOverview(id, 25),
- { revalidateOnFocus: false },
- );
- const { data: hotFunctionFindings } = useSWR<HealthFinding[]>(
- `code-health-hot-functions:${id}`,
- async () => {
- const types = [
- "function_hotspot",
- "code_age_volatility",
- "complex_conditional",
- ] as const;
- const batches = await Promise.all(
- types.map((t) =>
- listHealthFindings(id, { biomarker_type: t, limit: 100 }).catch(
- () => [] as HealthFinding[],
- ),
- ),
- );
- return batches.flat();
- },
- { revalidateOnFocus: false },
- );
-
- const { data: couplingFindings } = useSWR<HealthFinding[]>(
- `code-health-hidden-coupling:${id}`,
- () =>
- listHealthFindings(id, {
- biomarker_type: "hidden_coupling",
- limit: 100,
- }).catch(() => []),
- { revalidateOnFocus: false },
- );
-
- const { data: trend } = useSWR<HealthTrendResponse>(
- `code-health-trend:${id}`,
- () => getHealthTrend(id, 20),
- { revalidateOnFocus: false },
- );
-
- // File table state
- const [sortField, setSortField] = useState<FileSortField>("score");
- const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");
- const [search, setSearch] = useState("");
- const [onlyHotspots, setOnlyHotspots] = useState(false);
- const [onlyUntested, setOnlyUntested] = useState(false);
- const [onlyFailing, setOnlyFailing] = useState(false);
- const [offset, setOffset] = useState(0);
- const [minSeverity, setMinSeverity] = useState<Severity | "all">("all");
- const [selectedFile, setSelectedFile] = useState<string | null>(null);
-
- const filesKey = useMemo(
- () =>
- JSON.stringify({
- id,
- sortField,
- sortOrder,
- search,
- onlyHotspots,
- onlyUntested,
- onlyFailing,
- offset,
- }),
- [id, sortField, sortOrder, search, onlyHotspots, onlyUntested, onlyFailing, offset],
- );
-
- const { data: files, isLoading: filesLoading } = useSWR<HealthFilesResponse>(
- overview ? `code-health-files:${filesKey}` : null,
- () =>
- listHealthFiles(id, {
- sort: sortField,
- order: sortOrder,
- search: search || undefined,
- only_hotspots: onlyHotspots || undefined,
- only_untested: onlyUntested || undefined,
- only_failing: onlyFailing || undefined,
- offset,
- limit: PAGE_SIZE,
- }),
- { revalidateOnFocus: false, keepPreviousData: true },
- );
-
- const handleSort = (field: FileSortField) => {
- if (field === sortField) {
- setSortOrder((o) => (o === "asc" ? "desc" : "asc"));
- } else {
- setSortField(field);
- // Score: asc (worst first). Counts: desc. Path: asc.
- setSortOrder(["score", "line_coverage_pct", "file_path"].includes(field) ? "asc" : "desc");
- }
- setOffset(0);
- };
-
- const avgSeries = trend?.history?.slice().reverse().map((p) => p.average_health);
- const hotspotSeries = trend?.history?.slice().reverse().map((p) => p.hotspot_health);
- const worstSeries = trend?.history
- ?.slice()
- .reverse()
- .map((p) => p.worst_performer_score ?? 0);
-
- return (
- <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">
- <HealthPageChrome
- repoId={id}
- active="overview"
- title="Code Health"
- icon={<HeartPulse className="h-5 w-5 text-emerald-500" />}
- subtitle="Per-file health scores from CCN, nesting, duplication, coverage, and ownership biomarkers."
- meta={overview?.meta}
- actions={
- <Button size="sm" variant="outline" onClick={() => mutate()}>
- <RotateCw className="h-3.5 w-3.5 mr-1.5" /> Refresh
- </Button>
- }
- />
-
- {isLoading ? (
- <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-5 gap-3">
- {Array.from({ length: 5 }).map((_, i) => (
- <Skeleton key={i} className="h-24 w-full rounded-lg" />
- ))}
- </div>
- ) : error ? (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)] flex items-center justify-between gap-2">
- <span>Couldn&apos;t load health data. Run <code>repowise init</code> to populate.</span>
- <Button size="sm" variant="outline" onClick={() => mutate()}>Retry</Button>
- </div>
- ) : overview ? (
- <>
- <RecalibrationBanner repoId={id} />
- <HealthKpiCards
- summary={overview.summary}
- averageHistory={avgSeries}
- hotspotHistory={hotspotSeries}
- worstHistory={worstSeries}
- averageDelta={trend?.summary?.average_delta ?? undefined}
- hotspotDelta={trend?.summary?.hotspot_delta ?? undefined}
- />
-
- {overview.defect_accuracy ? (
- <DefectAccuracyCard data={overview.defect_accuracy} />
- ) : null}
-
- <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
- <div className="lg:col-span-2 space-y-3">
- <div className="flex flex-wrap items-center gap-2">
- <h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] mr-auto">
- Files {files?.total != null ? `(${files.total.toLocaleString()})` : ""}
- </h2>
- <div className="relative">
- <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
- <input
- value={search}
- onChange={(e) => {
- setSearch(e.target.value);
- setOffset(0);
- }}
- placeholder="Filter path…"
- className="text-xs pl-7 pr-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-56 focus:outline-none focus:border-[var(--color-border-strong)]"
- />
- </div>
- <FilterChip active={onlyHotspots} onClick={() => { setOnlyHotspots((v) => !v); setOffset(0); }}>
- Hotspots
- </FilterChip>
- <FilterChip active={onlyUntested} onClick={() => { setOnlyUntested((v) => !v); setOffset(0); }}>
- Untested
- </FilterChip>
- <FilterChip active={onlyFailing} onClick={() => { setOnlyFailing((v) => !v); setOffset(0); }}>
- Failing
- </FilterChip>
- </div>
-
- {filesLoading && !files ? (
- <Skeleton className="h-64 w-full rounded-lg" />
- ) : (
- <HealthFileTable
- files={files?.files ?? []}
- sortField={sortField}
- sortOrder={sortOrder}
- onSort={handleSort}
- onSelect={(f) => setSelectedFile(f.file_path)}
- selectedPath={selectedFile}
- />
- )}
-
- {files && files.total > PAGE_SIZE ? (
- <div className="flex items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)]">
- <span>
- Showing {offset + 1}–{Math.min(offset + PAGE_SIZE, files.total)} of {files.total}
- </span>
- <div className="flex gap-1">
- <Button
- size="sm"
- variant="outline"
- disabled={offset === 0}
- onClick={() => setOffset(Math.max(0, offset - PAGE_SIZE))}
- >
- Prev
- </Button>
- <Button
- size="sm"
- variant="outline"
- disabled={offset + PAGE_SIZE >= files.total}
- onClick={() => setOffset(offset + PAGE_SIZE)}
- >
- Next
- </Button>
- </div>
- </div>
- ) : null}
- </div>
-
- <div className="space-y-3">
- <div className="flex items-center gap-2">
- <h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] mr-auto">
- Findings
- </h2>
- <select
- value={minSeverity}
- onChange={(e) => setMinSeverity(e.target.value as Severity | "all")}
- className="text-xs px-2 py-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]"
- >
- <option value="all">All severities</option>
- <option value="low">Low+</option>
- <option value="medium">Medium+</option>
- <option value="high">High+</option>
- <option value="critical">Critical</option>
- </select>
- </div>
- <BiomarkerList
- findings={overview.top_findings}
- grouped
- minSeverity={minSeverity === "all" ? undefined : minSeverity}
- onSelect={(f) => setSelectedFile(f.file_path)}
- />
- </div>
- </div>
-
- {hotFunctionFindings && hotFunctionFindings.length >= 3 ? (
- <HotFunctionsPanel
- findings={hotFunctionFindings}
- onSelect={(f) => setSelectedFile(f.file_path)}
- />
- ) : null}
-
- {couplingFindings && couplingFindings.length >= 3 ? (
- <HiddenCouplingList
- findings={couplingFindings}
- onSelect={(path) => setSelectedFile(path)}
- />
- ) : null}
-
- {overview.modules && overview.modules.length > 0 ? (
- <div className="space-y-2">
- <h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
- By module
- </h2>
- <ModuleRollupList modules={overview.modules} />
- </div>
- ) : null}
- </>
- ) : null}
-
- <HealthFileDrawerHost
- repoId={id}
- filePath={selectedFile}
- onClose={() => setSelectedFile(null)}
- />
- </div>
- );
-}
-
-function FilterChip({
- active,
- onClick,
- children,
+/** Legacy route — redirects into the consolidated IA. */
+export default async function LegacyRedirect({
+ params,
}: {
- active: boolean;
- onClick: () => void;
- children: React.ReactNode;
+ params: Promise<{ id: string }>;
}) {
- return (
- <button
- type="button"
- onClick={onClick}
- className={`text-xs rounded-md px-2 py-1 border transition-colors ${
- active
- ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)] border-[var(--color-accent-primary)]/50"
- : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"
- }`}
- >
- {children}
- </button>
- );
+ const { id } = await params;
+ redirect(`/repos/${id}/code-health`);
}
diff --git a/packages/web/src/app/repos/[id]/health/refactoring-targets/page.tsx b/packages/web/src/app/repos/[id]/health/refactoring-targets/page.tsx
index c98850f5d..b7e9e81b4 100644
--- a/packages/web/src/app/repos/[id]/health/refactoring-targets/page.tsx
+++ b/packages/web/src/app/repos/[id]/health/refactoring-targets/page.tsx
@@ -1,275 +1,11 @@
-"use client";
+import { redirect } from "next/navigation";
-import { useMemo, useState } from "react";
-import { Wrench } from "lucide-react";
-import { useParams } from "next/navigation";
-import useSWR from "swr";
-
-import {
- AiPromptModal,
- ImpactEffortQuadrant,
- RefactoringTargetList,
- biomarkerLabel,
- buildAiPrompt,
-} from "@repowise-dev/ui/health";
-import type { FindingStatus, RefactoringTarget } from "@repowise-dev/ui/health";
-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-
-import {
- getHealthOverview,
- getRefactoringTargets,
- updateFindingStatus,
- type HealthOverviewResponse,
- type RefactoringTargetsResponse,
- type RefactoringQuery,
-} from "@/lib/api/code-health";
-import { HealthPageChrome } from "@/components/health/health-page-chrome";
-import { HealthFileDrawerHost } from "@/components/health/health-file-drawer-host";
-
-type GroupBy = "none" | "biomarker" | "module" | "effort";
-
-const EFFORT_LABEL: Record<string, string> = {
- S: "Small (≤40 NLOC)",
- M: "Medium (≤150 NLOC)",
- L: "Large (≤400 NLOC)",
- XL: "Extra large (>400 NLOC)",
-};
-
-export default function RefactoringTargetsPage() {
- const params = useParams<{ id: string }>();
- const id = params.id;
-
- const [biomarker, setBiomarker] = useState<string | "all">("all");
- const [minSeverity, setMinSeverity] = useState<string>("all");
- const [maxEffort, setMaxEffort] = useState<string>("all");
- const [sort, setSort] = useState<RefactoringQuery["sort"]>("impact_per_effort");
- const [groupBy, setGroupBy] = useState<GroupBy>("none");
- const [selectedFile, setSelectedFile] = useState<string | null>(null);
- const [promptTarget, setPromptTarget] = useState<RefactoringTarget | null>(null);
-
- const queryKey = useMemo(
- () => JSON.stringify({ id, biomarker, minSeverity, maxEffort, sort }),
- [id, biomarker, minSeverity, maxEffort, sort],
- );
-
- const { data, isLoading, error, mutate } = useSWR<RefactoringTargetsResponse>(
- `code-health-refactoring:${queryKey}`,
- () =>
- getRefactoringTargets(id, {
- limit: 200,
- biomarker: biomarker === "all" ? undefined : biomarker,
- min_severity: minSeverity === "all" ? undefined : minSeverity,
- max_effort: maxEffort === "all" ? undefined : maxEffort,
- sort,
- }),
- { revalidateOnFocus: false },
- );
-
- const { data: overview } = useSWR<HealthOverviewResponse>(
- `code-health-overview:${id}`,
- () => getHealthOverview(id, 25),
- { revalidateOnFocus: false },
- );
-
- const handleStatus = async (findingId: string, status: FindingStatus) => {
- await updateFindingStatus(id, findingId, status);
- mutate();
- };
-
- const biomarkerOptions = useMemo(() => {
- const set = new Set<string>();
- (overview?.biomarkers ?? []).forEach((b) => set.add(b.biomarker_type));
- (data?.targets ?? []).forEach((t) => t.biomarkers.forEach((b) => set.add(b)));
- return [...set].sort();
- }, [overview, data]);
-
- const grouped = useMemo(() => {
- if (!data) return [];
- const targets = data.targets;
- if (groupBy === "none") return [{ key: "All", targets }];
- const groups = new Map<string, typeof targets>();
- for (const t of targets) {
- let key = "—";
- if (groupBy === "biomarker") key = biomarkerLabel(t.primary_biomarker);
- else if (groupBy === "module") key = t.module ?? "(no module)";
- else if (groupBy === "effort") key = EFFORT_LABEL[t.effort_bucket] ?? t.effort_bucket;
- if (!groups.has(key)) groups.set(key, []);
- groups.get(key)!.push(t);
- }
- return [...groups.entries()]
- .sort((a, b) => b[1].length - a[1].length)
- .map(([key, targets]) => ({ key, targets }));
- }, [data, groupBy]);
-
- return (
- <div className="p-4 sm:p-6 space-y-6 max-w-[1400px]">
- <HealthPageChrome
- repoId={id}
- active="refactoring"
- title="Refactoring targets"
- icon={<Wrench className="h-5 w-5 text-orange-500" />}
- subtitle="Files ranked by total health impact divided by an effort proxy (NLOC bucket). High leverage = high impact, low effort."
- meta={overview?.meta}
- />
-
- <div className="flex flex-wrap items-center gap-2">
- <Select
- label="Biomarker"
- value={biomarker}
- onChange={(v) => setBiomarker(v)}
- options={[
- { value: "all", label: "All biomarkers" },
- ...biomarkerOptions.map((b) => ({ value: b, label: biomarkerLabel(b) })),
- ]}
- />
- <Select
- label="Min severity"
- value={minSeverity}
- onChange={setMinSeverity}
- options={[
- { value: "all", label: "Any severity" },
- { value: "low", label: "Low+" },
- { value: "medium", label: "Medium+" },
- { value: "high", label: "High+" },
- { value: "critical", label: "Critical only" },
- ]}
- />
- <Select
- label="Max effort"
- value={maxEffort}
- onChange={setMaxEffort}
- options={[
- { value: "all", label: "Any effort" },
- { value: "S", label: "Small only" },
- { value: "M", label: "Medium+" },
- { value: "L", label: "Large+" },
- ]}
- />
- <Select
- label="Sort"
- value={sort ?? "impact_per_effort"}
- onChange={(v) => setSort(v as RefactoringQuery["sort"])}
- options={[
- { value: "impact_per_effort", label: "Leverage (impact ÷ effort)" },
- { value: "total_impact", label: "Total impact" },
- { value: "score", label: "Worst score" },
- { value: "finding_count", label: "Finding count" },
- ]}
- />
- <Select
- label="Group"
- value={groupBy}
- onChange={(v) => setGroupBy(v as GroupBy)}
- options={[
- { value: "none", label: "Flat list" },
- { value: "biomarker", label: "By biomarker" },
- { value: "module", label: "By module" },
- { value: "effort", label: "By effort" },
- ]}
- />
- </div>
-
- {isLoading ? (
- <div className="grid gap-3">
- {Array.from({ length: 5 }).map((_, i) => (
- <Skeleton key={i} className="h-28 w-full" />
- ))}
- </div>
- ) : error ? (
- <p className="text-sm text-red-500">Failed to load refactoring targets.</p>
- ) : !data || data.targets.length === 0 ? (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-6 text-sm text-[var(--color-text-secondary)]">
- No refactoring targets match the current filters. Try widening the
- severity or effort filters, or run{" "}
- <code className="px-1 rounded bg-[var(--color-bg-muted)]">repowise health</code>{" "}
- to populate findings.
- </div>
- ) : (
- <>
- <ImpactEffortQuadrant
- points={data.targets.map((t) => ({
- file_path: t.file_path,
- total_impact: t.total_impact,
- effort_bucket: t.effort_bucket,
- nloc: t.nloc,
- score: t.score,
- }))}
- onSelect={(p) => setSelectedFile(p.file_path)}
- />
-
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Showing {data.targets.length} of {data.total} candidates.
- </p>
-
- <div className="space-y-6">
- {grouped.map((g) => (
- <section key={g.key} className="space-y-2">
- {groupBy !== "none" ? (
- <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
- {g.key} <span className="text-[var(--color-text-secondary)]">({g.targets.length})</span>
- </h3>
- ) : null}
- <RefactoringTargetList
- targets={g.targets}
- onSelect={(t) => setSelectedFile(t.file_path)}
- onStatusChange={handleStatus}
- onGeneratePrompt={(t) => setPromptTarget(t)}
- />
- </section>
- ))}
- </div>
- </>
- )}
-
- <HealthFileDrawerHost
- repoId={id}
- filePath={selectedFile}
- onClose={() => setSelectedFile(null)}
- />
-
- <AiPromptModal
- open={promptTarget !== null}
- onOpenChange={(open) => {
- if (!open) setPromptTarget(null);
- }}
- filePath={promptTarget?.file_path}
- title="AI fix prompt"
- description="A ready-to-paste prompt that gives your AI coding agent every biomarker, line range, score deduction, and constraint needed to refactor this file in one focused pass."
- getPrompt={
- promptTarget
- ? (flavor) => buildAiPrompt({ target: promptTarget, flavor })
- : null
- }
- />
- </div>
- );
-}
-
-function Select({
- label,
- value,
- onChange,
- options,
+/** Legacy route — redirects into the consolidated IA. */
+export default async function LegacyRedirect({
+ params,
}: {
- label: string;
- value: string;
- onChange: (v: string) => void;
- options: { value: string; label: string }[];
+ params: Promise<{ id: string }>;
}) {
- return (
- <label className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)]">
- <span className="uppercase tracking-wider">{label}</span>
- <select
- value={value}
- onChange={(e) => onChange(e.target.value)}
- className="text-xs px-2 py-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)]"
- >
- {options.map((o) => (
- <option key={o.value} value={o.value}>
- {o.label}
- </option>
- ))}
- </select>
- </label>
- );
+ const { id } = await params;
+ redirect(`/repos/${id}/code-health`);
}
diff --git a/packages/web/src/app/repos/[id]/health/trend/page.tsx b/packages/web/src/app/repos/[id]/health/trend/page.tsx
index 62e761230..e737bea24 100644
--- a/packages/web/src/app/repos/[id]/health/trend/page.tsx
+++ b/packages/web/src/app/repos/[id]/health/trend/page.tsx
@@ -1,175 +1,11 @@
-"use client";
+import { redirect } from "next/navigation";
-import { TrendingUp, AlertTriangle, TrendingDown } from "lucide-react";
-import { useParams } from "next/navigation";
-import useSWR from "swr";
-
-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-import { TrendChart, deltaColor, formatDelta } from "@repowise-dev/ui/health";
-
-import {
- getHealthTrend,
- type HealthTrendResponse,
-} from "@/lib/api/code-health";
-import { HealthPageChrome } from "@/components/health/health-page-chrome";
-
-export default function HealthTrendPage() {
- const params = useParams<{ id: string }>();
- const id = params.id;
-
- const { data, isLoading, error } = useSWR<HealthTrendResponse>(
- `code-health-trend:${id}`,
- () => getHealthTrend(id, 20),
- { revalidateOnFocus: false },
- );
-
- return (
- <div className="p-4 sm:p-6 space-y-6 max-w-[1400px]">
- <HealthPageChrome
- repoId={id}
- active="trend"
- title="Health trend"
- icon={<TrendingUp className="h-5 w-5 text-emerald-500" />}
- subtitle="KPI history over the most recent indexes. Snapshots are rolling — the latest 50 per repo."
- />
-
- {isLoading ? (
- <Skeleton className="h-64 w-full rounded-lg" />
- ) : error || !data ? (
- <p className="text-sm text-red-500">Failed to load trend data.</p>
- ) : (
- <>
- <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
- <DeltaCard
- label="Average health"
- current={data.summary.current_average_health}
- previous={data.summary.previous_average_health}
- delta={data.summary.average_delta}
- />
- <DeltaCard
- label="Hotspot health"
- current={data.summary.current_hotspot_health}
- previous={data.summary.previous_hotspot_health}
- delta={data.summary.hotspot_delta}
- />
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">
- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
- Snapshots
- </p>
- <p className="mt-1 text-2xl font-bold text-[var(--color-text-primary)] tabular-nums">
- {data.snapshot_count}
- </p>
- <p className="text-[11px] text-[var(--color-text-tertiary)] mt-1">
- rolling window: 50 max
- </p>
- </div>
- </div>
-
- {data.alerts.length > 0 ? (
- <div className="space-y-2">
- {data.alerts.map((a, i) => (
- <div
- key={i}
- className={`rounded-lg border p-3 flex items-start gap-2 ${
- a.kind === "declining"
- ? "border-red-500/40 bg-red-500/5"
- : "border-amber-500/40 bg-amber-500/5"
- }`}
- >
- <AlertTriangle
- className={`h-4 w-4 mt-0.5 ${a.kind === "declining" ? "text-red-500" : "text-amber-500"}`}
- />
- <div className="text-sm">
- <p className="font-medium text-[var(--color-text-primary)]">
- {a.kind === "declining" ? "Declining health" : "Predicted decline"}
- </p>
- <p className="text-xs text-[var(--color-text-secondary)]">{a.message}</p>
- </div>
- </div>
- ))}
- </div>
- ) : null}
-
- <TrendChart history={[...data.history].reverse()} />
-
- <section className="space-y-2">
- <h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
- Largest score changes since last index
- </h2>
- {data.file_deltas.length === 0 ? (
- <p className="text-sm text-[var(--color-text-tertiary)]">
- No per-file changes between the last two snapshots.
- </p>
- ) : (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] overflow-hidden">
- <table className="w-full text-sm">
- <thead className="bg-[var(--color-bg-elevated)] text-xs uppercase tracking-wider text-[var(--color-text-tertiary)]">
- <tr>
- <th className="text-left px-3 py-2 font-medium">File</th>
- <th className="text-right px-3 py-2 font-medium">Before</th>
- <th className="text-right px-3 py-2 font-medium">After</th>
- <th className="text-right px-3 py-2 font-medium">Δ</th>
- </tr>
- </thead>
- <tbody>
- {data.file_deltas.map((d) => (
- <tr
- key={d.file_path}
- className="border-t border-[var(--color-border-default)]"
- >
- <td className="px-3 py-2 font-mono text-xs text-[var(--color-text-primary)] truncate max-w-[480px]" title={d.file_path}>
- {d.file_path}
- </td>
- <td className="px-3 py-2 text-right tabular-nums text-[var(--color-text-secondary)]">
- {d.before.toFixed(1)}
- </td>
- <td className="px-3 py-2 text-right tabular-nums text-[var(--color-text-secondary)]">
- {d.after.toFixed(1)}
- </td>
- <td className={`px-3 py-2 text-right tabular-nums ${deltaColor(d.delta)}`}>
- <span className="inline-flex items-center gap-1">
- {d.delta < 0 ? <TrendingDown className="h-3 w-3" /> : null}
- {formatDelta(d.delta)}
- </span>
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- )}
- </section>
- </>
- )}
- </div>
- );
-}
-
-function DeltaCard({
- label,
- current,
- previous,
- delta,
+/** Legacy route — redirects into the consolidated IA. */
+export default async function LegacyRedirect({
+ params,
}: {
- label: string;
- current: number;
- previous: number | null;
- delta: number | null;
+ params: Promise<{ id: string }>;
}) {
- return (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">
- <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
- {label}
- </p>
- <p className="mt-1 text-2xl font-bold text-[var(--color-text-primary)] tabular-nums">
- {current.toFixed(1)}
- <span className="text-base font-normal text-[var(--color-text-secondary)]">/10</span>
- </p>
- <p className={`text-[11px] tabular-nums mt-0.5 ${deltaColor(delta)}`}>
- {delta == null
- ? "no prior snapshot"
- : `${formatDelta(delta)} vs. ${previous?.toFixed(1) ?? "—"}`}
- </p>
- </div>
- );
+ const { id } = await params;
+ redirect(`/repos/${id}/code-health?tab=trend`);
}
diff --git a/packages/web/src/app/repos/[id]/hotspots/loading.tsx b/packages/web/src/app/repos/[id]/hotspots/loading.tsx
deleted file mode 100644
index 331d4031a..000000000
--- a/packages/web/src/app/repos/[id]/hotspots/loading.tsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";
-
-export default function HotspotsLoading() {
- return <OwlLoader />;
-}
diff --git a/packages/web/src/app/repos/[id]/hotspots/page.tsx b/packages/web/src/app/repos/[id]/hotspots/page.tsx
index 82c0ca949..7e4437f25 100644
--- a/packages/web/src/app/repos/[id]/hotspots/page.tsx
+++ b/packages/web/src/app/repos/[id]/hotspots/page.tsx
@@ -1,177 +1,11 @@
-import type { Metadata } from "next";
-import { Flame, Shield } from "lucide-react";
-import { StatCard } from "@repowise-dev/ui/shared/stat-card";
-import { RoutedToRiskBanner } from "@/components/risk/routed-to-risk-banner";
-import { HotspotTable } from "@repowise-dev/ui/git/hotspot-table";
-import { ContributorBar } from "@repowise-dev/ui/git/contributor-bar";
-import { ChurnHistogram } from "@repowise-dev/ui/git/churn-histogram";
-import { CommitCategoryDonut } from "@repowise-dev/ui/git/commit-category-donut";
-import { RiskDistributionChart } from "@repowise-dev/ui/git/risk-distribution-chart";
-import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
-import { getHotspots, getGitSummary } from "@/lib/api/git";
-import { HealthRisksPanel } from "@/components/health/health-risks-panel";
-import { formatNumber } from "@repowise-dev/ui/lib/format";
+import { redirect } from "next/navigation";
-export const metadata: Metadata = { title: "Hotspots" };
-
-export default async function HotspotsPage({
+/** Legacy route — redirects into the consolidated IA. */
+export default async function LegacyRedirect({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
-
- let hotspots: Awaited<ReturnType<typeof getHotspots>> = [];
- let summary: Awaited<ReturnType<typeof getGitSummary>> | null = null;
-
- let loadError: Error | null = null;
- try {
- [hotspots, summary] = await Promise.all([
- getHotspots(id, 100),
- getGitSummary(id),
- ]);
- } catch (err) {
- loadError = err instanceof Error ? err : new Error("Couldn't load hotspots");
- console.error("[hotspots] load failed:", err);
- }
-
- // Aggregate commit categories across all hotspot files
- const aggregatedCategories: Record<string, number> = {};
- for (const h of hotspots) {
- for (const [cat, count] of Object.entries(h.commit_categories || {})) {
- aggregatedCategories[cat] = (aggregatedCategories[cat] || 0) + (count as number);
- }
- }
-
- const busFactorRiskCount = hotspots.filter((h) => h.bus_factor <= 1).length;
-
- return (
- <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">
- <RoutedToRiskBanner repoId={id} tab="hotspots" />
- <div>
- <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 flex items-center gap-2">
- <Flame className="h-5 w-5 text-red-500" />
- Hotspots
- </h1>
- <p className="text-sm text-[var(--color-text-secondary)]">
- High-churn files — where the most risky code lives.
- </p>
- </div>
-
- {loadError && hotspots.length === 0 && (
- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)]">
- Couldn&apos;t load hotspots. The data may not be ready yet — try running a sync first.
- </div>
- )}
-
- {/* Summary cards */}
- {summary && (
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-5">
- <StatCard
- label="Hotspot Files"
- value={formatNumber(summary.hotspot_count)}
- description="high-churn files"
- />
- <StatCard
- label="Stable Files"
- value={formatNumber(summary.stable_count)}
- description="low-churn files"
- />
- <StatCard
- label="Total Files"
- value={formatNumber(summary.total_files)}
- description="with git history"
- />
- <StatCard
- label="Avg Churn"
- value={`${Math.round(summary.average_churn_percentile)}%`}
- description="percentile"
- />
- <StatCard
- label="Bus Factor Risk"
- value={formatNumber(busFactorRiskCount)}
- description="files with factor ≤ 1"
- icon={<Shield className="h-4 w-4 text-red-400" />}
- />
- </div>
- )}
-
- {/* Charts row */}
- {hotspots.length > 0 && (
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
- <Card className="lg:col-span-2">
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">Churn Distribution</CardTitle>
- </CardHeader>
- <CardContent className="pt-0">
- <ChurnHistogram hotspots={hotspots} />
- </CardContent>
- </Card>
-
- {Object.keys(aggregatedCategories).length > 0 && (
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">Commit Types</CardTitle>
- </CardHeader>
- <CardContent className="pt-0 flex items-center justify-center">
- <CommitCategoryDonut categories={aggregatedCategories} />
- </CardContent>
- </Card>
- )}
- </div>
- )}
-
- {/* Risk distribution */}
- {hotspots.length > 0 && (
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">Risk Distribution</CardTitle>
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Composite risk score: churn (40%) + bus factor (35%) + trend (25%)
- </p>
- </CardHeader>
- <CardContent className="pt-0">
- <RiskDistributionChart hotspots={hotspots} />
- </CardContent>
- </Card>
- )}
-
- {/* Table + sidebar */}
- <div className="grid grid-cols-1 gap-6 xl:grid-cols-4">
- <div className="xl:col-span-3">
- <HotspotTable hotspots={hotspots} repoId={id} />
- </div>
-
- <div className="space-y-4">
- <HealthRisksPanel repoId={id} title="Health risks in this list" limit={6} />
- {/* Top owners leaderboard */}
- {summary && summary.top_owners.length > 0 && (
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">Top Owners</CardTitle>
- </CardHeader>
- <CardContent className="pt-0">
- <ContributorBar owners={summary.top_owners} />
- <div className="mt-3 space-y-1.5">
- {summary.top_owners.slice(0, 5).map((o, i) => (
- <div key={o.email || `owner-${i}`} className="flex items-center justify-between text-xs">
- <span
- className="text-[var(--color-text-secondary)] truncate"
- title={o.email ? `${o.name} <${o.email}>` : o.name}
- >
- {o.name}
- </span>
- <span className="text-[var(--color-text-tertiary)] tabular-nums ml-2">
- {formatNumber(o.file_count)} files ({Math.round(o.pct * 100)}%)
- </span>
- </div>
- ))}
- </div>
- </CardContent>
- </Card>
- )}
- </div>
- </div>
- </div>
- );
+ redirect(`/repos/${id}/code-health?tab=hotspots`);
}
diff --git a/packages/web/src/app/repos/[id]/modules/[path]/page.tsx b/packages/web/src/app/repos/[id]/modules/[path]/page.tsx
index 3cdf87136..19f937454 100644
--- a/packages/web/src/app/repos/[id]/modules/[path]/page.tsx
+++ b/packages/web/src/app/repos/[id]/modules/[path]/page.tsx
@@ -5,6 +5,7 @@ import useSWR from "swr";
import Link from "next/link";
import { ArrowLeft, Folder } from "lucide-react";
import { ModuleHealthDetailView } from "@repowise-dev/ui/modules/module-health-detail";
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
import { getModuleHealth } from "@/lib/api/modules";
@@ -25,7 +26,7 @@ export default function ModuleHealthPage() {
<div className="p-4 sm:p-6 space-y-4 max-w-[1600px]">
<div className="flex items-center justify-between">
<Link
- href={`/repos/${id}/risk?tab=modules`}
+ href={`/repos/${id}/code-health?tab=modules`}
className="inline-flex items-center gap-1 text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
>
<ArrowLeft className="h-3 w-3" /> All modules
@@ -57,9 +58,7 @@ export default function ModuleHealthPage() {
const key = o.email ?? `name:${o.name}`;
router.push(`/repos/${id}/owners/${encodeURIComponent(key)}`);
}}
- onSelectFile={(p) =>
- router.push(`/repos/${id}/wiki/${encodeURIComponent(p)}`)
- }
+ onSelectFile={(p) => router.push(fileEntityPath(`/repos/${id}`, p))}
onSelectDecision={(decisionId) =>
router.push(`/repos/${id}/decisions/${encodeURIComponent(decisionId)}`)
}
diff --git a/packages/web/src/app/repos/[id]/overview/loading.tsx b/packages/web/src/app/repos/[id]/overview/loading.tsx
index 20f5cea11..b20b5f4db 100644
--- a/packages/web/src/app/repos/[id]/overview/loading.tsx
+++ b/packages/web/src/app/repos/[id]/overview/loading.tsx
@@ -1,5 +1,32 @@
-import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";
+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+/** Progressive skeleton mirroring the Overview layout — header, attention
+ * strip, stat strip, tab area. (The owl stays reserved for brand moments.) */
export default function OverviewLoading() {
- return <OwlLoader />;
+ return (
+ <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">
+ <div className="space-y-3">
+ <div className="flex items-center gap-3">
+ <Skeleton className="h-7 w-48" />
+ <Skeleton className="h-5 w-16" />
+ <Skeleton className="h-7 w-40 rounded-full" />
+ </div>
+ <Skeleton className="h-4 w-72" />
+ <Skeleton className="h-9 w-80" />
+ </div>
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
+ <Skeleton className="h-56 lg:col-span-2" />
+ <div className="space-y-4">
+ <Skeleton className="h-32" />
+ <Skeleton className="h-32" />
+ </div>
+ </div>
+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-5">
+ {Array.from({ length: 5 }).map((_, i) => (
+ <Skeleton key={i} className="h-16" />
+ ))}
+ </div>
+ <Skeleton className="h-72" />
+ </div>
+ );
}
diff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsx
index 3607b9eaf..0c902a039 100644
--- a/packages/web/src/app/repos/[id]/overview/page.tsx
+++ b/packages/web/src/app/repos/[id]/overview/page.tsx
@@ -1,47 +1,21 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { Hash } from "lucide-react";
-import { getRepo, getRepoStats } from "@/lib/api/repos";
-import { getGitSummary, getHotspots, getOwnership } from "@/lib/api/git";
-import { getDeadCodeSummary, listDeadCode } from "@/lib/api/dead-code";
-import { listDecisions, getDecisionHealth } from "@/lib/api/decisions";
-import { getGraph, getModuleGraph, getCommunities, getExecutionFlows } from "@/lib/api/graph";
+import { getOverviewSummary } from "@/lib/api/overview";
import { getProviders } from "@/lib/api/providers";
-import { getDistillSavings } from "@/lib/api/costs";
-import { getHealthOverview } from "@/lib/api/code-health";
-import { listJobs } from "@/lib/api/jobs";
-import { getKnowledgeMap } from "@/lib/api/knowledge-map";
import { Badge } from "@repowise-dev/ui/ui/badge";
import { StatCard } from "@repowise-dev/ui/shared/stat-card";
-import { DefectAccuracyCard } from "@repowise-dev/ui/health";
-import { HealthScoreRing } from "@repowise-dev/ui/dashboard/health-score-ring";
+import { EmptyState } from "@repowise-dev/ui/shared";
+import { HealthScoreBadge } from "@repowise-dev/ui/dashboard/health-score-badge";
import { AttentionPanel } from "@repowise-dev/ui/dashboard/attention-panel";
-import { QuickActionsWrapper as QuickActions } from "@/components/dashboard/quick-actions-wrapper";
+import { WhereToStartCard } from "@repowise-dev/ui/dashboard/where-to-start";
import { SavingsMini } from "@repowise-dev/ui/dashboard/savings-mini";
-import { computeHealthScore, buildAttentionItems, aggregateLanguages } from "@/lib/utils/health-score";
-import { HotspotsMini } from "@repowise-dev/ui/dashboard/hotspots-mini";
-import { DecisionsTimeline } from "@repowise-dev/ui/dashboard/decisions-timeline";
-import { ModuleOverviewGrid } from "@repowise-dev/ui/dashboard/module-overview-grid";
-import { CommunitySummaryGridWrapper as CommunitySummaryGrid } from "@/components/dashboard/community-summary-grid-wrapper";
-import { ExecutionFlowsPanel } from "@repowise-dev/ui/dashboard/execution-flows-panel";
-import { BusFactorPanel } from "@repowise-dev/ui/git/bus-factor-panel";
-import { CommitCategorySparkline } from "@repowise-dev/ui/git/commit-category-sparkline";
-import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@repowise-dev/ui/ui/tabs";
-import { formatNumber } from "@repowise-dev/ui/lib/format";
-import type {
- RepoStatsResponse,
- GitSummaryResponse,
- HotspotResponse,
- OwnershipEntry,
- DeadCodeSummaryResponse,
- DecisionRecordResponse,
- DecisionHealthResponse,
- GraphExportResponse,
- ModuleGraphResponse,
- CommunitySummaryItem,
- ExecutionFlowsResponse,
-} from "@/lib/api/types";
+import { LanguageDonut } from "@repowise-dev/ui/dashboard/language-donut";
+import { QuickActionsWrapper as QuickActions } from "@/components/dashboard/quick-actions-wrapper";
+import { OverviewTabs } from "@/components/overview/overview-tabs";
+import { computeHealthScore } from "@/lib/utils/health-score";
+import { formatNumber, formatRelativeTime } from "@repowise-dev/ui/lib/format";
+import type { AttentionItem } from "@repowise-dev/ui/dashboard/attention-panel";
export const metadata: Metadata = { title: "Overview" };
@@ -49,7 +23,6 @@ interface Props {
params: Promise<{ id: string }>;
}
-// Each fetch wrapped to return null on failure — the dashboard degrades gracefully
async function safeFetch<T>(fn: () => Promise<T>): Promise<T | null> {
try {
return await fn();
@@ -58,345 +31,177 @@ async function safeFetch<T>(fn: () => Promise<T>): Promise<T | null> {
}
}
+function trendFor(delta: number | null | undefined, suffix = "") {
+ if (delta == null || delta === 0) return undefined;
+ return {
+ value: `${delta > 0 ? "+" : ""}${delta}${suffix}`,
+ positive: delta > 0,
+ };
+}
+
export default async function OverviewPage({ params }: Props) {
const { id } = await params;
- const repo = await safeFetch(() => getRepo(id));
- if (!repo) notFound();
-
- // Fetch all data in parallel — each independently failable
- const [stats, gitSummary, hotspots, ownership, deadCodeSummary, deadCodeSafe, decisions, decisionHealth, graph, moduleGraph, providers, completedJobs, knowledgeMap, communities, executionFlows, distillSavings, healthOverview] =
- await Promise.all([
- safeFetch(() => getRepoStats(id)),
- safeFetch(() => getGitSummary(id)),
- safeFetch(() => getHotspots(id, 50)),
- safeFetch(() => getOwnership(id, "module")),
- safeFetch(() => getDeadCodeSummary(id)),
- safeFetch(() => listDeadCode(id, { safe_only: true, status: "active", limit: 50 })),
- safeFetch(() => listDecisions(id, { limit: 10 })),
- safeFetch(() => getDecisionHealth(id)),
- safeFetch(() => getGraph(id)),
- safeFetch(() => getModuleGraph(id)),
- safeFetch(() => getProviders()),
- safeFetch(() => listJobs({ repo_id: id, limit: 20, status: "completed" })),
- safeFetch(() => getKnowledgeMap(id)),
- safeFetch(() => getCommunities(id)),
- safeFetch(() => getExecutionFlows(id, { top_n: 5, max_depth: 5 })),
- safeFetch(() => getDistillSavings(id)),
- safeFetch(() => getHealthOverview(id, 25)),
- ]);
+ const [summary, providers] = await Promise.all([
+ safeFetch(() => getOverviewSummary(id)),
+ safeFetch(() => getProviders()),
+ ]);
+ if (!summary) notFound();
- // Find timestamps for last sync and last full re-index from completed jobs
- const lastSyncJob = completedJobs?.find((j) => !j.config?.mode || j.config.mode === "sync");
- const lastResyncJob = completedJobs?.find((j) => j.config?.mode === "full_resync");
+ const { repo, stats, health, attention, sync } = summary;
+ const isFresh = stats.file_count === 0;
- // Compute health score
- const siloCount = ownership?.filter((o) => o.is_silo).length ?? 0;
const healthScore = computeHealthScore({
- docCoveragePct: stats?.doc_coverage_pct ?? 0,
- freshnessScore: stats?.freshness_score ?? 0,
- deadExportCount: stats?.dead_export_count ?? 0,
- symbolCount: stats?.symbol_count ?? 1,
- hotspotCount: gitSummary?.hotspot_count ?? 0,
- totalFiles: gitSummary?.total_files ?? 1,
- siloCount,
- totalModules: ownership?.length ?? 1,
+ docCoveragePct: stats.doc_coverage_pct,
+ freshnessScore: stats.freshness_score,
+ deadExportCount: stats.dead_export_count,
+ symbolCount: stats.symbol_count || 1,
+ hotspotCount: stats.hotspot_count,
+ totalFiles: stats.file_count || 1,
+ siloCount: stats.silo_count,
+ totalModules: stats.module_count || 1,
});
- // Build attention items
- const attentionItems = buildAttentionItems({
- staleDecisions: decisionHealth?.stale_decisions ?? [],
- proposedDecisions: decisionHealth?.proposed_awaiting_review ?? [],
- ungovernedHotspots: decisionHealth?.ungoverned_hotspots ?? [],
- siloModules: ownership?.filter((o) => o.is_silo) ?? [],
- deadCodeSafe: deadCodeSafe ?? [],
- });
+ const attentionItems: AttentionItem[] = attention.map((a) => ({
+ id: a.id,
+ type: a.type,
+ title: a.title,
+ description: a.description,
+ severity: a.severity,
+ href:
+ a.type === "stale_decision" || a.type === "proposed_decision"
+ ? `/repos/${id}/decisions/${a.target_id}`
+ : undefined,
+ }));
- // Aggregate language distribution from graph nodes
- const langDistribution = graph ? aggregateLanguages(graph.nodes) : {};
+ const langDistribution: Record<string, number> = {};
+ for (const l of summary.languages) langDistribution[l.language] = l.file_count;
- // Aggregate commit categories across hotspots for the Activity tab
- const aggregatedCategories: Record<string, number> = {};
- for (const h of hotspots ?? []) {
- for (const [cat, count] of Object.entries(h.commit_categories ?? {})) {
- aggregatedCategories[cat] = (aggregatedCategories[cat] || 0) + count;
- }
- }
- const hasCategories = Object.values(aggregatedCategories).some((v) => v > 0);
+ const lastActivityAt = sync.last_sync_at ?? sync.last_resync_at ?? health.last_indexed_at;
return (
<div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">
- {/* ── Hero: Health Score + Repo Info + Quick Actions ── */}
- <div className="flex flex-col sm:flex-row items-start gap-6">
- <HealthScoreRing
- score={healthScore.score}
- components={healthScore.components}
- note={healthScore.note}
+ {/* ── Compact header ── */}
+ <div className="space-y-3">
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">
+ <h1 className="text-xl font-semibold text-[var(--color-text-primary)] truncate">
+ {repo.name}
+ </h1>
+ {repo.head_commit && (
+ <Badge variant="outline" className="text-[10px] h-5 shrink-0">
+ <Hash className="h-2.5 w-2.5" />
+ {repo.head_commit.slice(0, 7)}
+ </Badge>
+ )}
+ <Badge variant="outline" className="text-[10px] h-5 shrink-0">
+ {repo.default_branch}
+ </Badge>
+ {!isFresh && (
+ <HealthScoreBadge
+ score={healthScore.score}
+ components={healthScore.components}
+ note={healthScore.note}
+ history={health.history}
+ />
+ )}
+ {lastActivityAt && (
+ <span
+ className="text-[11px] text-[var(--color-text-tertiary)]"
+ title={new Date(lastActivityAt).toLocaleString()}
+ >
+ synced {formatRelativeTime(lastActivityAt)}
+ </span>
+ )}
+ </div>
+ <p className="text-xs font-mono text-[var(--color-text-tertiary)] truncate -mt-1">
+ {repo.local_path}
+ </p>
+ <QuickActions
+ repoId={id}
+ repoName={repo.name}
+ pageCount={sync.page_count || stats.file_count}
+ modelName={providers?.active.model ?? sync.last_sync_model ?? ""}
+ lastSyncAt={sync.last_sync_at}
+ lastResyncAt={sync.last_resync_at}
/>
+ </div>
- <div className="flex-1 min-w-0 space-y-3">
- <div>
- <div className="flex items-center gap-2">
- <h1 className="text-xl font-semibold text-[var(--color-text-primary)] truncate">
- {repo.name}
- </h1>
- {repo.head_commit && (
- <Badge variant="outline" className="text-[10px] h-5 shrink-0">
- <Hash className="h-2.5 w-2.5" />
- {repo.head_commit.slice(0, 7)}
- </Badge>
- )}
- <Badge variant="outline" className="text-[10px] h-5 shrink-0">
- {repo.default_branch}
- </Badge>
+ {isFresh ? (
+ <EmptyState
+ title={
+ lastActivityAt
+ ? `Indexed ${formatRelativeTime(lastActivityAt)} — nothing to show yet`
+ : "This repo hasn't been indexed yet"
+ }
+ description="Run a sync (above) or `repowise init` in the repo to populate the overview. Stats, attention items, and activity appear as soon as the first index lands."
+ />
+ ) : (
+ <>
+ {/* ── Attention strip leads ── */}
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
+ <div className="lg:col-span-2">
+ <AttentionPanel items={attentionItems} repoId={id} />
+ </div>
+ <div className="space-y-4">
+ <WhereToStartCard targets={summary.onboarding_targets} repoId={id} />
+ <SavingsMini data={summary.savings} repoId={id} />
</div>
- <p className="text-xs font-mono text-[var(--color-text-tertiary)] truncate mt-0.5">
- {repo.local_path}
- </p>
</div>
- {/* Quick actions */}
- <QuickActions
- repoId={id}
- repoName={repo.name}
- pageCount={stats?.file_count ?? 0}
- modelName={providers?.active.model ?? ""}
- lastSyncAt={lastSyncJob?.finished_at ?? null}
- lastResyncAt={lastResyncJob?.finished_at ?? null}
- />
-
- {/* Key metrics strip */}
+ {/* ── Stat strip with deltas ── */}
<div className="grid grid-cols-2 gap-2 sm:grid-cols-5">
<StatCard
label="Files"
- value={stats ? formatNumber(stats.file_count) : "–"}
- href={`/repos/${id}/graph`}
+ value={formatNumber(stats.file_count)}
+ trend={trendFor(stats.deltas.file_count)}
+ href={`/repos/${id}/architecture?view=graph`}
dense
/>
<StatCard
label="Symbols"
- value={stats ? formatNumber(stats.symbol_count) : "–"}
- href={`/repos/${id}/symbols`}
- dense
- />
- <StatCard
- label="Entry Points"
- value={stats ? formatNumber(stats.entry_point_count) : "–"}
- href={`/repos/${id}/graph?viewMode=architecture`}
+ value={formatNumber(stats.symbol_count)}
+ href={`/repos/${id}/architecture?view=symbols`}
dense
/>
<StatCard
label="Doc Coverage"
- value={stats ? `${Math.round(stats.doc_coverage_pct)}%` : "–"}
+ value={`${Math.round(stats.doc_coverage_pct)}%`}
href={`/repos/${id}/docs/coverage`}
dense
/>
<StatCard
label="Dead Exports"
- value={stats ? formatNumber(stats.dead_export_count) : "–"}
- description={
- deadCodeSummary
- ? `${formatNumber(deadCodeSummary.deletable_lines)} cleanup-candidate lines`
- : undefined
- }
- href={`/repos/${id}/dead-code`}
+ value={formatNumber(stats.dead_export_count)}
+ href={`/repos/${id}/code-health?tab=dead-code`}
+ dense
+ />
+ <StatCard
+ label="Hotspots"
+ value={formatNumber(stats.hotspot_count)}
+ href={`/repos/${id}/code-health?tab=hotspots`}
dense
/>
</div>
- </div>
- </div>
- {/* ── Does the health score find the bugs? — self-validation ── */}
- {healthOverview?.defect_accuracy ? (
- <DefectAccuracyCard data={healthOverview.defect_accuracy} />
- ) : null}
-
- {/* ── At a glance: what needs eyes now ── */}
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
- <div className="lg:col-span-2">
- <AttentionPanel items={attentionItems} repoId={id} />
- </div>
- <div>
- <SavingsMini
- data={distillSavings}
+ {/* ── Pulse / Structure ── */}
+ <OverviewTabs
repoId={id}
- langDistribution={langDistribution}
- langHref={`/repos/${id}/graph?colorMode=language`}
+ hotspots={summary.top_hotspots}
+ hotspotTotal={stats.hotspot_count}
+ decisions={summary.recent_decisions}
/>
- </div>
- </div>
-
- {/* ── Detail sections — one focus at a time ── */}
- <Tabs defaultValue="activity">
- <TabsList>
- <TabsTrigger value="activity">Activity</TabsTrigger>
- <TabsTrigger value="architecture">Architecture</TabsTrigger>
- <TabsTrigger value="graph">Graph</TabsTrigger>
- <TabsTrigger value="ownership">Ownership</TabsTrigger>
- </TabsList>
-
- {/* Activity — recent change pressure and decisions */}
- <TabsContent value="activity" className="mt-4 space-y-4">
- <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
- <HotspotsMini hotspots={hotspots ?? []} repoId={id} />
- <DecisionsTimeline
- decisions={
- decisions
- ? [...decisions].sort(
- (a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
- )
- : []
- }
- repoId={id}
- />
- </div>
- {hasCategories && (
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">Commit Activity</CardTitle>
- </CardHeader>
- <CardContent>
- <CommitCategorySparkline categories={aggregatedCategories} />
- <div className="flex items-center gap-4 mt-2 text-[10px] text-[var(--color-text-tertiary)]">
- <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "var(--color-info)" }} /> Feature</span>
- <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "var(--color-error)" }} /> Fix</span>
- <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "var(--color-accent-secondary)" }} /> Refactor</span>
- <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "var(--color-accent-fill)" }} /> Dependency</span>
- </div>
- </CardContent>
- </Card>
- )}
- </TabsContent>
- {/* Architecture — module map */}
- <TabsContent value="architecture" className="mt-4">
- {moduleGraph && moduleGraph.nodes.length > 0 ? (
- <ModuleOverviewGrid
- nodes={moduleGraph.nodes}
- edges={moduleGraph.edges}
- repoId={id}
- />
- ) : (
- <p className="text-sm text-[var(--color-text-tertiary)]">No module graph available.</p>
- )}
- </TabsContent>
-
- {/* Graph — communities & execution flows */}
- <TabsContent value="graph" className="mt-4 space-y-4">
- <div className="flex justify-end">
- <a href={`/repos/${id}/graph?colorMode=community`} className="text-[10px] text-[var(--color-accent-primary)] hover:underline">
- View all →
- </a>
- </div>
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
- {communities && communities.length > 0 && (
- <CommunitySummaryGrid communities={communities} repoId={id} />
- )}
- {executionFlows && executionFlows.flows.length > 0 && (
- <ExecutionFlowsPanel flows={executionFlows.flows} repoId={id} />
- )}
- </div>
- {!(communities && communities.length > 0) && !(executionFlows && executionFlows.flows.length > 0) && (
- <p className="text-sm text-[var(--color-text-tertiary)]">No graph intelligence available.</p>
+ {/* ── Languages (moved out of the savings card) ── */}
+ {summary.languages.length > 0 && (
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
+ <LanguageDonut
+ distribution={langDistribution}
+ viewAllHref={`/repos/${id}/architecture?view=graph&colorMode=language`}
+ />
+ </div>
)}
- </TabsContent>
-
- {/* Ownership — bus factor, silos, onboarding */}
- <TabsContent value="ownership" className="mt-4 space-y-4">
- <div className="flex justify-end">
- <a href={`/repos/${id}/ownership`} className="text-[10px] text-[var(--color-accent-primary)] hover:underline">
- View all →
- </a>
- </div>
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
- {hotspots && hotspots.length > 0 && (
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">Bus Factor</CardTitle>
- </CardHeader>
- <CardContent>
- <BusFactorPanel hotspots={hotspots} />
- </CardContent>
- </Card>
- )}
-
- {knowledgeMap && (
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">Knowledge Silos</CardTitle>
- </CardHeader>
- <CardContent>
- {knowledgeMap.knowledge_silos.length === 0 ? (
- <p className="text-xs text-[var(--color-text-tertiary)]">No silos detected — good bus factor!</p>
- ) : (
- <div className="space-y-1">
- <p className="text-xs text-[var(--color-text-secondary)] mb-2">
- {formatNumber(knowledgeMap.knowledge_silos.length)} file
- {knowledgeMap.knowledge_silos.length === 1 ? "" : "s"} with &gt;80% single-owner concentration
- </p>
- <ul className="space-y-1">
- {knowledgeMap.knowledge_silos.slice(0, 3).map((silo) => (
- <li key={silo.file_path}>
- <a
- href={`/repos/${id}/graph?node=${encodeURIComponent(silo.file_path)}`}
- className="flex items-center justify-between gap-2 -mx-2 px-2 py-0.5 rounded hover:bg-[var(--color-bg-elevated)] transition-colors"
- >
- <p className="text-[11px] font-mono text-[var(--color-text-primary)] truncate min-w-0">
- {silo.file_path}
- </p>
- <span className="text-[10px] text-[var(--color-text-tertiary)] shrink-0">
- {Math.round(silo.owner_pct * 100)}%
- </span>
- </a>
- </li>
- ))}
- {knowledgeMap.knowledge_silos.length > 3 && (
- <li>
- <a href={`/repos/${id}/ownership`} className="text-[10px] text-[var(--color-accent-primary)] hover:underline">
- +{knowledgeMap.knowledge_silos.length - 3} more
- </a>
- </li>
- )}
- </ul>
- </div>
- )}
- </CardContent>
- </Card>
- )}
-
- {knowledgeMap && (
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm font-medium">Onboarding Targets</CardTitle>
- </CardHeader>
- <CardContent>
- {knowledgeMap.onboarding_targets.length === 0 ? (
- <p className="text-xs text-[var(--color-text-tertiary)]">No graph data available.</p>
- ) : (
- <ul className="space-y-2">
- {knowledgeMap.onboarding_targets.slice(0, 5).map((target) => (
- <li key={target.path}>
- <a
- href={`/repos/${id}/graph?node=${encodeURIComponent(target.path)}`}
- className="block -mx-2 px-2 py-0.5 rounded hover:bg-[var(--color-bg-elevated)] transition-colors space-y-0.5"
- >
- <p className="text-[11px] font-mono text-[var(--color-text-primary)] truncate">
- {target.path}
- </p>
- <p className="text-[10px] text-[var(--color-text-tertiary)]">
- pagerank {target.pagerank.toFixed(4)} · {formatNumber(target.doc_words)} doc words
- </p>
- </a>
- </li>
- ))}
- </ul>
- )}
- </CardContent>
- </Card>
- )}
- </div>
- </TabsContent>
- </Tabs>
+ </>
+ )}
</div>
);
}
diff --git a/packages/web/src/app/repos/[id]/owners/[owner]/page.tsx b/packages/web/src/app/repos/[id]/owners/[owner]/page.tsx
index da92a7709..1b7594414 100644
--- a/packages/web/src/app/repos/[id]/owners/[owner]/page.tsx
+++ b/packages/web/src/app/repos/[id]/owners/[owner]/page.tsx
@@ -5,6 +5,7 @@ import useSWR from "swr";
import Link from "next/link";
import { ArrowLeft, Users } from "lucide-react";
import { OwnerProfileView } from "@repowise-dev/ui/owners/owner-profile";
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
import { getOwnerProfile } from "@/lib/api/owners";
@@ -55,9 +56,7 @@ export default function OwnerProfilePage() {
{data && (
<OwnerProfileView
owner={data}
- onSelectFile={(path) =>
- router.push(`/repos/${id}/wiki/${encodeURIComponent(path)}`)
- }
+ onSelectFile={(path) => router.push(fileEntityPath(`/repos/${id}`, path))}
onSelectModule={(mod) => router.push(`/repos/${id}/modules/${encodeURIComponent(mod)}`)}
onSelectCoAuthor={(c) => {
const k = c.email ?? `name:${c.name}`;
diff --git a/packages/web/src/app/repos/[id]/ownership/loading.tsx b/packages/web/src/app/repos/[id]/ownership/loading.tsx
deleted file mode 100644
index e3a3a6d7e..000000000
--- a/packages/web/src/app/repos/[id]/ownership/loading.tsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";
-
-export default function OwnershipLoading() {
- return <OwlLoader />;
-}
diff --git a/packages/web/src/app/repos/[id]/ownership/page.tsx b/packages/web/src/app/repos/[id]/ownership/page.tsx
index 8da07693a..120a110dd 100644
--- a/packages/web/src/app/repos/[id]/ownership/page.tsx
+++ b/packages/web/src/app/repos/[id]/ownership/page.tsx
@@ -1,173 +1,11 @@
-"use client";
-
-import { useState } from "react";
-import useSWR from "swr";
-import { useParams } from "next/navigation";
-import { Users, Shield } from "lucide-react";
-import { RoutedToRiskBanner } from "@/components/risk/routed-to-risk-banner";
-import { StatCard } from "@repowise-dev/ui/shared/stat-card";
-import { OwnershipTable } from "@repowise-dev/ui/git/ownership-table";
-import { ContributorBar } from "@repowise-dev/ui/git/contributor-bar";
-import { OwnershipTreemap } from "@repowise-dev/ui/git/ownership-treemap";
-import { BusFactorPanel } from "@repowise-dev/ui/git/bus-factor-panel";
-import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-import { getOwnership, getGitSummary, getHotspots } from "@/lib/api/git";
-import { HealthRisksPanel } from "@/components/health/health-risks-panel";
-import { formatNumber } from "@repowise-dev/ui/lib/format";
-import { cn } from "@/lib/utils/cn";
-import type { OwnershipEntry, GitSummaryResponse, HotspotResponse } from "@/lib/api/types";
-
-type Granularity = "module" | "file";
-
-export default function OwnershipPage() {
- const params = useParams<{ id: string }>();
- const id = params.id;
- const [granularity, setGranularity] = useState<Granularity>("module");
-
- const { data: entries, isLoading: loadingEntries } = useSWR<OwnershipEntry[]>(
- `ownership:${id}:${granularity}`,
- () => getOwnership(id, granularity),
- { revalidateOnFocus: false },
- );
-
- const { data: summary } = useSWR<GitSummaryResponse>(
- `git-summary:${id}`,
- () => getGitSummary(id),
- { revalidateOnFocus: false },
- );
-
- const { data: hotspotData } = useSWR<HotspotResponse[]>(
- `hotspots-for-ownership:${id}`,
- () => getHotspots(id, 100),
- { revalidateOnFocus: false },
- );
-
- const siloCount = (entries ?? []).filter((e) => e.is_silo).length;
- const busFactorRiskCount = (hotspotData ?? []).filter((h) => h.bus_factor <= 1).length;
-
- return (
- <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">
- <RoutedToRiskBanner repoId={id} tab="heatmap" tabLabel="Heatmap (ownership)" />
- <div>
- <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 flex items-center gap-2">
- <Users className="h-5 w-5 text-[var(--color-accent-primary)]" />
- Code Ownership
- </h1>
- <p className="text-sm text-[var(--color-text-secondary)]">
- Who owns what — silo detection and bus factor risk.
- </p>
- </div>
-
- {/* Summary stats */}
- {summary && (
- <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
- <StatCard
- label="Total Files"
- value={formatNumber(summary.total_files)}
- description="with git history"
- />
- <StatCard
- label="Silo Modules"
- value={siloCount}
- description="owner >80%"
- trend={siloCount > 0 ? { value: `${siloCount}`, positive: false } : undefined}
- />
- <StatCard
- label="Contributors"
- value={summary.top_owners.length}
- description="unique owners"
- />
- <StatCard
- label="Bus Factor Risk"
- value={formatNumber(busFactorRiskCount)}
- description="files with factor ≤ 1"
- icon={<Shield className="h-4 w-4 text-red-400" />}
- />
- </div>
- )}
-
- {/* Treemap visualization */}
- {entries && entries.length > 0 && (
- <Card>
- <CardHeader className="pb-2">
- <div className="flex items-center justify-between">
- <CardTitle className="text-sm">Ownership Map</CardTitle>
- {/* Granularity toggle */}
- <div className="flex rounded-md border border-[var(--color-border-default)] overflow-hidden text-xs">
- {(["module", "file"] as Granularity[]).map((g) => (
- <button
- key={g}
- onClick={() => setGranularity(g)}
- className={cn(
- "px-3 py-1.5 font-medium transition-colors capitalize",
- granularity === g
- ? "bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)]"
- : "bg-transparent text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]",
- )}
- >
- {g}
- </button>
- ))}
- </div>
- </div>
- </CardHeader>
- <CardContent className="pt-0">
- <OwnershipTreemap entries={entries} />
- </CardContent>
- </Card>
- )}
-
- {/* Bus Factor + Contributor sidebar */}
- <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
- {hotspotData && hotspotData.length > 0 && (
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">Bus Factor Analysis</CardTitle>
- </CardHeader>
- <CardContent className="pt-0">
- <BusFactorPanel hotspots={hotspotData} />
- </CardContent>
- </Card>
- )}
-
- {summary && summary.top_owners.length > 0 && (
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">Top Contributors</CardTitle>
- </CardHeader>
- <CardContent className="pt-0">
- <ContributorBar owners={summary.top_owners} />
- <div className="mt-3 space-y-1.5">
- {summary.top_owners.slice(0, 10).map((o, i) => (
- <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 ?? 0) * 100)}%
- </span>
- </div>
- ))}
- </div>
- </CardContent>
- </Card>
- )}
- </div>
-
- {/* Detail table + health sidecar */}
- <div className="grid grid-cols-1 gap-6 xl:grid-cols-4">
- <div className="xl:col-span-3">
- {loadingEntries ? (
- <div className="space-y-2">
- {Array.from({ length: 8 }).map((_, i) => (
- <Skeleton key={i} className="h-10 w-full" />
- ))}
- </div>
- ) : (
- <OwnershipTable entries={entries ?? []} repoId={id} />
- )}
- </div>
- <HealthRisksPanel repoId={id} title="Lowest-health files" limit={6} />
- </div>
- </div>
- );
+import { redirect } from "next/navigation";
+
+/** Legacy route — redirects into the consolidated IA. */
+export default async function LegacyRedirect({
+ params,
+}: {
+ params: Promise<{ id: string }>;
+}) {
+ const { id } = await params;
+ redirect(`/repos/${id}/owners`);
}
diff --git a/packages/web/src/app/repos/[id]/page.tsx b/packages/web/src/app/repos/[id]/page.tsx
index da05478f4..c6a0ad943 100644
--- a/packages/web/src/app/repos/[id]/page.tsx
+++ b/packages/web/src/app/repos/[id]/page.tsx
@@ -1,63 +1,11 @@
-import type { Metadata } from "next";
-import { notFound } from "next/navigation";
-import { Hash } from "lucide-react";
-import { getRepo } from "@/lib/api/repos";
-import { Badge } from "@repowise-dev/ui/ui/badge";
-import { ChatInterface } from "@/components/chat/chat-interface";
+import { redirect } from "next/navigation";
-interface Props {
+/** Repo root — Overview is the landing page; Chat lives at /chat. */
+export default async function RepoRootPage({
+ params,
+}: {
params: Promise<{ id: string }>;
-}
-
-export async function generateMetadata({ params }: Props): Promise<Metadata> {
- const { id } = await params;
- try {
- const repo = await getRepo(id);
- return { title: `${repo.name} — Chat` };
- } catch {
- return { title: "Repository" };
- }
-}
-
-export default async function RepoChatPage({ params }: Props) {
+}) {
const { id } = await params;
-
- let repo;
- try {
- repo = await getRepo(id);
- } catch {
- notFound();
- }
-
- return (
- <div className="flex flex-col h-full">
- {/* Compact header */}
- <div className="px-4 pt-3 pb-2 flex items-center justify-between shrink-0 border-b border-[var(--color-border-default)]">
- <div className="min-w-0">
- <h1 className="text-sm font-semibold text-[var(--color-text-primary)] truncate">
- {repo.name}
- </h1>
- <p className="text-[10px] font-mono text-[var(--color-text-tertiary)] truncate">
- {repo.local_path}
- </p>
- </div>
- <div className="flex items-center gap-1.5 shrink-0 ml-3">
- {repo.head_commit && (
- <Badge variant="outline" className="text-[10px] h-5">
- <Hash className="h-2.5 w-2.5" />
- {repo.head_commit.slice(0, 7)}
- </Badge>
- )}
- <Badge variant="outline" className="text-[10px] h-5">
- {repo.default_branch}
- </Badge>
- </div>
- </div>
-
- {/* Chat interface fills remaining height */}
- <div className="flex-1 min-h-0">
- <ChatInterface repoId={id} repoName={repo.name} />
- </div>
- </div>
- );
+ redirect(`/repos/${id}/overview`);
}
diff --git a/packages/web/src/app/repos/[id]/risk/page.tsx b/packages/web/src/app/repos/[id]/risk/page.tsx
index 2df5b5740..25aebafea 100644
--- a/packages/web/src/app/repos/[id]/risk/page.tsx
+++ b/packages/web/src/app/repos/[id]/risk/page.tsx
@@ -1,84 +1,15 @@
-"use client";
-
-import { useParams, useRouter, useSearchParams } from "next/navigation";
-import { useCallback } from "react";
-import { ShieldAlert } from "lucide-react";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@repowise-dev/ui/ui/tabs";
-import { HeatmapTab } from "@/components/risk/heatmap-tab";
-import { HotspotsTab } from "@/components/risk/hotspots-tab";
-import { DeadCodeTab } from "@/components/risk/dead-code-tab";
-import { ImpactTab } from "@/components/risk/impact-tab";
-import { ModulesTab } from "@/components/risk/modules-tab";
-import { SecurityTab } from "@/components/risk/security-tab";
-import { RiskSummaryStrip } from "@/components/risk/risk-summary-strip";
-
-const TABS = ["heatmap", "hotspots", "modules", "dead-code", "impact", "security"] as const;
-type TabId = (typeof TABS)[number];
-
-export default function RiskPage() {
- const params = useParams<{ id: string }>();
- const router = useRouter();
- const searchParams = useSearchParams();
- const repoId = params.id;
-
- const rawTab = searchParams.get("tab") as TabId | null;
- const activeTab: TabId = rawTab && TABS.includes(rawTab) ? rawTab : "heatmap";
-
- const setTab = useCallback(
- (next: string) => {
- const sp = new URLSearchParams(searchParams.toString());
- if (next === "heatmap") sp.delete("tab");
- else sp.set("tab", next);
- const qs = sp.toString();
- router.replace(qs ? `?${qs}` : "?", { scroll: false });
- },
- [router, searchParams],
- );
-
- return (
- <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">
- <div>
- <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 flex items-center gap-2">
- <ShieldAlert className="h-5 w-5 text-orange-500" />
- Risk
- </h1>
- <p className="text-sm text-[var(--color-text-secondary)]">
- Where the risk is concentrated — ownership silos, churn hotspots, dead code, and PR
- blast radius — in one place.
- </p>
- </div>
-
- <RiskSummaryStrip repoId={repoId} />
-
- <Tabs value={activeTab} onValueChange={setTab} className="space-y-4">
- <TabsList className="h-auto flex-wrap">
- <TabsTrigger value="heatmap">Heatmap</TabsTrigger>
- <TabsTrigger value="hotspots">Hotspots</TabsTrigger>
- <TabsTrigger value="modules">Modules</TabsTrigger>
- <TabsTrigger value="dead-code">Dead code</TabsTrigger>
- <TabsTrigger value="impact">Impact analyzer</TabsTrigger>
- <TabsTrigger value="security">Security</TabsTrigger>
- </TabsList>
-
- <TabsContent value="heatmap" className="space-y-6">
- <HeatmapTab repoId={repoId} />
- </TabsContent>
- <TabsContent value="hotspots" className="space-y-6">
- <HotspotsTab repoId={repoId} />
- </TabsContent>
- <TabsContent value="modules" className="space-y-6">
- <ModulesTab repoId={repoId} />
- </TabsContent>
- <TabsContent value="dead-code" className="space-y-6">
- <DeadCodeTab repoId={repoId} />
- </TabsContent>
- <TabsContent value="impact" className="space-y-6">
- <ImpactTab repoId={repoId} />
- </TabsContent>
- <TabsContent value="security" className="space-y-6">
- <SecurityTab repoId={repoId} />
- </TabsContent>
- </Tabs>
- </div>
- );
+import { redirect } from "next/navigation";
+
+/** Legacy route — Risk merged into Code Health. Tab names map 1:1. */
+export default async function LegacyRiskRedirect({
+ params,
+ searchParams,
+}: {
+ params: Promise<{ id: string }>;
+ searchParams: Promise<Record<string, string | string[] | undefined>>;
+}) {
+ const { id } = await params;
+ const sp = await searchParams;
+ const tab = typeof sp.tab === "string" ? sp.tab : "heatmap";
+ redirect(`/repos/${id}/code-health?tab=${encodeURIComponent(tab)}`);
}
diff --git a/packages/web/src/app/repos/[id]/security/page.tsx b/packages/web/src/app/repos/[id]/security/page.tsx
index 28a6602a6..9384e5e57 100644
--- a/packages/web/src/app/repos/[id]/security/page.tsx
+++ b/packages/web/src/app/repos/[id]/security/page.tsx
@@ -1,17 +1,11 @@
-"use client";
-
-import { useEffect } from "react";
-import { useParams, useRouter } from "next/navigation";
-
-// Security now lives as a tab under Risk. Keep this route as a redirect so
-// existing links / bookmarks continue to work.
-export default function SecurityPage() {
- const params = useParams<{ id: string }>();
- const router = useRouter();
-
- useEffect(() => {
- router.replace(`/repos/${params.id}/risk?tab=security`);
- }, [params.id, router]);
-
- return null;
+import { redirect } from "next/navigation";
+
+/** Legacy route — redirects into the consolidated IA. */
+export default async function LegacyRedirect({
+ params,
+}: {
+ params: Promise<{ id: string }>;
+}) {
+ const { id } = await params;
+ redirect(`/repos/${id}/code-health?tab=security`);
}
diff --git a/packages/web/src/app/repos/[id]/settings/page.tsx b/packages/web/src/app/repos/[id]/settings/page.tsx
index 8676b42df..2344a44f8 100644
--- a/packages/web/src/app/repos/[id]/settings/page.tsx
+++ b/packages/web/src/app/repos/[id]/settings/page.tsx
@@ -1,6 +1,8 @@
import type { Metadata } from "next";
+import Link from "next/link";
import { notFound } from "next/navigation";
import { Settings } from "lucide-react";
+import { WebhookSection } from "@/components/settings/webhook-section";
import { getRepo } from "@/lib/api/repos";
import { getCoordinatorHealth } from "@/lib/api/health";
import { RepoSettingsFormWrapper as RepoSettingsForm } from "@/components/repos/repo-settings-form-wrapper";
@@ -80,32 +82,30 @@ export default async function RepoSettingsPage({ params }: Props) {
<Separator />
- <div>
- <h2 className="text-sm font-medium text-[var(--color-text-primary)] mb-1">Webhook URLs</h2>
- <p className="text-xs text-[var(--color-text-tertiary)] mb-3">
- Configure your repository host to call these endpoints on push events.
- </p>
- <div className="space-y-2">
- {(["github", "gitlab"] as const).map((host) => (
- <div key={host} className="rounded-md bg-[var(--color-bg-inset)] px-3 py-2">
- <p className="text-xs font-medium text-[var(--color-text-tertiary)] mb-0.5 capitalize">
- {host}
- </p>
- <p className="text-xs font-mono text-[var(--color-text-secondary)] break-all">
- {`[your-server]/api/webhooks/${host}`}
- </p>
- </div>
- ))}
- </div>
- </div>
+ {/* Shared with global settings — interpolates the real server URL. */}
+ <WebhookSection />
+
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Connection, provider and MCP configuration live in{" "}
+ <Link
+ href="/settings"
+ className="text-[var(--color-accent-primary)] hover:underline"
+ >
+ global settings
+ </Link>
+ .
+ </p>
<Separator />
- <Card className="border-red-900/30">
+ <Card className="border-[var(--color-error)]/40 bg-[var(--color-error)]/5">
<CardHeader>
- <CardTitle className="text-sm font-medium text-red-400">Danger Zone</CardTitle>
+ <CardTitle className="text-sm font-medium text-[var(--color-error)]">
+ Danger Zone
+ </CardTitle>
<CardDescription>
Permanently delete this repository and all its generated pages, symbols, and history.
+ This cannot be undone.
</CardDescription>
</CardHeader>
<CardContent>
diff --git a/packages/web/src/app/repos/[id]/symbols/[symbolId]/loading.tsx b/packages/web/src/app/repos/[id]/symbols/[symbolId]/loading.tsx
new file mode 100644
index 000000000..f48c0fc25
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/symbols/[symbolId]/loading.tsx
@@ -0,0 +1,20 @@
+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+
+export default function SymbolPageLoading() {
+ return (
+ <div className="p-4 sm:p-6 max-w-[1100px] space-y-4">
+ <Skeleton className="h-6 w-1/2" />
+ <Skeleton className="h-4 w-1/3" />
+ <Skeleton className="h-20 w-full" />
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-6">
+ {Array.from({ length: 6 }).map((_, i) => (
+ <Skeleton key={i} className="h-16" />
+ ))}
+ </div>
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
+ <Skeleton className="h-48" />
+ <Skeleton className="h-48" />
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/app/repos/[id]/symbols/[symbolId]/page.tsx b/packages/web/src/app/repos/[id]/symbols/[symbolId]/page.tsx
new file mode 100644
index 000000000..200c63c85
--- /dev/null
+++ b/packages/web/src/app/repos/[id]/symbols/[symbolId]/page.tsx
@@ -0,0 +1,33 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { getSymbolDetail } from "@/lib/api/symbols";
+import { SymbolPage } from "@repowise-dev/ui/symbols";
+import type { SymbolDetailResponse } from "@repowise-dev/types/symbols";
+
+interface Props {
+ params: Promise<{ id: string; symbolId: string }>;
+}
+
+export async function generateMetadata({ params }: Props): Promise<Metadata> {
+ const { symbolId } = await params;
+ const decoded = decodeURIComponent(symbolId);
+ return { title: decoded.split("::").pop() ?? decoded };
+}
+
+export default async function SymbolEntityPage({ params }: Props) {
+ const { id, symbolId } = await params;
+ const decoded = decodeURIComponent(symbolId);
+
+ let detail: SymbolDetailResponse;
+ try {
+ detail = await getSymbolDetail(id, decoded);
+ } catch {
+ notFound();
+ }
+
+ return (
+ <div className="p-4 sm:p-6 max-w-[1100px]">
+ <SymbolPage data={detail} repoId={id} />
+ </div>
+ );
+}
diff --git a/packages/web/src/app/repos/[id]/symbols/loading.tsx b/packages/web/src/app/repos/[id]/symbols/loading.tsx
deleted file mode 100644
index 7b1772697..000000000
--- a/packages/web/src/app/repos/[id]/symbols/loading.tsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";
-
-export default function SymbolsLoading() {
- return <OwlLoader />;
-}
diff --git a/packages/web/src/app/repos/[id]/symbols/page.tsx b/packages/web/src/app/repos/[id]/symbols/page.tsx
index 23cb74c4c..5692535c6 100644
--- a/packages/web/src/app/repos/[id]/symbols/page.tsx
+++ b/packages/web/src/app/repos/[id]/symbols/page.tsx
@@ -1,28 +1,11 @@
-import type { Metadata } from "next";
-import { Code2 } from "lucide-react";
-import { SymbolTableWrapper as SymbolTable } from "@/components/symbols/symbol-table-wrapper";
+import { redirect } from "next/navigation";
-export const metadata: Metadata = { title: "Symbols" };
-
-export default async function SymbolsPage({
+/** Legacy route — the symbol index now lives under Architecture. */
+export default async function LegacySymbolsRedirect({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
-
- return (
- <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">
- <div>
- <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 flex items-center gap-2">
- <Code2 className="h-5 w-5 text-[var(--color-accent-primary)]" />
- Symbol Index
- </h1>
- <p className="text-sm text-[var(--color-text-secondary)]">
- Searchable index of all functions, classes, and exports.
- </p>
- </div>
- <SymbolTable repoId={id} />
- </div>
- );
+ redirect(`/repos/${id}/architecture?view=symbols`);
}
diff --git a/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsx b/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsx
index 23b7d7998..65637986b 100644
--- a/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsx
+++ b/packages/web/src/app/repos/[id]/wiki/[...slug]/page.tsx
@@ -21,7 +21,10 @@ import { Badge } from "@repowise-dev/ui/ui/badge";
import { Separator } from "@repowise-dev/ui/ui/separator";
import { formatRelativeTime, formatTokens } from "@repowise-dev/ui/lib/format";
import { CoChangeList } from "@repowise-dev/ui/git/co-change-list";
-import { Hash, Cpu, StickyNote, Network } from "lucide-react";
+import { Hash, Cpu, FileCode2 } from "lucide-react";
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
+import { HumanNotes } from "@/components/wiki/human-notes";
+import { VersionHistoryWrapper } from "@/components/wiki/version-history";
import type { GraphMetricsResponse } from "@/lib/api/types";
interface Props {
@@ -106,6 +109,17 @@ export default async function WikiPageRoute({ params }: Props) {
</Badge>
)}
+ {/* Canonical file page — everything about this file in one place. */}
+ {page.page_type === "file_page" && page.target_path && (
+ <Link
+ href={fileEntityPath(`/repos/${id}`, page.target_path)}
+ className="hidden sm:inline-flex shrink-0 items-center gap-1 rounded-md border border-[var(--color-border-default)] px-2 py-0.5 text-xs text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ >
+ <FileCode2 className="h-3 w-3" />
+ File page
+ </Link>
+ )}
+
{/* Regenerate */}
<RegenerateButtonWrapper pageId={page.id} repoId={id} />
</div>
@@ -116,19 +130,17 @@ export default async function WikiPageRoute({ params }: Props) {
{page.title}
</h1>
- {page.human_notes && (
- <div className="mb-5 rounded-lg border border-[var(--color-border-accent)] bg-[var(--color-accent-blue)]/5 px-4 py-3">
- <div className="flex items-center gap-1.5 mb-1.5">
- <StickyNote className="h-3.5 w-3.5 text-[var(--color-accent-blue)]" />
- <span className="text-xs font-medium text-[var(--color-accent-blue)] uppercase tracking-wider">
- Human Notes
- </span>
- </div>
- <p className="text-sm text-[var(--color-text-secondary)] whitespace-pre-wrap leading-relaxed">
- {page.human_notes}
- </p>
+ <HumanNotes pageId={page.id} initialNotes={page.human_notes ?? null} />
+
+ {/* Inline collapsible ToC for viewports without the right sidebar. */}
+ <details className="xl:hidden mb-5 rounded-lg border border-[var(--color-border-default)] px-4 py-2.5">
+ <summary className="cursor-pointer text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ On this page
+ </summary>
+ <div className="pt-2">
+ <TableOfContents content={page.content} />
</div>
- )}
+ </details>
<article className="prose prose-invert max-w-none leading-relaxed overflow-hidden">
<WikiRenderer
@@ -155,6 +167,20 @@ export default async function WikiPageRoute({ params }: Props) {
)}
</div>
+ {/* Version changelog — full content history with diffs */}
+ {versionList.length > 0 && (
+ <div className="px-4 sm:px-6 pb-6 max-w-[768px] mx-auto">
+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-2">
+ Version history
+ </p>
+ <VersionHistoryWrapper
+ pageId={page.id}
+ currentVersion={page.version}
+ currentContent={page.content}
+ />
+ </div>
+ )}
+
{/* Bottom bar */}
<div className="border-t border-[var(--color-border-default)] px-4 sm:px-6 py-3 flex flex-wrap items-center gap-x-4 gap-y-1.5 text-xs text-[var(--color-text-tertiary)]">
<span>Generated {formatRelativeTime(page.updated_at)}</span>
@@ -218,7 +244,7 @@ export default async function WikiPageRoute({ params }: Props) {
<div className="flex justify-between text-xs">
<span className="text-[var(--color-text-tertiary)]">Community</span>
<Link
- href={`/repos/${id}/graph?colorMode=community`}
+ href={`/repos/${id}/architecture?view=graph&colorMode=community`}
className="text-[var(--color-accent)] hover:underline font-mono text-[11px]"
>
{graphMetrics.community_label}
@@ -256,6 +282,11 @@ export default async function WikiPageRoute({ params }: Props) {
<BacklinksPanel
backlinks={getBacklinks(page.metadata)}
repoId={id}
+ renderLink={({ href, className, title, children }) => (
+ <Link href={href} className={className} title={title}>
+ {children}
+ </Link>
+ )}
/>
{/* Security findings panel */}
diff --git a/packages/web/src/app/settings/page.tsx b/packages/web/src/app/settings/page.tsx
index eeade2231..540d9a0b0 100644
--- a/packages/web/src/app/settings/page.tsx
+++ b/packages/web/src/app/settings/page.tsx
@@ -20,6 +20,11 @@ export default function SettingsPage() {
<ProviderSection />
<WebhookSection />
<McpSection />
+
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Per-repository options (sync, exclude patterns, deletion) live on each
+ repo&apos;s own Settings page, reachable from its sidebar.
+ </p>
</div>
);
}
diff --git a/packages/web/src/app/workspace/contracts/page.tsx b/packages/web/src/app/workspace/contracts/page.tsx
index 3d2c06299..4d910a741 100644
--- a/packages/web/src/app/workspace/contracts/page.tsx
+++ b/packages/web/src/app/workspace/contracts/page.tsx
@@ -8,6 +8,7 @@ import { ContractLinksTable } from "@repowise-dev/ui/workspace/contract-links-ta
import { ContractTypeBadge, RoleBadge } from "@repowise-dev/ui/workspace/contract-type-badge";
import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
import { StatCard } from "@repowise-dev/ui/shared/stat-card";
+import { EmptyState } from "@repowise-dev/ui/shared";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
const TYPE_OPTIONS = [
@@ -178,9 +179,11 @@ export default function ContractsPage() {
))}
</div>
) : (data?.contracts ?? []).length === 0 ? (
- <p className="text-sm text-[var(--color-text-tertiary)] py-4 text-center">
- No contracts detected.
- </p>
+ <EmptyState
+ className="p-6"
+ title="No contracts detected"
+ description="API contracts are detected during workspace indexing when providers and consumers share schemas."
+ />
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm">
diff --git a/packages/web/src/app/workspace/page.tsx b/packages/web/src/app/workspace/page.tsx
index a40bab9ba..b6b5d5a82 100644
--- a/packages/web/src/app/workspace/page.tsx
+++ b/packages/web/src/app/workspace/page.tsx
@@ -57,6 +57,32 @@ export default async function WorkspaceDashboardPage() {
}
const avgCoverage = reposWithStats > 0 ? Math.round(totalCoveragePctSum / reposWithStats) : 0;
+ // "Needs attention" rollup across the whole workspace (not a page slice).
+ const needsIndex = wsRepos.filter(
+ (r) => (r.status ?? (r.repo_id ? "indexed" : "needs_index")) === "needs_index",
+ );
+ const missingDirs = wsRepos.filter((r) => r.status === "missing_dir");
+ const docsSkipped = wsRepos.filter((r) => r.docs_skip_reason);
+ const attentionItems: string[] = [];
+ if (needsIndex.length > 0)
+ attentionItems.push(
+ `${needsIndex.length} repo${needsIndex.length === 1 ? "" : "s"} not indexed yet (${needsIndex
+ .slice(0, 3)
+ .map((r) => r.alias)
+ .join(", ")}${needsIndex.length > 3 ? ", …" : ""})`,
+ );
+ if (missingDirs.length > 0)
+ attentionItems.push(
+ `${missingDirs.length} repo director${missingDirs.length === 1 ? "y is" : "ies are"} missing on disk (${missingDirs
+ .slice(0, 3)
+ .map((r) => r.alias)
+ .join(", ")}${missingDirs.length > 3 ? ", …" : ""})`,
+ );
+ if (docsSkipped.length > 0)
+ attentionItems.push(
+ `docs skipped for ${docsSkipped.length} repo${docsSkipped.length === 1 ? "" : "s"}`,
+ );
+
return (
<div className="p-5 sm:p-8 space-y-8 max-w-[1200px]">
{/* Header */}
@@ -85,6 +111,20 @@ export default async function WorkspaceDashboardPage() {
)}
</div>
+ {/* Needs attention */}
+ {attentionItems.length > 0 && (
+ <div className="rounded-lg border border-[var(--color-warning)]/40 bg-[var(--color-warning)]/5 px-4 py-3">
+ <p className="text-xs font-medium uppercase tracking-wider text-[var(--color-warning)]">
+ Needs attention
+ </p>
+ <ul className="mt-1.5 list-disc space-y-0.5 pl-4 text-xs text-[var(--color-text-secondary)]">
+ {attentionItems.map((item) => (
+ <li key={item}>{item}</li>
+ ))}
+ </ul>
+ </div>
+ )}
+
{/* Aggregate Stats */}
<div className="grid grid-cols-2 gap-4 lg:grid-cols-5">
<StatCard
@@ -135,18 +175,10 @@ export default async function WorkspaceDashboardPage() {
docsSkipReason={wsRepo.docs_skip_reason ?? null}
stats={wsRepo.file_count > 0 ? {
file_count: wsRepo.file_count,
- symbol_count: wsRepo.symbol_count,
doc_coverage_pct: wsRepo.doc_coverage_pct,
- entry_point_count: 0,
- freshness_score: 0,
- dead_export_count: 0,
} : null}
gitSummary={wsRepo.file_count > 0 ? {
- total_files: wsRepo.file_count,
hotspot_count: wsRepo.hotspot_count,
- stable_count: 0,
- average_churn_percentile: 0,
- top_owners: [],
} : null}
actions={
status !== "missing_dir" ? (
diff --git a/packages/web/src/app/workspace/workspace-graph-section.tsx b/packages/web/src/app/workspace/workspace-graph-section.tsx
index 796741353..7fc207276 100644
--- a/packages/web/src/app/workspace/workspace-graph-section.tsx
+++ b/packages/web/src/app/workspace/workspace-graph-section.tsx
@@ -64,7 +64,7 @@ export function WorkspaceGraphSection({ repoCount }: WorkspaceGraphSectionProps)
) : data && data.nodes.length >= 2 ? (
<WorkspaceGraph
data={data}
- onRepoClick={(repoId) => router.push(`/repos/${repoId}/graph`)}
+ onRepoClick={(repoId) => router.push(`/repos/${repoId}/architecture?view=graph`)}
/>
) : (
<div className="flex items-center justify-center h-full">
diff --git a/packages/web/src/components/architecture/c4-view.tsx b/packages/web/src/components/architecture/c4-view.tsx
new file mode 100644
index 000000000..a34df106d
--- /dev/null
+++ b/packages/web/src/components/architecture/c4-view.tsx
@@ -0,0 +1,521 @@
+"use client";
+
+/**
+ * C4 / Architecture diagrams — `/repos/[id]/c4`.
+ *
+ * Supports two modes:
+ * - mode=c4 — legacy C4 three-level diagram
+ * - mode=architecture — new unified architecture view (default)
+ *
+ * URL params are synced bidirectionally with the Zustand store so that
+ * refresh + share preserve the view state.
+ */
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useQueryState, parseAsInteger, parseAsString, parseAsStringLiteral } from "nuqs";
+import {
+ C4Diagram,
+ type C4Level,
+ useArchitectureStore,
+ useArchitectureLayout,
+ useArchitectureNavigation,
+ archNodeTypes,
+ archEdgeTypes,
+ SearchBar,
+ ArchBreadcrumb,
+ ArchLegend,
+ PersonaSelector,
+ NodeTypeCategoryFilters,
+ FilterPanel,
+ CodeViewer,
+ PathFinderModal,
+ type Persona,
+ KEYFRAMES,
+} from "@repowise-dev/ui/c4";
+import {
+ Background,
+ BackgroundVariant,
+ Controls,
+ MiniMap,
+ ReactFlow,
+ ReactFlowProvider,
+ useReactFlow,
+} from "@xyflow/react";
+import "@xyflow/react/dist/style.css";
+import { useC4L1, useC4L2, useC4L3 } from "@/lib/hooks/use-c4";
+import { useArchitectureView } from "@/lib/hooks/use-architecture";
+import { useC4DocsPathSet } from "@/lib/hooks/use-c4-context";
+import { useRepo } from "@/lib/hooks/use-repo";
+import { getC4Mermaid } from "@/lib/api/c4";
+import { C4DetailPanelHost } from "@/components/c4/c4-detail-panel-host";
+import { ArchDetailPanelHost } from "@/components/c4/arch-detail-panel-host";
+import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
+import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";
+import { AlertTriangle, Compass } from "lucide-react";
+
+// First-visit discoverability flag for the guided tour.
+const TOUR_SEEN_KEY = "repowise:arch-tour-seen";
+
+const MODE_VALUES = ["c4", "architecture"] as const;
+const VIEW_VALUES = ["overview", "groups", "detail"] as const;
+const PERSONA_VALUES = ["overview", "learn", "deep-dive"] as const;
+// Unified click grammar (kg-ux plan B5): single click = select + inspect on
+// every node kind. Only true non-entities stay unselectable — portals are
+// navigation stubs, the scope frame is a pointer-events-none underlay.
+const SYNTHETIC_NODE_TYPES = new Set(["portal", "scopeFrame"]);
+
+function clampLevel(n: number | null): C4Level {
+ return n === 1 ? 1 : n === 3 ? 3 : 2;
+}
+
+export function C4View({ repoId, legacy }: { repoId: string; legacy?: boolean }) {
+ const { repo } = useRepo(repoId);
+
+ // The hosting Architecture page decides Layers vs legacy C4 via `?view=`;
+ // `?mode=c4` is honored as a legacy deep-link fallback.
+ const [mode] = useQueryState(
+ "mode",
+ parseAsStringLiteral(MODE_VALUES).withDefault("architecture"),
+ );
+ const showLegacy = legacy ?? mode === "c4";
+
+ return (
+ <div className="flex flex-col h-full">
+ {showLegacy ? (
+ <LegacyC4View repoId={repoId} repoName={repo?.name ?? "System"} />
+ ) : (
+ <ArchitectureViewPage repoId={repoId} repoName={repo?.name ?? "System"} />
+ )}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Architecture View (new)
+// ---------------------------------------------------------------------------
+
+function ArchitectureViewPage({ repoId, repoName }: { repoId: string; repoName: string }) {
+ return (
+ <ReactFlowProvider>
+ <ArchitectureViewInner repoId={repoId} repoName={repoName} />
+ </ReactFlowProvider>
+ );
+}
+
+function ArchitectureViewInner({ repoId, repoName }: { repoId: string; repoName: string }) {
+ const { view, error, isLoading } = useArchitectureView(repoId);
+ const { fitView } = useReactFlow();
+
+ // Renamed from "view" — the parent Architecture page owns `?view=` for its
+ // sub-view switcher (graph | c4 | symbols).
+ const [, setViewParam] = useQueryState(
+ "c4view",
+ parseAsStringLiteral(VIEW_VALUES).withDefault("overview"),
+ );
+ const [layerParam, setLayerParam] = useQueryState("layer", parseAsString);
+ const [groupParam, setGroupParam] = useQueryState("group", parseAsString);
+ const [nodeParam, setNodeParam] = useQueryState("node", parseAsString);
+ const [personaParam, setPersonaParam] = useQueryState(
+ "persona",
+ parseAsStringLiteral(PERSONA_VALUES).withDefault("overview"),
+ );
+
+ const setView = useArchitectureStore((s) => s.setView);
+ const navigationLevel = useArchitectureStore((s) => s.navigationLevel);
+ const activeLayerId = useArchitectureStore((s) => s.activeLayerId);
+ const activeSubGroupId = useArchitectureStore((s) => s.activeSubGroupId);
+ const selectedNodeId = useArchitectureStore((s) => s.selectedNodeId);
+ const persona = useArchitectureStore((s) => s.persona);
+ const drillIntoLayer = useArchitectureStore((s) => s.drillIntoLayer);
+ const drillIntoSubGroup = useArchitectureStore((s) => s.drillIntoSubGroup);
+ const selectNode = useArchitectureStore((s) => s.selectNode);
+ const setPersona = useArchitectureStore((s) => s.setPersona);
+ const setReactFlowInstance = useArchitectureStore((s) => s.setReactFlowInstance);
+ const pathFinderOpen = useArchitectureStore((s) => s.pathFinderOpen);
+ const tourActive = useArchitectureStore((s) => s.tourActive);
+ const startTour = useArchitectureStore((s) => s.startTour);
+
+ // "Take the tour" is highlighted until first taken (localStorage flag).
+ const [tourSeen, setTourSeen] = useState(true);
+ useEffect(() => {
+ setTourSeen(localStorage.getItem(TOUR_SEEN_KEY) === "1");
+ }, []);
+ const handleStartTour = useCallback(() => {
+ localStorage.setItem(TOUR_SEEN_KEY, "1");
+ setTourSeen(true);
+ startTour();
+ }, [startTour]);
+
+ useEffect(() => {
+ if (view) setView(view);
+ }, [view, setView]);
+
+ const initializedRef = useRef(false);
+ useEffect(() => {
+ if (!view || initializedRef.current) return;
+ initializedRef.current = true;
+
+ if (personaParam && personaParam !== "overview") {
+ setPersona(personaParam as Persona);
+ }
+ if (layerParam) {
+ drillIntoLayer(layerParam);
+ }
+ if (groupParam) {
+ drillIntoSubGroup(groupParam);
+ }
+ if (nodeParam) {
+ selectNode(nodeParam);
+ }
+ }, [view, layerParam, groupParam, nodeParam, personaParam,
+ drillIntoLayer, drillIntoSubGroup, selectNode, setPersona]);
+
+ const syncingRef = useRef(false);
+ useEffect(() => {
+ // Until the deep-link restore above has run, the store still holds its
+ // default overview state — syncing that to the URL would null out the
+ // very params the restore is about to read, so every shared link
+ // snapped back to the overview.
+ if (!initializedRef.current) return;
+ if (syncingRef.current) return;
+ syncingRef.current = true;
+ void setViewParam(
+ navigationLevel === "layer-detail"
+ ? "detail"
+ : navigationLevel === "layer-groups"
+ ? "groups"
+ : "overview",
+ );
+ void setLayerParam(activeLayerId);
+ void setGroupParam(activeSubGroupId);
+ void setNodeParam(selectedNodeId);
+ void setPersonaParam(persona);
+ syncingRef.current = false;
+ }, [navigationLevel, activeLayerId, activeSubGroupId, selectedNodeId, persona,
+ setViewParam, setLayerParam, setGroupParam, setNodeParam, setPersonaParam]);
+
+ useArchitectureNavigation();
+
+ const { nodes, edges, loading: layoutLoading, hiddenEdgeCount } = useArchitectureLayout();
+
+ const pendingFitRef = useRef(false);
+ const prevNavRef = useRef({ navigationLevel, activeLayerId });
+ useEffect(() => {
+ if (
+ prevNavRef.current.navigationLevel !== navigationLevel ||
+ prevNavRef.current.activeLayerId !== activeLayerId
+ ) {
+ pendingFitRef.current = true;
+ prevNavRef.current = { navigationLevel, activeLayerId };
+ }
+ }, [navigationLevel, activeLayerId]);
+
+ useEffect(() => {
+ if (!pendingFitRef.current || nodes.length === 0) return;
+ pendingFitRef.current = false;
+ const raf = requestAnimationFrame(() => {
+ fitView({ duration: 400, padding: 0.2 });
+ });
+ return () => cancelAnimationFrame(raf);
+ }, [nodes, fitView]);
+
+ // Camera ease on select (kg-ux plan B5): frame the selected node without
+ // drilling. Eases once per selection — layout refreshes (dimming etc.)
+ // never re-center a camera the user has panned away.
+ const lastEasedRef = useRef<string | null>(null);
+ useEffect(() => {
+ if (!selectedNodeId) {
+ lastEasedRef.current = null;
+ return;
+ }
+ if (lastEasedRef.current === selectedNodeId) return;
+ if (!nodes.some((n) => n.id === selectedNodeId)) return;
+ lastEasedRef.current = selectedNodeId;
+ const raf = requestAnimationFrame(() => {
+ fitView({ nodes: [{ id: selectedNodeId }], duration: 250, padding: 0.4, maxZoom: 1.15 });
+ });
+ return () => cancelAnimationFrame(raf);
+ }, [selectedNodeId, nodes, fitView]);
+
+ const handleNodeClick = useCallback(
+ (_: React.MouseEvent, node: { id: string; type?: string }) => {
+ if (SYNTHETIC_NODE_TYPES.has(node.type ?? "")) return;
+ selectNode(node.id);
+ },
+ [selectNode],
+ );
+
+ // Double click = drill (grammar): layer → groups/detail, group → detail,
+ // folder → expand/collapse. (Drilling clears selection in the store.)
+ const handleNodeDoubleClick = useCallback(
+ (_: React.MouseEvent, node: { id: string; type?: string }) => {
+ if (node.type === "layerCluster") {
+ drillIntoLayer(node.id);
+ } else if (node.type === "subGroupCluster") {
+ useArchitectureStore.getState().drillIntoSubGroup(node.id);
+ } else if (node.type === "archContainer") {
+ useArchitectureStore.getState().toggleContainer(node.id);
+ }
+ },
+ [drillIntoLayer],
+ );
+
+ const handlePaneClick = useCallback(() => {
+ selectNode(null);
+ }, [selectNode]);
+
+ const fetchContent = useCallback(
+ async (filePath: string) => {
+ const apiBase =
+ typeof window !== "undefined"
+ ? (process.env.NEXT_PUBLIC_REPOWISE_API_URL ?? "")
+ : "";
+ const apiKey =
+ typeof window !== "undefined"
+ ? localStorage.getItem("repowise_api_key")
+ : null;
+ const res = await fetch(
+ `${apiBase}/api/repos/${repoId}/file-content?` +
+ new URLSearchParams({ file_path: filePath }).toString(),
+ { headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : {} },
+ );
+ if (!res.ok) {
+ throw new Error(`Failed to fetch file content (${res.status})`);
+ }
+ return res.text();
+ },
+ [repoId],
+ );
+
+ const anyLoading = isLoading || layoutLoading;
+
+ return (
+ <>
+ <div className="shrink-0 px-4 sm:px-6 py-3 border-b border-[var(--color-border-default)]">
+ <div className="flex items-center justify-between">
+ <div>
+ <h1 className="text-lg font-semibold text-[var(--color-text-primary)]">
+ Layers
+ </h1>
+ <p className="text-xs text-[var(--color-text-secondary)] mt-0.5">
+ {repoName} — curated layered view of the system.
+ </p>
+ </div>
+ <div className="flex items-center gap-3">
+ {view && view.tour.length > 0 && !tourActive && (
+ <button
+ onClick={handleStartTour}
+ className={`flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-medium transition-colors ${
+ tourSeen
+ ? "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)]"
+ : "border-[var(--color-accent-primary)]/50 bg-[var(--color-accent-primary)]/10 text-[var(--color-accent-primary)] hover:bg-[var(--color-accent-primary)]/20"
+ }`}
+ >
+ <Compass className="h-3.5 w-3.5" />
+ Take the tour
+ </button>
+ )}
+ <PersonaSelector />
+ <NodeTypeCategoryFilters />
+ </div>
+ </div>
+ <div className="mt-2 flex items-center gap-4">
+ <SearchBar />
+ <ArchBreadcrumb />
+ </div>
+ </div>
+
+ <style>{KEYFRAMES.accentPulse}{KEYFRAMES.edgeFlow}{`
+ /* Zoom-into-tier feel: nodes glide to their next slot (plan D). */
+ @media (prefers-reduced-motion: no-preference) {
+ .react-flow__node { transition: transform 180ms ease; }
+ }
+ `}</style>
+ <div className="flex-1 min-h-0 relative bg-[var(--color-bg-canvas)]">
+ {error && (
+ <div className="absolute inset-0 flex items-center justify-center z-10">
+ <EmptyState
+ icon={<AlertTriangle className="h-5 w-5" aria-hidden />}
+ title="Couldn't load the knowledge graph"
+ description={error.message}
+ className="max-w-md p-8"
+ />
+ </div>
+ )}
+ {anyLoading && nodes.length === 0 && !error && (
+ <div className="absolute inset-0 flex items-center justify-center z-10 pointer-events-none">
+ <OwlLoader size={120} label="Loading knowledge graph…" className="min-h-0" />
+ </div>
+ )}
+ {/* Re-layout feedback (B6): ELK stage-2 on big layers used to freeze
+ silently — a small owl chip says the canvas is thinking. */}
+ {anyLoading && nodes.length > 0 && !error && (
+ <div className="absolute top-3 left-1/2 -translate-x-1/2 z-10 pointer-events-none rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/95 px-3 py-1 shadow-sm">
+ <OwlLoader size={28} label="Laying out…" className="min-h-0 flex-row gap-2 text-[10px]" />
+ </div>
+ )}
+
+ <ReactFlow
+ nodes={nodes}
+ edges={edges}
+ nodeTypes={archNodeTypes}
+ edgeTypes={archEdgeTypes}
+ onNodeClick={handleNodeClick}
+ onNodeDoubleClick={handleNodeDoubleClick}
+ onPaneClick={handlePaneClick}
+ onInit={setReactFlowInstance}
+ fitView
+ fitViewOptions={{ padding: 0.2 }}
+ minZoom={0.1}
+ maxZoom={3}
+ proOptions={{ hideAttribution: true }}
+ nodesDraggable={false}
+ nodesConnectable={false}
+ >
+ {/* Blueprint graph paper: 24px line grid on the warm canvas, matching
+ the mermaid container (kg-ux plan §2.1). */}
+ <Background variant={BackgroundVariant.Lines} gap={24} size={1} color="var(--color-diagram-grid)" />
+ <Controls showInteractive={false} />
+ {/* maskColor comes from --xy-minimap-mask-background (theme-aware). */}
+ <MiniMap pannable zoomable />
+ </ReactFlow>
+
+ {/* Orientation (plan C-1) and the tour player (C-2) render in the
+ right Sidebar only — the floating left asides duplicated them
+ (user feedback 2026-06-05: one place). */}
+
+ {hiddenEdgeCount > 0 && (
+ <div
+ className="absolute bottom-4 left-14 z-10 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-secondary)]/90 px-3 py-1 text-xs text-[var(--color-text-secondary)]"
+ title="Weakest aggregated connections are hidden to keep the view legible. Drill in to see them."
+ >
+ +{hiddenEdgeCount} weaker link{hiddenEdgeCount === 1 ? "" : "s"} hidden
+ </div>
+ )}
+
+ {/* Decoder ring — collapsible, every tier (B6). */}
+ <div className="absolute bottom-4 right-[224px] z-10">
+ <ArchLegend />
+ </div>
+
+ <ArchDetailPanelHost repoId={repoId} />
+
+ <FilterPanel />
+
+ <CodeViewer fetchContent={fetchContent} />
+
+ {pathFinderOpen && <PathFinderModal />}
+ </div>
+ </>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Legacy C4 View (preserved for backward compat)
+// ---------------------------------------------------------------------------
+
+function LegacyC4View({ repoId, repoName }: { repoId: string; repoName: string }) {
+ const [levelParam, setLevelParam] = useQueryState(
+ "level",
+ parseAsInteger.withDefault(2),
+ );
+ const [containerParam, setContainerParam] = useQueryState(
+ "container",
+ parseAsString,
+ );
+
+ const level = clampLevel(levelParam);
+ const activeContainerId = containerParam || null;
+
+ const { view: l1View, error: l1Err, isLoading: l1Loading } = useC4L1(level === 1 ? repoId : null);
+ const { view: l2View, error: l2Err, isLoading: l2Loading } = useC4L2(level >= 2 ? repoId : null);
+ const { view: l3View, error: l3Err, isLoading: l3Loading } = useC4L3(
+ level === 3 ? repoId : null,
+ level === 3 ? activeContainerId : null,
+ );
+
+ const setLevel = useCallback(
+ (next: C4Level) => {
+ void setLevelParam(next);
+ if (next !== 3) void setContainerParam(null);
+ },
+ [setContainerParam, setLevelParam],
+ );
+
+ const drillInto = useCallback(
+ (containerId: string) => {
+ void setLevelParam(3);
+ void setContainerParam(containerId);
+ },
+ [setContainerParam, setLevelParam],
+ );
+
+ const drillOut = useCallback(() => {
+ if (level === 3) {
+ void setLevelParam(2);
+ void setContainerParam(null);
+ } else if (level === 2) {
+ void setLevelParam(1);
+ }
+ }, [level, setContainerParam, setLevelParam]);
+
+ const loading = level === 1 ? l1Loading : level === 2 ? l2Loading : l3Loading;
+ const error = level === 1 ? l1Err : level === 2 ? l2Err : l3Err;
+
+ const { pathSet: docsPathSet, pageIdByPath } = useC4DocsPathSet(repoId);
+
+ const fetchMermaid = useCallback(
+ () => getC4Mermaid(repoId, level, activeContainerId),
+ [activeContainerId, level, repoId],
+ );
+
+ return (
+ <>
+ <div className="shrink-0 px-4 sm:px-6 py-3 border-b border-[var(--color-border-default)]">
+ <div className="flex items-center justify-between gap-4">
+ <div>
+ <h1 className="text-lg font-semibold text-[var(--color-text-primary)]">
+ Knowledge Graph
+ </h1>
+ <p className="text-xs text-[var(--color-text-secondary)] mt-0.5">
+ System context, containers, and components — drill in to navigate.
+ </p>
+ </div>
+ {/* Legacy mode is frozen (locked decision 4) — point at the new view. */}
+ <a
+ href="?view=layers"
+ className="shrink-0 rounded-full border border-[var(--color-accent-primary,#f59520)]/50 bg-[var(--color-accent-primary,#f59520)]/10 px-3 py-1 text-xs text-[var(--color-accent-primary,#f59520)] hover:bg-[var(--color-accent-primary,#f59520)]/20"
+ >
+ Try the new architecture view →
+ </a>
+ </div>
+ </div>
+ <div className="flex-1 min-h-0">
+ <C4Diagram
+ level={level}
+ activeContainerId={activeContainerId}
+ systemName={repoName}
+ l1View={l1View}
+ l2View={l2View}
+ l3View={l3View}
+ loading={loading}
+ error={error}
+ onLevelChange={setLevel}
+ onDrillInto={drillInto}
+ onDrillOut={drillOut}
+ docsPathSet={docsPathSet}
+ fetchMermaid={fetchMermaid}
+ renderInspector={({ data, onClose, onDrillIn }) => (
+ <C4DetailPanelHost
+ repoId={repoId}
+ data={data}
+ pageIdByPath={pageIdByPath}
+ onClose={onClose}
+ onDrillIn={onDrillIn}
+ />
+ )}
+ />
+ </div>
+ </>
+ );
+}
diff --git a/packages/web/src/components/architecture/dependencies-view.tsx b/packages/web/src/components/architecture/dependencies-view.tsx
new file mode 100644
index 000000000..eab1274eb
--- /dev/null
+++ b/packages/web/src/components/architecture/dependencies-view.tsx
@@ -0,0 +1,61 @@
+"use client";
+
+import useSWR from "swr";
+import Link from "next/link";
+import { Package } from "lucide-react";
+import { DependencyRegistry } from "@repowise-dev/ui/dependencies";
+import { ApiError } from "@repowise-dev/ui/shared/api-error";
+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
+import { getExternalSystems } from "@/lib/api/external-systems";
+
+export function DependenciesView({ repoId }: { repoId: string }) {
+ const { data, error, isLoading, mutate } = useSWR(
+ `external-systems:${repoId}`,
+ () => getExternalSystems(repoId),
+ { revalidateOnFocus: false },
+ );
+
+ return (
+ <div className="max-w-[1600px] space-y-6 p-4 sm:p-6">
+ <div>
+ <h1 className="mb-1 flex items-center gap-2 text-xl font-semibold text-[var(--color-text-primary)]">
+ <Package className="h-5 w-5 text-[var(--color-accent-primary)]" />
+ Dependencies
+ </h1>
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ Third-party dependencies declared in this repo&apos;s manifests.
+ </p>
+ </div>
+
+ {error ? (
+ <ApiError
+ title="Couldn't load the dependency registry"
+ message={error instanceof Error ? error.message : String(error)}
+ onRetry={() => void mutate()}
+ />
+ ) : isLoading || !data ? (
+ <div className="space-y-3">
+ <Skeleton className="h-8 w-72" />
+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2 xl:grid-cols-3">
+ {Array.from({ length: 6 }).map((_, i) => (
+ <Skeleton key={i} className="h-20" />
+ ))}
+ </div>
+ </div>
+ ) : (
+ <DependencyRegistry
+ data={data}
+ renderManifestLink={(declaredIn, children) => (
+ <Link
+ href={fileEntityPath(`/repos/${repoId}`, declaredIn)}
+ className="hover:text-[var(--color-accent-primary)] hover:underline"
+ >
+ {children}
+ </Link>
+ )}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/packages/web/src/components/architecture/graph-view.tsx b/packages/web/src/components/architecture/graph-view.tsx
new file mode 100644
index 000000000..116daddb4
--- /dev/null
+++ b/packages/web/src/components/architecture/graph-view.tsx
@@ -0,0 +1,201 @@
+"use client";
+
+import { useCallback, useState } from "react";
+import useSWR from "swr";
+import { useQueryState } from "nuqs";
+import { useSearchParams } from "next/navigation";
+import { GraphFlow } from "@/components/graph/graph-flow";
+import { GraphDocPanel } from "@/components/graph/graph-doc-panel";
+import { GraphTruncationBanner } from "@repowise-dev/ui/graph/graph-truncation-banner";
+import { getGraph } from "@/lib/api/graph";
+import type { GraphExportResponse } from "@/lib/api/types";
+
+type ViewMode = "module" | "full" | "architecture" | "dead" | "hotfiles" | "unified";
+type ColorMode = "language" | "community" | "risk";
+
+const VALID_COLOR_MODES = new Set<ColorMode>(["language", "community", "risk"]);
+
+const VALID_VIEW_MODES = new Set<ViewMode>([
+ "module",
+ "full",
+ "architecture",
+ "dead",
+ "hotfiles",
+ "unified",
+]);
+
+// Scopes that render their own dedicated endpoint and therefore never touch the
+// capped full-graph endpoint (`/api/graph`). The constellation ("architecture")
+// and the module browser fetch their own graphs, so the page must NOT eagerly
+// fetch the full graph — nor show its truncation banner — for these scopes.
+const SCOPES_WITHOUT_FULL_GRAPH = new Set<ViewMode>(["architecture", "module"]);
+
+export function GraphView({
+ repoId,
+ scope = "map",
+ onScopeViewChange,
+}: {
+ repoId: string;
+ /** Which top-level Architecture mode hosts the canvas: Map = constellation,
+ * Explore = file/module graphs. One mounted component serves both. */
+ scope?: "map" | "explore";
+ /** Scope switches inside the canvas (toolbar) re-sync `?view=` upstream. */
+ onScopeViewChange?: (view: "map" | "explore") => void;
+}) {
+ const searchParams = useSearchParams();
+
+ const viewModeParam = searchParams.get("viewMode");
+ const initialViewMode = VALID_VIEW_MODES.has((viewModeParam ?? "") as ViewMode)
+ ? (viewModeParam as ViewMode)
+ : undefined;
+ const initialNode = searchParams.get("node");
+
+ const colorModeParam = searchParams.get("colorMode");
+ const initialColorMode = VALID_COLOR_MODES.has((colorModeParam ?? "") as ColorMode)
+ ? (colorModeParam as ColorMode)
+ : undefined;
+
+ const [, setSelectedNode] = useQueryState("node");
+ const [, setColorModeParam] = useQueryState("colorMode");
+ const [, setViewModeParam] = useQueryState("viewMode");
+ const [docNodeId, setDocNodeId] = useState<string | null>(null);
+ const [graphLimit, setGraphLimit] = useState<number | undefined>(undefined);
+
+ // The scope the canvas mounts into: a pinned node forces "full"; an explicit
+ // ?viewMode= wins; otherwise the hosting mode decides (Map → constellation,
+ // Explore → full graph).
+ const mountViewMode: ViewMode = initialNode
+ ? "full"
+ : initialViewMode ?? (scope === "explore" ? "full" : "architecture");
+
+ // Track the live scope so we only fetch the capped full graph (and render
+ // its truncation banner) for scopes that actually use it. Remount the canvas
+ // (flowKey) when the truncation banner jumps to the constellation — that is
+ // a host-initiated scope change, which GraphFlow only reads at mount.
+ const [viewMode, setViewMode] = useState<ViewMode>(mountViewMode);
+ const [flowKey, setFlowKey] = useState(0);
+ const [forcedViewMode, setForcedViewMode] = useState<ViewMode | null>(null);
+ const usesFullGraph = !SCOPES_WITHOUT_FULL_GRAPH.has(viewMode);
+
+ const { data: graphData } = useSWR<GraphExportResponse>(
+ usesFullGraph ? `graph:${repoId}:${graphLimit ?? "default"}` : null,
+ () => getGraph(repoId, graphLimit),
+ { revalidateOnFocus: false, revalidateOnReconnect: false },
+ );
+
+ // Click a file node → open doc panel
+ const handleNodeClick = useCallback(
+ (nodeId: string, nodeType: string) => {
+ // Module clicks are handled inside GraphFlow (drill-down)
+ // File clicks open the doc panel
+ if (nodeType !== "moduleGroup") {
+ setDocNodeId((prev) => (prev === nodeId ? null : nodeId));
+ void setSelectedNode(nodeId);
+ }
+ },
+ [setSelectedNode],
+ );
+
+ // Double click or context menu "View Docs"
+ const handleNodeViewDocs = useCallback(
+ (nodeId: string) => {
+ setDocNodeId((prev) => (prev === nodeId ? null : nodeId));
+ void setSelectedNode(nodeId);
+ },
+ [setSelectedNode],
+ );
+
+ // When the community panel opens from the legend, dismiss the doc panel
+ // so the two never stack on the right rail. Single-sidebar UX.
+ const handleCommunityPanelOpen = useCallback(() => {
+ setDocNodeId(null);
+ }, []);
+
+ // In-canvas scope switches keep the URL honest: `?viewMode=` mirrors the
+ // graph scope and `?view=` flips between Map and Explore.
+ const handleViewModeChange = useCallback(
+ (mode: ViewMode) => {
+ setViewMode(mode);
+ void setViewModeParam(mode === "architecture" ? null : mode);
+ onScopeViewChange?.(mode === "architecture" ? "map" : "explore");
+ },
+ [onScopeViewChange, setViewModeParam],
+ );
+
+ // Color-mode changes (toolbar or 1/2/3 keys) sync to the URL so shared
+ // links restore the same coloring.
+ const handleColorModeChange = useCallback(
+ (mode: ColorMode) => {
+ void setColorModeParam(mode);
+ },
+ [setColorModeParam],
+ );
+
+ // "Switch to the Knowledge Graph" from the truncation banner: remount the
+ // canvas in the constellation scope. No page reload.
+ const handleSwitchToArchitecture = useCallback(() => {
+ setForcedViewMode("architecture");
+ setFlowKey((k) => k + 1);
+ handleViewModeChange("architecture");
+ }, [handleViewModeChange]);
+
+ const isMap = scope === "map" && !initialNode;
+
+ return (
+ <div className="flex flex-col h-full">
+ {/* 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)]">
+ {isMap ? "Architecture Map" : "Dependency Explorer"}
+ </h1>
+ <p className="text-xs text-[var(--color-text-secondary)] mt-0.5">
+ {isMap
+ ? "Detected communities and how they connect — double-click a hub to blossom it"
+ : "Explore dependencies, overlays and trace paths between files"}
+ </p>
+ </div>
+
+ {/* Truncation banner — shown only when the current scope renders the
+ capped full graph and the server actually capped it. Constellation /
+ module scopes use their own endpoints, so the banner stays hidden. */}
+ {usesFullGraph && graphData?.truncated && graphData.total_node_count != null && (
+ <div className="shrink-0 px-4 sm:px-6 pt-3">
+ <GraphTruncationBanner
+ shown={graphData.nodes.length}
+ total={graphData.total_node_count}
+ limit={graphLimit ?? graphData.nodes.length}
+ onLoadMore={(nextLimit) => setGraphLimit(nextLimit)}
+ onSwitchToArchitecture={handleSwitchToArchitecture}
+ />
+ </div>
+ )}
+
+ {/* Graph area */}
+ <div className="flex-1 overflow-hidden p-3">
+ <div className="h-full w-full rounded-lg border border-[var(--color-border-default)] overflow-hidden relative">
+ <GraphFlow
+ key={flowKey}
+ repoId={repoId}
+ initialViewMode={forcedViewMode ?? mountViewMode}
+ initialColorMode={initialColorMode}
+ initialSelectedNode={initialNode}
+ onNodeClick={handleNodeClick}
+ onNodeViewDocs={handleNodeViewDocs}
+ onCommunityPanelOpen={handleCommunityPanelOpen}
+ onViewModeChange={handleViewModeChange}
+ onColorModeChange={handleColorModeChange}
+ />
+
+ {/* Doc panel — shows on file click. Single right-rail surface. */}
+ {docNodeId && (
+ <GraphDocPanel
+ repoId={repoId}
+ nodeId={docNodeId}
+ onClose={() => setDocNodeId(null)}
+ />
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/c4/arch-detail-panel-host.tsx b/packages/web/src/components/c4/arch-detail-panel-host.tsx
index 2434e3b81..953eab55f 100644
--- a/packages/web/src/components/c4/arch-detail-panel-host.tsx
+++ b/packages/web/src/components/c4/arch-detail-panel-host.tsx
@@ -65,7 +65,7 @@ export function ArchDetailPanelHost({ repoId }: ArchDetailPanelHostProps) {
renderDoc={(content) => <ChatMarkdown content={content} />}
onOpenInGraph={
filePath
- ? (p) => router.push(`/repos/${repoId}/graph?node=${encodeURIComponent(p)}`)
+ ? (p) => router.push(`/repos/${repoId}/architecture?view=graph&node=${encodeURIComponent(p)}`)
: undefined
}
onOpenDoc={() => {
diff --git a/packages/web/src/components/c4/c4-detail-panel-host.tsx b/packages/web/src/components/c4/c4-detail-panel-host.tsx
index 93ffc8e1f..f78fb88b1 100644
--- a/packages/web/src/components/c4/c4-detail-panel-host.tsx
+++ b/packages/web/src/components/c4/c4-detail-panel-host.tsx
@@ -77,7 +77,7 @@ export function C4DetailPanelHost({
contributors={contributors}
onClose={onClose}
onDrillIn={onDrillIn}
- onOpenInGraph={path ? (p) => router.push(`/repos/${repoId}/graph?node=${encodeURIComponent(p)}`) : undefined}
+ onOpenInGraph={path ? (p) => router.push(`/repos/${repoId}/architecture?view=graph&node=${encodeURIComponent(p)}`) : undefined}
onOpenDoc={(href) => router.push(href)}
/>
);
diff --git a/packages/web/src/components/chat/chat-interface.tsx b/packages/web/src/components/chat/chat-interface.tsx
index 5d3b17ddf..2c7bd7edc 100644
--- a/packages/web/src/components/chat/chat-interface.tsx
+++ b/packages/web/src/components/chat/chat-interface.tsx
@@ -1,16 +1,25 @@
"use client";
+import { useEffect, useRef } from "react";
+import useSWR from "swr";
+import Link from "next/link";
import { ChatInterface as ChatInterfaceShell } from "@repowise-dev/ui/chat/chat-interface";
import { useChat } from "@/lib/hooks/use-chat";
+import { pageHref } from "@/lib/utils/page-href";
+import { listConversations } from "@/lib/api/chat";
+import { getProviders } from "@/lib/api/providers";
+import { getRepoStats } from "@/lib/api/repos";
import { ModelSelector } from "./model-selector";
import { ConversationHistory } from "./conversation-history";
interface ChatInterfaceProps {
repoId: string;
repoName?: string;
+ /** Question to send immediately on mount (quick-ask deep links, `?q=`). */
+ initialQuestion?: string;
}
-export function ChatInterface({ repoId, repoName }: ChatInterfaceProps) {
+export function ChatInterface({ repoId, repoName, initialQuestion }: ChatInterfaceProps) {
const {
messages,
conversationId,
@@ -21,6 +30,53 @@ export function ChatInterface({ repoId, repoName }: ChatInterfaceProps) {
reset,
} = useChat(repoId);
+ // Provider guard: surface "no chat provider configured" BEFORE the first
+ // send instead of erroring after.
+ const { data: providers } = useSWR(
+ `providers:${repoId}`,
+ () => getProviders(repoId),
+ { revalidateOnFocus: false },
+ );
+ const anyConfigured =
+ providers === undefined || providers.providers.some((p) => p.configured);
+
+ // Orientation status line for the empty state.
+ const { data: stats } = useSWR(
+ `repo-stats:${repoId}`,
+ () => getRepoStats(repoId),
+ { revalidateOnFocus: false },
+ );
+
+ // Fire the seeded question exactly once (guards StrictMode double-effects).
+ const seededRef = useRef(false);
+ useEffect(() => {
+ if (!initialQuestion || seededRef.current) return;
+ seededRef.current = true;
+ void sendMessage(initialQuestion);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [initialQuestion]);
+
+ // Resume the most recent conversation when landing on a blank chat (no
+ // seeded question). Once only; "New conversation" still resets cleanly.
+ const resumedRef = useRef(false);
+ useEffect(() => {
+ if (resumedRef.current || seededRef.current || initialQuestion) return;
+ if (messages.length > 0 || conversationId) return;
+ resumedRef.current = true;
+ void (async () => {
+ try {
+ const conversations = await listConversations(repoId);
+ const latest = conversations[0];
+ if (latest && latest.message_count > 0) {
+ await loadConversation(latest.id);
+ }
+ } catch {
+ // Resume is best-effort; a blank chat is a fine fallback.
+ }
+ })();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [repoId]);
+
return (
<ChatInterfaceShell
repoId={repoId}
@@ -30,7 +86,31 @@ export function ChatInterface({ repoId, repoName }: ChatInterfaceProps) {
error={error}
onSend={(text) => sendMessage(text)}
onCancel={reset}
+ buildCitationHref={(s) => pageHref(repoId, s.pageId)}
modelSelectorSlot={<ModelSelector repoId={repoId} />}
+ statusSlot={
+ stats ? (
+ <span>
+ {stats.file_count.toLocaleString()} files ·{" "}
+ {Math.round(stats.doc_coverage_pct)}% documented
+ {stats.symbol_count > 0 &&
+ ` · ${stats.symbol_count.toLocaleString()} symbols indexed`}
+ </span>
+ ) : undefined
+ }
+ sendDisabled={!anyConfigured}
+ sendDisabledReason={
+ <span>
+ No chat provider is configured. Add an API key in{" "}
+ <Link
+ href="/settings"
+ className="text-[var(--color-accent-primary)] hover:underline"
+ >
+ settings
+ </Link>{" "}
+ to start asking questions.
+ </span>
+ }
historySlot={
<ConversationHistory
repoId={repoId}
diff --git a/packages/web/src/components/code-health/coverage-tab.tsx b/packages/web/src/components/code-health/coverage-tab.tsx
new file mode 100644
index 000000000..6375963ad
--- /dev/null
+++ b/packages/web/src/components/code-health/coverage-tab.tsx
@@ -0,0 +1,388 @@
+"use client";
+
+/**
+ * Coverage tab — test-coverage summary, risk × coverage scatter, untested
+ * hotspots (with the dependents/commit context from the findings), module
+ * rollup, and the per-file table. Rows link to the file page's coverage tab
+ * (line-level heatmap).
+ */
+
+import { useMemo, useState } from "react";
+import { ArrowUpRight, Sparkles } from "lucide-react";
+import { useRouter } from "next/navigation";
+import useSWR from "swr";
+
+import {
+ AiPromptModal,
+ CoverageBar,
+ ModuleCoverageList,
+ UntestedHotspotWarning,
+ RiskCoverageScatter,
+ buildCoverageAiPrompt,
+ scoreBadgeClass,
+ type CoverageFilePromptInput,
+} from "@repowise-dev/ui/health";
+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
+import { ResponsiveTable, type ResponsiveColumn } from "@repowise-dev/ui/shared";
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
+
+import {
+ getHealthCoverage,
+ listHealthFindings,
+ type CoverageFileRow,
+ type HealthCoverageResponse,
+ type HealthFinding,
+} from "@/lib/api/code-health";
+
+export function CoverageTab({ repoId: id }: { repoId: string }) {
+ const router = useRouter();
+ const [promptRow, setPromptRow] = useState<CoverageFilePromptInput | null>(null);
+
+ const { data, isLoading, error } = useSWR<HealthCoverageResponse>(
+ `code-health-coverage:${id}`,
+ () => getHealthCoverage(id, { limit: 1000 }),
+ { revalidateOnFocus: false },
+ );
+
+ // The untested_hotspot findings carry dependents_count / commit_count_90d
+ // in their details — join them into the warning entries.
+ const { data: untestedFindings } = useSWR<HealthFinding[]>(
+ `code-health-untested-findings:${id}`,
+ () =>
+ listHealthFindings(id, { biomarker_type: "untested_hotspot", limit: 50 }).catch(
+ () => [],
+ ),
+ { revalidateOnFocus: false },
+ );
+
+ const openFilePage = (path: string) =>
+ router.push(`${fileEntityPath(`/repos/${id}`, path)}?tab=coverage`);
+
+ return (
+ <div className="space-y-6">
+ {isLoading ? (
+ <CoverageSkeleton />
+ ) : error ? (
+ <EmptyState
+ title="Couldn't load coverage data"
+ description="The coverage endpoint returned an error. Try refreshing, or re-run the health pass."
+ />
+ ) : !data || data.summary.file_count === 0 ? (
+ <NoCoverageState />
+ ) : (
+ <CoverageView
+ data={data}
+ untestedFindings={untestedFindings ?? []}
+ onOpenFile={openFilePage}
+ onGeneratePrompt={(r) => setPromptRow(r)}
+ />
+ )}
+
+ <AiPromptModal
+ open={promptRow !== null}
+ onOpenChange={(open) => {
+ if (!open) setPromptRow(null);
+ }}
+ filePath={promptRow?.file_path}
+ title="AI test prompt"
+ description="A ready-to-paste prompt that asks your AI coding agent to add tests for this file's uncovered lines and branches."
+ getPrompt={
+ promptRow
+ ? (flavor) => buildCoverageAiPrompt({ row: promptRow, flavor })
+ : null
+ }
+ />
+ </div>
+ );
+}
+
+function CoverageView({
+ data,
+ untestedFindings,
+ onOpenFile,
+ onGeneratePrompt,
+}: {
+ data: HealthCoverageResponse;
+ untestedFindings: HealthFinding[];
+ onOpenFile: (path: string) => void;
+ onGeneratePrompt: (row: CoverageFilePromptInput) => void;
+}) {
+ const { summary, files, modules } = data;
+ const [search, setSearch] = useState("");
+
+ const num = (v: unknown): number | null =>
+ typeof v === "number" && Number.isFinite(v) ? v : null;
+
+ // Untested hotspots: prefer the real biomarker findings (which carry
+ // dependents/commit context); fall back to the low-coverage × low-score
+ // heuristic when the biomarker never fired (e.g. coverage just ingested).
+ const untested = useMemo(() => {
+ const covByPath = new Map(files.map((f) => [f.file_path, f]));
+ if (untestedFindings.length > 0) {
+ return untestedFindings.slice(0, 10).map((f) => {
+ const cov = covByPath.get(f.file_path);
+ const d = f.details ?? {};
+ return {
+ file_path: f.file_path,
+ line_coverage_pct:
+ num(d.line_coverage_pct) ?? cov?.line_coverage_pct ?? null,
+ dependents_count: num(d.dependents_count) ?? undefined,
+ commit_count_90d: num(d.commit_count_90d),
+ health_score: cov?.health_score,
+ };
+ });
+ }
+ return files
+ .filter(
+ (f) =>
+ f.line_coverage_pct != null &&
+ f.line_coverage_pct < 30 &&
+ (f.health_score == null || f.health_score < 6),
+ )
+ .slice(0, 10)
+ .map((f) => ({
+ file_path: f.file_path,
+ line_coverage_pct: f.line_coverage_pct,
+ health_score: f.health_score,
+ }));
+ }, [files, untestedFindings]);
+
+ const scatterPoints = useMemo(
+ () =>
+ files
+ .filter((f) => f.health_score != null && f.line_coverage_pct != null)
+ .map((f) => ({
+ file_path: f.file_path,
+ health_score: f.health_score!,
+ line_coverage_pct: f.line_coverage_pct,
+ nloc: f.nloc ?? 0,
+ })),
+ [files],
+ );
+
+ const filteredFiles = useMemo(() => {
+ if (!search) return files;
+ const s = search.toLowerCase();
+ return files.filter((f) => f.file_path.toLowerCase().includes(s));
+ }, [files, search]);
+
+ const columns: ResponsiveColumn<CoverageFileRow>[] = [
+ {
+ key: "file_path",
+ header: "File",
+ priority: 1,
+ render: (f) => (
+ <span className="inline-flex items-center gap-1.5 font-mono text-xs text-[var(--color-text-primary)]">
+ <span className="truncate max-w-[420px]" title={f.file_path}>
+ {f.file_path}
+ </span>
+ <ArrowUpRight className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />
+ </span>
+ ),
+ },
+ {
+ key: "line_coverage_pct",
+ header: "Line coverage",
+ priority: 1,
+ render: (f) => <CoverageBar value={f.line_coverage_pct} size="sm" />,
+ },
+ {
+ key: "branch_coverage_pct",
+ header: "Branch",
+ priority: 3,
+ align: "right",
+ render: (f) => (
+ <span className="tabular-nums text-[var(--color-text-secondary)]">
+ {f.branch_coverage_pct == null ? "—" : `${f.branch_coverage_pct.toFixed(0)}%`}
+ </span>
+ ),
+ },
+ {
+ key: "total_coverable_lines",
+ header: "Lines",
+ priority: 3,
+ align: "right",
+ render: (f) => (
+ <span className="tabular-nums text-[var(--color-text-tertiary)]">
+ {f.total_coverable_lines}
+ </span>
+ ),
+ },
+ {
+ key: "health_score",
+ header: "Health",
+ priority: 2,
+ align: "right",
+ render: (f) =>
+ f.health_score == null ? (
+ <span className="text-[var(--color-text-tertiary)]">—</span>
+ ) : (
+ <span
+ className={`inline-block rounded px-1.5 py-0.5 text-xs font-semibold ${scoreBadgeClass(f.health_score)}`}
+ >
+ {f.health_score.toFixed(1)}
+ </span>
+ ),
+ },
+ {
+ key: "actions",
+ header: "",
+ priority: 1,
+ align: "right",
+ render: (f) => (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ onGeneratePrompt({
+ file_path: f.file_path,
+ line_coverage_pct: f.line_coverage_pct,
+ branch_coverage_pct: f.branch_coverage_pct,
+ total_coverable_lines: f.total_coverable_lines,
+ covered_lines: f.covered_lines,
+ source_format: f.source_format,
+ health_score: f.health_score ?? null,
+ nloc: f.nloc ?? null,
+ });
+ }}
+ title="Generate AI test prompt for this file"
+ className="inline-flex items-center justify-center rounded-md p-1 text-[var(--color-text-tertiary)] hover:text-[var(--color-success)] hover:bg-[var(--color-success)]/10 transition-colors"
+ >
+ <Sparkles className="h-3.5 w-3.5" />
+ </button>
+ ),
+ },
+ ];
+
+ return (
+ <div className="space-y-6">
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-4">
+ <SummaryCard label="Files">
+ <span className="text-2xl font-bold tabular-nums text-[var(--color-text-primary)]">
+ {summary.file_count.toLocaleString()}
+ </span>
+ </SummaryCard>
+ <SummaryCard label="Line coverage">
+ <span className="text-2xl font-bold tabular-nums text-[var(--color-text-primary)]">
+ {summary.line_coverage_pct == null
+ ? "—"
+ : `${summary.line_coverage_pct.toFixed(1)}%`}
+ </span>
+ <p className="text-xs text-[var(--color-text-tertiary)] mt-1 tabular-nums">
+ {summary.covered_lines.toLocaleString()} /{" "}
+ {summary.total_lines.toLocaleString()} lines
+ </p>
+ </SummaryCard>
+ <SummaryCard label="Branch coverage">
+ <span className="text-2xl font-bold tabular-nums text-[var(--color-text-primary)]">
+ {summary.branch_coverage_pct == null
+ ? "—"
+ : `${summary.branch_coverage_pct.toFixed(1)}%`}
+ </span>
+ </SummaryCard>
+ <SummaryCard label="Source">
+ <span className="text-lg font-semibold text-[var(--color-text-primary)] uppercase">
+ {summary.source_format ?? "—"}
+ </span>
+ <p className="text-xs text-[var(--color-text-tertiary)] mt-1">
+ {summary.ingested_at ? new Date(summary.ingested_at).toLocaleString() : "never"}
+ </p>
+ </SummaryCard>
+ </div>
+
+ <RiskCoverageScatter points={scatterPoints} onSelect={(p) => onOpenFile(p.file_path)} />
+
+ {untested.length > 0 ? <UntestedHotspotWarning entries={untested} /> : null}
+
+ <section className="space-y-2">
+ <h2 className="text-sm font-semibold text-[var(--color-text-primary)]">
+ Module coverage ({modules.length})
+ </h2>
+ <ModuleCoverageList modules={modules} />
+ </section>
+
+ <section className="space-y-2">
+ <div className="flex items-center gap-2">
+ <h2 className="text-sm font-semibold text-[var(--color-text-primary)] mr-auto">
+ Files ({filteredFiles.length.toLocaleString()})
+ </h2>
+ <input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Filter path…"
+ className="text-xs px-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-56 focus:outline-none focus:border-[var(--color-border-strong)]"
+ />
+ </div>
+ <ResponsiveTable
+ columns={columns}
+ rows={filteredFiles}
+ rowKey={(f) => f.file_path}
+ onRowClick={(f) => onOpenFile(f.file_path)}
+ stacked="sm"
+ empty={
+ <EmptyState
+ title="No files match"
+ description="Adjust the path filter to see coverage rows."
+ />
+ }
+ />
+ </section>
+ </div>
+ );
+}
+
+function SummaryCard({
+ label,
+ children,
+}: {
+ label: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">
+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1">
+ {label}
+ </p>
+ {children}
+ </div>
+ );
+}
+
+function NoCoverageState() {
+ return (
+ <div className="rounded-lg border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-8">
+ <div className="max-w-xl mx-auto text-center space-y-3">
+ <h2 className="text-base font-semibold text-[var(--color-text-primary)]">
+ No coverage data ingested yet
+ </h2>
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ Run your test suite with coverage enabled, then ingest the report.
+ You&apos;ll see a risk × coverage map, untested-hotspot warnings, and a
+ per-module breakdown.
+ </p>
+ <pre className="inline-block px-4 py-2 rounded bg-[var(--color-bg-muted)] text-left text-xs font-mono">
+ pytest --cov --cov-report=lcov{"\n"}
+ repowise health --coverage coverage.lcov
+ </pre>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Supported formats: LCOV · Cobertura · Clover.
+ </p>
+ </div>
+ </div>
+ );
+}
+
+function CoverageSkeleton() {
+ return (
+ <div className="space-y-6">
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Skeleton key={i} className="h-24 w-full rounded-lg" />
+ ))}
+ </div>
+ <Skeleton className="h-72 w-full rounded-lg" />
+ <Skeleton className="h-48 w-full rounded-lg" />
+ </div>
+ );
+}
diff --git a/packages/web/src/components/code-health/trend-tab.tsx b/packages/web/src/components/code-health/trend-tab.tsx
new file mode 100644
index 000000000..3e92b9227
--- /dev/null
+++ b/packages/web/src/components/code-health/trend-tab.tsx
@@ -0,0 +1,213 @@
+"use client";
+
+/**
+ * Trend tab — KPI history over recent indexes. Handles the single-snapshot
+ * case explicitly (no misleading flat chart) and renders per-file deltas on
+ * a ResponsiveTable.
+ */
+
+import { AlertTriangle, TrendingDown, TrendingUp } from "lucide-react";
+import useSWR from "swr";
+
+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+import { TrendChart, deltaColor, formatDelta } from "@repowise-dev/ui/health";
+import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
+import { ResponsiveTable, type ResponsiveColumn } from "@repowise-dev/ui/shared";
+
+import {
+ getHealthTrend,
+ type HealthTrendResponse,
+} from "@/lib/api/code-health";
+
+type FileDelta = HealthTrendResponse["file_deltas"][number];
+
+export function TrendTab({ repoId: id }: { repoId: string }) {
+ const { data, isLoading, error } = useSWR<HealthTrendResponse>(
+ `code-health-trend:${id}`,
+ () => getHealthTrend(id, 20),
+ { revalidateOnFocus: false },
+ );
+
+ if (isLoading) return <Skeleton className="h-64 w-full rounded-lg" />;
+ if (error || !data) {
+ return (
+ <EmptyState
+ title="Couldn't load trend data"
+ description="The trend endpoint returned an error. Try refreshing."
+ />
+ );
+ }
+
+ const singleSnapshot = data.snapshot_count <= 1;
+
+ const deltaColumns: ResponsiveColumn<FileDelta>[] = [
+ {
+ key: "file_path",
+ header: "File",
+ priority: 1,
+ render: (d) => (
+ <span
+ className="font-mono text-xs text-[var(--color-text-primary)] truncate max-w-[420px] inline-block"
+ title={d.file_path}
+ >
+ {d.file_path}
+ </span>
+ ),
+ },
+ {
+ key: "before",
+ header: "Before",
+ priority: 2,
+ align: "right",
+ render: (d) => (
+ <span className="tabular-nums text-[var(--color-text-secondary)]">
+ {d.before.toFixed(1)}
+ </span>
+ ),
+ },
+ {
+ key: "after",
+ header: "After",
+ priority: 2,
+ align: "right",
+ render: (d) => (
+ <span className="tabular-nums text-[var(--color-text-secondary)]">
+ {d.after.toFixed(1)}
+ </span>
+ ),
+ },
+ {
+ key: "delta",
+ header: "Δ",
+ priority: 1,
+ align: "right",
+ render: (d) => (
+ <span className={`tabular-nums inline-flex items-center gap-1 ${deltaColor(d.delta)}`}>
+ {d.delta < 0 ? <TrendingDown className="h-3 w-3" /> : null}
+ {formatDelta(d.delta)}
+ </span>
+ ),
+ },
+ ];
+
+ return (
+ <div className="space-y-6">
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
+ <DeltaCard
+ label="Average health"
+ current={data.summary.current_average_health}
+ previous={data.summary.previous_average_health}
+ delta={data.summary.average_delta}
+ />
+ <DeltaCard
+ label="Hotspot health"
+ current={data.summary.current_hotspot_health}
+ previous={data.summary.previous_hotspot_health}
+ delta={data.summary.hotspot_delta}
+ />
+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">
+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
+ Snapshots
+ </p>
+ <p className="mt-1 text-2xl font-bold text-[var(--color-text-primary)] tabular-nums">
+ {data.snapshot_count}
+ </p>
+ <p className="text-[11px] text-[var(--color-text-tertiary)] mt-1">
+ rolling window: 50 max
+ </p>
+ </div>
+ </div>
+
+ {data.alerts.length > 0 ? (
+ <div className="space-y-2">
+ {data.alerts.map((a, i) => (
+ <div
+ key={i}
+ className={`rounded-lg border p-3 flex items-start gap-2 ${
+ a.kind === "declining"
+ ? "border-[var(--color-error)]/40 bg-[var(--color-error)]/5"
+ : "border-[var(--color-warning)]/40 bg-[var(--color-warning)]/5"
+ }`}
+ >
+ <AlertTriangle
+ className={`h-4 w-4 mt-0.5 ${a.kind === "declining" ? "text-[var(--color-error)]" : "text-[var(--color-warning)]"}`}
+ />
+ <div className="text-sm">
+ <p className="font-medium text-[var(--color-text-primary)]">
+ {a.kind === "declining" ? "Declining health" : "Predicted decline"}
+ </p>
+ <p className="text-xs text-[var(--color-text-secondary)]">{a.message}</p>
+ </div>
+ </div>
+ ))}
+ </div>
+ ) : null}
+
+ {singleSnapshot ? (
+ <EmptyState
+ icon={<TrendingUp className="h-6 w-6" />}
+ title="One snapshot so far"
+ description="The trend lines appear once a second snapshot lands. Run repowise update (or wait for the next sync) and this page fills in."
+ />
+ ) : (
+ <TrendChart history={[...data.history].reverse()} />
+ )}
+
+ <section className="space-y-2">
+ <h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ Largest score changes since last index
+ </h2>
+ {data.file_deltas.length === 0 ? (
+ <EmptyState
+ title={
+ singleSnapshot
+ ? "No comparison available yet"
+ : "No per-file changes between the last two snapshots"
+ }
+ description={
+ singleSnapshot
+ ? "Per-file deltas compare the last two snapshots."
+ : undefined
+ }
+ />
+ ) : (
+ <ResponsiveTable
+ columns={deltaColumns}
+ rows={data.file_deltas}
+ rowKey={(d) => d.file_path}
+ stacked="sm"
+ />
+ )}
+ </section>
+ </div>
+ );
+}
+
+function DeltaCard({
+ label,
+ current,
+ previous,
+ delta,
+}: {
+ label: string;
+ current: number;
+ previous: number | null;
+ delta: number | null;
+}) {
+ return (
+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">
+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">
+ {label}
+ </p>
+ <p className="mt-1 text-2xl font-bold text-[var(--color-text-primary)] tabular-nums">
+ {current.toFixed(1)}
+ <span className="text-base font-normal text-[var(--color-text-secondary)]">/10</span>
+ </p>
+ <p className={`text-[11px] tabular-nums mt-0.5 ${deltaColor(delta)}`}>
+ {delta == null
+ ? "no prior snapshot"
+ : `${formatDelta(delta)} vs. ${previous?.toFixed(1) ?? "—"}`}
+ </p>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/code-health/triage-tab.tsx b/packages/web/src/components/code-health/triage-tab.tsx
new file mode 100644
index 000000000..1a83d04a9
--- /dev/null
+++ b/packages/web/src/components/code-health/triage-tab.tsx
@@ -0,0 +1,625 @@
+"use client";
+
+/**
+ * Triage tab — the "what do I fix next" queue. KPI strip, the ranked
+ * fix-next list (refactoring-target ranking + file inventory merged into one
+ * view), a findings sidebar coordinated by the same severity filter, and the
+ * function-level panels.
+ */
+
+import { useMemo, useState } from "react";
+import useSWR from "swr";
+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+import { Button } from "@repowise-dev/ui/ui/button";
+import { EmptyState } from "@repowise-dev/ui/shared/empty-state";
+import { symbolEntityPath } from "@repowise-dev/ui/shared/entity";
+import {
+ AiPromptModal,
+ HealthKpiCards,
+ HealthFileTable,
+ BiomarkerList,
+ HotFunctionsPanel,
+ HiddenCouplingList,
+ ImpactEffortQuadrant,
+ RecalibrationBanner,
+ RefactoringTargetList,
+ DefectAccuracyCard,
+ biomarkerLabel,
+ buildAiPrompt,
+ type FileSortField,
+ type FindingStatus,
+ type RefactoringTarget,
+ type Severity,
+} from "@repowise-dev/ui/health";
+import { Search } from "lucide-react";
+import {
+ getHealthOverview,
+ getHealthTrend,
+ getRefactoringTargets,
+ listHealthFiles,
+ listHealthFindings,
+ updateFindingStatus,
+ type HealthFinding,
+ type HealthOverviewResponse,
+ type HealthTrendResponse,
+ type HealthFilesResponse,
+ type RefactoringTargetsResponse,
+ type RefactoringQuery,
+} from "@/lib/api/code-health";
+import { HealthFileDrawerHost } from "@/components/health/health-file-drawer-host";
+
+const PAGE_SIZE = 50;
+const QUEUE_PAGE = 200;
+const QUEUE_MAX = 500;
+
+type GroupBy = "none" | "biomarker" | "module" | "effort";
+type QueueView = "queue" | "files";
+
+const EFFORT_LABEL: Record<string, string> = {
+ S: "Small (≤40 NLOC)",
+ M: "Medium (≤150 NLOC)",
+ L: "Large (≤400 NLOC)",
+ XL: "Extra large (>400 NLOC)",
+};
+
+export function TriageTab({ repoId: id }: { repoId: string }) {
+ const { data: overview, isLoading, error, mutate } = useSWR<HealthOverviewResponse>(
+ `code-health-overview:${id}`,
+ () => getHealthOverview(id, 25),
+ { revalidateOnFocus: false },
+ );
+ const { data: hotFunctionFindings } = useSWR<HealthFinding[]>(
+ `code-health-hot-functions:${id}`,
+ async () => {
+ const types = [
+ "function_hotspot",
+ "code_age_volatility",
+ "complex_conditional",
+ ] as const;
+ const batches = await Promise.all(
+ types.map((t) =>
+ listHealthFindings(id, { biomarker_type: t, limit: 100 }).catch(
+ () => [] as HealthFinding[],
+ ),
+ ),
+ );
+ return batches.flat();
+ },
+ { revalidateOnFocus: false },
+ );
+
+ const { data: couplingFindings } = useSWR<HealthFinding[]>(
+ `code-health-hidden-coupling:${id}`,
+ () =>
+ listHealthFindings(id, {
+ biomarker_type: "hidden_coupling",
+ limit: 100,
+ }).catch(() => []),
+ { revalidateOnFocus: false },
+ );
+
+ const { data: trend } = useSWR<HealthTrendResponse>(
+ `code-health-trend:${id}`,
+ () => getHealthTrend(id, 20),
+ { revalidateOnFocus: false },
+ );
+
+ // ---- One filter set coordinates the queue AND the findings sidebar ----
+ const [minSeverity, setMinSeverity] = useState<Severity | "all">("all");
+ const [biomarker, setBiomarker] = useState<string>("all");
+ const [maxEffort, setMaxEffort] = useState<string>("all");
+ const [sort, setSort] = useState<RefactoringQuery["sort"]>("impact_per_effort");
+ const [groupBy, setGroupBy] = useState<GroupBy>("none");
+ const [queueLimit, setQueueLimit] = useState(QUEUE_PAGE);
+ const [view, setView] = useState<QueueView>("queue");
+ const [selectedFile, setSelectedFile] = useState<string | null>(null);
+ const [promptTarget, setPromptTarget] = useState<RefactoringTarget | null>(null);
+ const [highlighted, setHighlighted] = useState<string | null>(null);
+
+ const queueKey = useMemo(
+ () => JSON.stringify({ id, biomarker, minSeverity, maxEffort, sort, queueLimit }),
+ [id, biomarker, minSeverity, maxEffort, sort, queueLimit],
+ );
+ const {
+ data: queue,
+ isLoading: queueLoading,
+ mutate: mutateQueue,
+ } = useSWR<RefactoringTargetsResponse>(
+ overview ? `code-health-queue:${queueKey}` : null,
+ () =>
+ getRefactoringTargets(id, {
+ limit: queueLimit,
+ biomarker: biomarker === "all" ? undefined : biomarker,
+ min_severity: minSeverity === "all" ? undefined : minSeverity,
+ max_effort: maxEffort === "all" ? undefined : maxEffort,
+ sort,
+ }),
+ { revalidateOnFocus: false, keepPreviousData: true },
+ );
+
+ // ---- All-files inventory view ----
+ const [sortField, setSortField] = useState<FileSortField>("score");
+ const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");
+ const [search, setSearch] = useState("");
+ const [onlyHotspots, setOnlyHotspots] = useState(false);
+ const [onlyUntested, setOnlyUntested] = useState(false);
+ const [onlyFailing, setOnlyFailing] = useState(false);
+ const [offset, setOffset] = useState(0);
+
+ const filesKey = useMemo(
+ () =>
+ JSON.stringify({
+ id,
+ sortField,
+ sortOrder,
+ search,
+ onlyHotspots,
+ onlyUntested,
+ onlyFailing,
+ offset,
+ }),
+ [id, sortField, sortOrder, search, onlyHotspots, onlyUntested, onlyFailing, offset],
+ );
+
+ const { data: files, isLoading: filesLoading } = useSWR<HealthFilesResponse>(
+ overview && view === "files" ? `code-health-files:${filesKey}` : null,
+ () =>
+ listHealthFiles(id, {
+ sort: sortField,
+ order: sortOrder,
+ search: search || undefined,
+ only_hotspots: onlyHotspots || undefined,
+ only_untested: onlyUntested || undefined,
+ only_failing: onlyFailing || undefined,
+ offset,
+ limit: PAGE_SIZE,
+ }),
+ { revalidateOnFocus: false, keepPreviousData: true },
+ );
+
+ const handleSort = (field: FileSortField) => {
+ if (field === sortField) {
+ setSortOrder((o) => (o === "asc" ? "desc" : "asc"));
+ } else {
+ setSortField(field);
+ // Score: asc (worst first). Counts: desc. Path: asc.
+ setSortOrder(["score", "line_coverage_pct", "file_path"].includes(field) ? "asc" : "desc");
+ }
+ setOffset(0);
+ };
+
+ const handleStatus = async (findingId: string, status: FindingStatus) => {
+ await updateFindingStatus(id, findingId, status);
+ mutateQueue();
+ };
+
+ const biomarkerOptions = useMemo(() => {
+ const set = new Set<string>();
+ (overview?.biomarkers ?? []).forEach((b) => set.add(b.biomarker_type));
+ (queue?.targets ?? []).forEach((t) => t.biomarkers.forEach((b) => set.add(b)));
+ return [...set].sort();
+ }, [overview, queue]);
+
+ // Grouped queue — group order follows the user's sort (first occurrence),
+ // not group size, so "Leverage" sorted stays leverage-led inside and out.
+ const grouped = useMemo(() => {
+ const targets = queue?.targets ?? [];
+ if (groupBy === "none") return [{ key: "All", targets }];
+ const groups = new Map<string, typeof targets>();
+ for (const t of targets) {
+ let key = "—";
+ if (groupBy === "biomarker") key = biomarkerLabel(t.primary_biomarker);
+ else if (groupBy === "module") key = t.module ?? "(no module)";
+ else if (groupBy === "effort") key = EFFORT_LABEL[t.effort_bucket] ?? t.effort_bucket;
+ if (!groups.has(key)) groups.set(key, []);
+ groups.get(key)!.push(t);
+ }
+ return [...groups.entries()].map(([key, targets]) => ({ key, targets }));
+ }, [queue, groupBy]);
+
+ // Quadrant dot click → highlight + scroll to the card.
+ const highlightTarget = (path: string) => {
+ setHighlighted(path);
+ requestAnimationFrame(() => {
+ document
+ .querySelector(`[data-refactoring-card="${CSS.escape(path)}"]`)
+ ?.scrollIntoView({ behavior: "smooth", block: "center" });
+ });
+ window.setTimeout(
+ () => setHighlighted((p) => (p === path ? null : p)),
+ 2400,
+ );
+ };
+
+ const avgSeries = trend?.history?.slice().reverse().map((p) => p.average_health);
+ const hotspotSeries = trend?.history?.slice().reverse().map((p) => p.hotspot_health);
+ const worstSeries = trend?.history
+ ?.slice()
+ .reverse()
+ .map((p) => p.worst_performer_score ?? 0);
+
+ return (
+ <div className="space-y-6">
+ {isLoading ? (
+ <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-5 gap-3">
+ {Array.from({ length: 5 }).map((_, i) => (
+ <Skeleton key={i} className="h-24 w-full rounded-lg" />
+ ))}
+ </div>
+ ) : error ? (
+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)] flex items-center justify-between gap-2">
+ <span>Couldn&apos;t load health data. Run <code>repowise init</code> to populate.</span>
+ <Button size="sm" variant="outline" onClick={() => mutate()}>Retry</Button>
+ </div>
+ ) : overview ? (
+ <>
+ <RecalibrationBanner repoId={id} />
+ <HealthKpiCards
+ summary={overview.summary}
+ averageHistory={avgSeries}
+ hotspotHistory={hotspotSeries}
+ worstHistory={worstSeries}
+ averageDelta={trend?.summary?.average_delta ?? undefined}
+ hotspotDelta={trend?.summary?.hotspot_delta ?? undefined}
+ />
+
+ {overview.defect_accuracy ? (
+ <DefectAccuracyCard data={overview.defect_accuracy} collapsible />
+ ) : null}
+
+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
+ <div className="lg:col-span-2 space-y-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] mr-auto">
+ Fix next
+ </h2>
+ <ViewToggle view={view} onChange={setView} />
+ </div>
+
+ {view === "queue" ? (
+ <>
+ <div className="flex flex-wrap items-center gap-2">
+ <FilterSelect
+ label="Severity"
+ value={minSeverity}
+ onChange={(v) => setMinSeverity(v as Severity | "all")}
+ options={[
+ { value: "all", label: "Any severity" },
+ { value: "low", label: "Low+" },
+ { value: "medium", label: "Medium+" },
+ { value: "high", label: "High+" },
+ { value: "critical", label: "Critical only" },
+ ]}
+ />
+ <FilterSelect
+ label="Biomarker"
+ value={biomarker}
+ onChange={setBiomarker}
+ options={[
+ { value: "all", label: "All biomarkers" },
+ ...biomarkerOptions.map((b) => ({ value: b, label: biomarkerLabel(b) })),
+ ]}
+ />
+ <FilterSelect
+ label="Max effort"
+ value={maxEffort}
+ onChange={setMaxEffort}
+ options={[
+ { value: "all", label: "Any effort" },
+ { value: "S", label: "Small only" },
+ { value: "M", label: "Medium+" },
+ { value: "L", label: "Large+" },
+ ]}
+ />
+ <FilterSelect
+ label="Sort"
+ value={sort ?? "impact_per_effort"}
+ onChange={(v) => setSort(v as RefactoringQuery["sort"])}
+ options={[
+ { value: "impact_per_effort", label: "Leverage (impact ÷ effort)" },
+ { value: "total_impact", label: "Total impact" },
+ { value: "score", label: "Worst score" },
+ { value: "finding_count", label: "Finding count" },
+ ]}
+ />
+ <FilterSelect
+ label="Group"
+ value={groupBy}
+ onChange={(v) => setGroupBy(v as GroupBy)}
+ options={[
+ { value: "none", label: "Flat list" },
+ { value: "biomarker", label: "By biomarker" },
+ { value: "module", label: "By module" },
+ { value: "effort", label: "By effort" },
+ ]}
+ />
+ </div>
+
+ {queueLoading && !queue ? (
+ <div className="grid gap-3">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Skeleton key={i} className="h-28 w-full" />
+ ))}
+ </div>
+ ) : !queue || queue.targets.length === 0 ? (
+ <EmptyState
+ title="No findings match the current filters"
+ description="Try widening the severity or effort filters, or run repowise health to populate findings."
+ />
+ ) : (
+ <>
+ <ImpactEffortQuadrant
+ points={queue.targets.map((t) => ({
+ file_path: t.file_path,
+ total_impact: t.total_impact,
+ effort_bucket: t.effort_bucket,
+ nloc: t.nloc,
+ score: t.score,
+ }))}
+ onSelect={(p) => highlightTarget(p.file_path)}
+ />
+
+ <div className="space-y-6">
+ {grouped.map((g) => (
+ <section key={g.key} className="space-y-2">
+ {groupBy !== "none" ? (
+ <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ {g.key}{" "}
+ <span className="text-[var(--color-text-secondary)]">
+ ({g.targets.length})
+ </span>
+ </h3>
+ ) : null}
+ <RefactoringTargetList
+ targets={g.targets}
+ onSelect={(t) => setSelectedFile(t.file_path)}
+ onStatusChange={handleStatus}
+ onGeneratePrompt={(t) => setPromptTarget(t)}
+ highlightedPath={highlighted}
+ />
+ </section>
+ ))}
+ </div>
+
+ <div className="flex items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)]">
+ <span>
+ Showing {queue.targets.length} of {queue.total} candidates
+ </span>
+ {queue.total > queue.targets.length && queueLimit < QUEUE_MAX ? (
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => setQueueLimit(QUEUE_MAX)}
+ >
+ Load more
+ </Button>
+ ) : null}
+ </div>
+ </>
+ )}
+ </>
+ ) : (
+ <>
+ <div className="flex flex-wrap items-center gap-2">
+ <div className="relative">
+ <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />
+ <input
+ value={search}
+ onChange={(e) => {
+ setSearch(e.target.value);
+ setOffset(0);
+ }}
+ placeholder="Filter path…"
+ className="text-xs pl-7 pr-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-56 focus:outline-none focus:border-[var(--color-border-strong)]"
+ />
+ </div>
+ <FilterChip active={onlyHotspots} onClick={() => { setOnlyHotspots((v) => !v); setOffset(0); }}>
+ Hotspots
+ </FilterChip>
+ <FilterChip active={onlyUntested} onClick={() => { setOnlyUntested((v) => !v); setOffset(0); }}>
+ Untested
+ </FilterChip>
+ <FilterChip active={onlyFailing} onClick={() => { setOnlyFailing((v) => !v); setOffset(0); }}>
+ Failing
+ </FilterChip>
+ <span className="text-xs text-[var(--color-text-tertiary)] ml-auto">
+ {files?.total != null ? `${files.total.toLocaleString()} files` : ""}
+ </span>
+ </div>
+
+ {filesLoading && !files ? (
+ <Skeleton className="h-64 w-full rounded-lg" />
+ ) : (
+ <HealthFileTable
+ files={files?.files ?? []}
+ sortField={sortField}
+ sortOrder={sortOrder}
+ onSort={handleSort}
+ onSelect={(f) => setSelectedFile(f.file_path)}
+ selectedPath={selectedFile}
+ />
+ )}
+
+ {files && files.total > PAGE_SIZE ? (
+ <div className="flex items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)]">
+ <span>
+ Showing {offset + 1}–{Math.min(offset + PAGE_SIZE, files.total)} of {files.total}
+ </span>
+ <div className="flex gap-1">
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={offset === 0}
+ onClick={() => setOffset(Math.max(0, offset - PAGE_SIZE))}
+ >
+ Prev
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={offset + PAGE_SIZE >= files.total}
+ onClick={() => setOffset(offset + PAGE_SIZE)}
+ >
+ Next
+ </Button>
+ </div>
+ </div>
+ ) : null}
+ </>
+ )}
+ </div>
+
+ <div className="space-y-3">
+ <div className="flex items-center gap-2">
+ <h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] mr-auto">
+ Findings
+ </h2>
+ <select
+ value={minSeverity}
+ onChange={(e) => setMinSeverity(e.target.value as Severity | "all")}
+ aria-label="Minimum severity (filters the queue too)"
+ className="text-xs px-2 py-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]"
+ >
+ <option value="all">All severities</option>
+ <option value="low">Low+</option>
+ <option value="medium">Medium+</option>
+ <option value="high">High+</option>
+ <option value="critical">Critical</option>
+ </select>
+ </div>
+ <BiomarkerList
+ findings={overview.top_findings}
+ grouped
+ minSeverity={minSeverity === "all" ? undefined : minSeverity}
+ onSelect={(f) => setSelectedFile(f.file_path)}
+ />
+ </div>
+ </div>
+
+ {hotFunctionFindings && hotFunctionFindings.length >= 3 ? (
+ <HotFunctionsPanel
+ findings={hotFunctionFindings}
+ onSelect={(f) => setSelectedFile(f.file_path)}
+ symbolHrefFor={(f) =>
+ f.symbol_id ? symbolEntityPath(`/repos/${id}`, f.symbol_id) : undefined
+ }
+ />
+ ) : null}
+
+ {couplingFindings && couplingFindings.length >= 3 ? (
+ <HiddenCouplingList
+ findings={couplingFindings}
+ onSelect={(path) => setSelectedFile(path)}
+ />
+ ) : null}
+ </>
+ ) : null}
+
+ <HealthFileDrawerHost
+ repoId={id}
+ filePath={selectedFile}
+ onClose={() => setSelectedFile(null)}
+ />
+
+ <AiPromptModal
+ open={promptTarget !== null}
+ onOpenChange={(open) => {
+ if (!open) setPromptTarget(null);
+ }}
+ filePath={promptTarget?.file_path}
+ title="AI fix prompt"
+ description="A ready-to-paste prompt that gives your AI coding agent every biomarker, line range, score deduction, and constraint needed to refactor this file in one focused pass."
+ getPrompt={
+ promptTarget
+ ? (flavor) => buildAiPrompt({ target: promptTarget, flavor })
+ : null
+ }
+ />
+ </div>
+ );
+}
+
+function ViewToggle({
+ view,
+ onChange,
+}: {
+ view: QueueView;
+ onChange: (v: QueueView) => void;
+}) {
+ return (
+ <div className="flex rounded-md border border-[var(--color-border-default)] overflow-hidden text-xs">
+ {(
+ [
+ { value: "queue", label: "Queue" },
+ { value: "files", label: "All files" },
+ ] as { value: QueueView; label: string }[]
+ ).map((opt) => (
+ <button
+ key={opt.value}
+ type="button"
+ onClick={() => onChange(opt.value)}
+ className={`px-3 py-1.5 font-medium transition-colors ${
+ view === opt.value
+ ? "bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)]"
+ : "bg-transparent text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]"
+ }`}
+ >
+ {opt.label}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+function FilterSelect({
+ label,
+ value,
+ onChange,
+ options,
+}: {
+ label: string;
+ value: string;
+ onChange: (v: string) => void;
+ options: { value: string; label: string }[];
+}) {
+ return (
+ <label className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)]">
+ <span className="uppercase tracking-wider">{label}</span>
+ <select
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ className="text-xs px-2 py-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)]"
+ >
+ {options.map((o) => (
+ <option key={o.value} value={o.value}>
+ {o.label}
+ </option>
+ ))}
+ </select>
+ </label>
+ );
+}
+
+function FilterChip({
+ active,
+ onClick,
+ children,
+}: {
+ active: boolean;
+ onClick: () => void;
+ children: React.ReactNode;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={`text-xs rounded-md px-2 py-1 border transition-colors ${
+ active
+ ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)] border-[var(--color-accent-primary)]/50"
+ : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"
+ }`}
+ >
+ {children}
+ </button>
+ );
+}
diff --git a/packages/web/src/components/commits/commits-explorer.tsx b/packages/web/src/components/commits/commits-explorer.tsx
index e4c07c3a9..b222b3bca 100644
--- a/packages/web/src/components/commits/commits-explorer.tsx
+++ b/packages/web/src/components/commits/commits-explorer.tsx
@@ -2,6 +2,7 @@
import { useState } from "react";
import useSWR from "swr";
+import { useQueryState } from "nuqs";
import { AlertTriangle, Bug, GitCommitHorizontal } from "lucide-react";
import { StatCard } from "@repowise-dev/ui/shared/stat-card";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
@@ -11,25 +12,39 @@ import {
SheetHeader,
SheetTitle,
} from "@repowise-dev/ui/ui/sheet";
-import { CommitTable, type CommitSort } from "@repowise-dev/ui/commits/commit-table";
+import {
+ CommitTable,
+ type CommitAuthorship,
+ type CommitSort,
+} from "@repowise-dev/ui/commits/commit-table";
import { CommitDetailCard } from "@repowise-dev/ui/commits/commit-detail-card";
import { CredibilityStrip } from "@repowise-dev/ui/commits/credibility-strip";
-import { getCommit, getCommitsPage } from "@/lib/api/git";
+import { AgentTrendStrip } from "@repowise-dev/ui/commits/agent-trend-strip";
+import { getAgentTrend, getCommit, getCommitsPage } from "@/lib/api/git";
import type { CommitResponse, Paginated } from "@/lib/api/types";
const PAGE_SIZE = 50;
export function CommitsExplorer({ repoId }: { repoId: string }) {
const [sort, setSort] = useState<CommitSort>("risk");
+ const [authorship, setAuthorship] = useState<CommitAuthorship>("all");
const [limit, setLimit] = useState(PAGE_SIZE);
- const [selectedSha, setSelectedSha] = useState<string | null>(null);
+ // ?commit= deep link — entity links from Overview/file pages land here with
+ // the detail sheet already open, and the sheet state survives refresh.
+ const [selectedSha, setSelectedSha] = useQueryState("commit");
const { data, isLoading, isValidating, error } = useSWR<Paginated<CommitResponse>>(
- `commits:${repoId}:${sort}:${limit}`,
- () => getCommitsPage(repoId, { sort, limit }),
+ `commits:${repoId}:${sort}:${authorship}:${limit}`,
+ () => getCommitsPage(repoId, { sort, authorship, limit }),
{ revalidateOnFocus: false, keepPreviousData: true },
);
+ const { data: trend } = useSWR(
+ `agent-trend:${repoId}`,
+ () => getAgentTrend(repoId),
+ { revalidateOnFocus: false },
+ );
+
const { data: detail, isLoading: detailLoading } = useSWR(
selectedSha ? `commit:${repoId}:${selectedSha}` : null,
() => getCommit(repoId, selectedSha as string),
@@ -69,6 +84,8 @@ export function CommitsExplorer({ repoId }: { repoId: string }) {
<div className="space-y-6">
<CredibilityStrip />
+ {trend && <AgentTrendStrip trend={trend} />}
+
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
<StatCard
label="Commits"
@@ -80,13 +97,13 @@ export function CommitsExplorer({ repoId }: { repoId: string }) {
label="High priority"
value={highCount}
description="top tercile (loaded)"
- icon={<AlertTriangle className="h-4 w-4 text-red-400" />}
+ icon={<AlertTriangle className="h-4 w-4 text-[var(--color-error)]" />}
/>
<StatCard
label="Fix commits"
value={fixCount}
description="bug-fix subjects"
- icon={<Bug className="h-4 w-4 text-orange-400" />}
+ icon={<Bug className="h-4 w-4 text-[var(--color-warning)]" />}
/>
<StatCard
label="Avg entropy"
@@ -102,14 +119,22 @@ export function CommitsExplorer({ repoId }: { repoId: string }) {
setSort(s);
setLimit(PAGE_SIZE);
}}
- onSelect={(c) => setSelectedSha(c.sha)}
+ authorship={authorship}
+ onAuthorshipChange={(a) => {
+ setAuthorship(a);
+ setLimit(PAGE_SIZE);
+ }}
+ onSelect={(c) => void setSelectedSha(c.sha)}
total={total}
hasMore={hasMore}
loadingMore={isValidating && !isLoading}
onLoadMore={() => setLimit((n) => Math.min(n + PAGE_SIZE, 200))}
/>
- <Sheet open={selectedSha !== null} onOpenChange={(open) => !open && setSelectedSha(null)}>
+ <Sheet
+ open={selectedSha !== null}
+ onOpenChange={(open) => !open && void setSelectedSha(null)}
+ >
<SheetContent side="right" className="w-[440px] max-w-[92vw] sm:w-[560px]">
<SheetHeader>
<SheetTitle>Commit change-risk</SheetTitle>
diff --git a/packages/web/src/components/dead-code/finding-row.tsx b/packages/web/src/components/dead-code/finding-row.tsx
index 5c82ec3eb..30e1c951c 100644
--- a/packages/web/src/components/dead-code/finding-row.tsx
+++ b/packages/web/src/components/dead-code/finding-row.tsx
@@ -161,8 +161,8 @@ export function FindingRow({ finding, repoId, selected, onToggle, onUpdate }: Fi
<div className="flex items-center gap-1 flex-wrap justify-end">
<RowActions
actions={[
- { icon: GitBranch, label: "Graph", href: `/repos/${repoId}/graph?node=${encodeURIComponent(finding.file_path)}` },
- ...(finding.symbol_name ? [{ icon: Code2, label: "Symbol", href: `/repos/${repoId}/symbols` }] : []),
+ { icon: GitBranch, label: "Graph", href: `/repos/${repoId}/architecture?view=graph&node=${encodeURIComponent(finding.file_path)}` },
+ ...(finding.symbol_name ? [{ icon: Code2, label: "Symbol", href: `/repos/${repoId}/architecture?view=symbols` }] : []),
]}
/>
{finding.status === "open" && (
diff --git a/packages/web/src/components/dead-code/findings-table.tsx b/packages/web/src/components/dead-code/findings-table.tsx
index 3122a69a5..2985eb33b 100644
--- a/packages/web/src/components/dead-code/findings-table.tsx
+++ b/packages/web/src/components/dead-code/findings-table.tsx
@@ -192,7 +192,7 @@ export function FindingsTable({ repoId }: FindingsTableProps) {
/>
) : (
<div className="rounded-lg border border-[var(--color-border-default)] overflow-x-auto mt-2">
- <table className="w-full text-sm">
+ <table className="w-full min-w-[640px] text-sm">
<caption className="sr-only">Dead code findings</caption>
<thead className="sticky top-0 z-10 bg-[var(--color-bg-elevated)]">
<tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">
diff --git a/packages/web/src/components/decisions/decision-detail.tsx b/packages/web/src/components/decisions/decision-detail.tsx
index 0740ceee8..0c5d5b391 100644
--- a/packages/web/src/components/decisions/decision-detail.tsx
+++ b/packages/web/src/components/decisions/decision-detail.tsx
@@ -6,7 +6,7 @@ import remarkGfm from "remark-gfm";
import useSWR from "swr";
import { toast } from "sonner";
import Link from "next/link";
-import { ChevronLeft, FileSearch } from "lucide-react";
+import { ChevronLeft, ChevronRight, FileSearch, Flame, GitCommitHorizontal } from "lucide-react";
import { Badge } from "@repowise-dev/ui/ui/badge";
import { stripMarkdown } from "@repowise-dev/ui/lib/format";
import { ConfirmDialog } from "@repowise-dev/ui/ui/confirm-dialog";
@@ -17,6 +17,7 @@ import { DecisionLineage } from "@repowise-dev/ui/decisions/decision-lineage";
import {
getDecisionEvidence,
getDecisionLineage,
+ listDecisions,
patchDecision,
} from "@/lib/api/decisions";
import { listModuleHealth } from "@/lib/api/modules";
@@ -76,6 +77,21 @@ export function DecisionDetail({ decision, repoId }: DecisionDetailProps) {
{ revalidateOnFocus: false },
);
+ // Sibling list for prev/next navigation — same ordering as the list page.
+ const { data: siblings } = useSWR(
+ `decisions-siblings:${repoId}`,
+ () => listDecisions(repoId, { include_proposed: true, limit: 100 }),
+ { revalidateOnFocus: false },
+ );
+ const { prevId, nextId } = React.useMemo(() => {
+ const ids = (siblings ?? []).map((d) => d.id);
+ const idx = ids.indexOf(decision.id);
+ return {
+ prevId: idx > 0 ? ids[idx - 1] : null,
+ nextId: idx >= 0 && idx < ids.length - 1 ? ids[idx + 1] : null,
+ };
+ }, [siblings, decision.id]);
+
// Suggestions for the module autocomplete — top-level modules indexed for
// this repo. Loaded once; cheap to cache.
const { data: moduleHealth } = useSWR(
@@ -176,13 +192,29 @@ export function DecisionDetail({ decision, repoId }: DecisionDetailProps) {
return (
<div className="space-y-6">
- <Link
- href={`/repos/${repoId}/decisions`}
- className="inline-flex items-center gap-1 text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
- >
- <ChevronLeft className="h-3.5 w-3.5" />
- All decisions
- </Link>
+ <div className="flex items-center justify-between gap-2">
+ <Link
+ href={`/repos/${repoId}/decisions`}
+ className="inline-flex items-center gap-1 text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
+ >
+ <ChevronLeft className="h-3.5 w-3.5" />
+ All decisions
+ </Link>
+ <div className="flex items-center gap-1">
+ <PrevNextLink
+ href={prevId ? `/repos/${repoId}/decisions/${prevId}` : null}
+ label="Previous decision"
+ >
+ <ChevronLeft className="h-3.5 w-3.5" /> Prev
+ </PrevNextLink>
+ <PrevNextLink
+ href={nextId ? `/repos/${repoId}/decisions/${nextId}` : null}
+ label="Next decision"
+ >
+ Next <ChevronRight className="h-3.5 w-3.5" />
+ </PrevNextLink>
+ </div>
+ </div>
{/* Header */}
<div className="space-y-2">
<div className="flex flex-wrap items-center gap-3">
@@ -255,18 +287,50 @@ export function DecisionDetail({ decision, repoId }: DecisionDetailProps) {
onSave={saveLinkage}
/>
+ {/* The full evidence rows live in the drawer (Evidence button); this
+ card answers "what happened to the governed code since?". */}
<div className="rounded-lg border border-[var(--color-border-default)] p-4">
- <h3 className="mb-2 text-sm font-medium text-[var(--color-text-secondary)]">Evidence</h3>
- <div className="space-y-1 text-sm text-[var(--color-text-tertiary)]">
- <div>Source: {decision.source}</div>
- {decision.evidence_file && (
- <div className="font-mono text-xs">
- {decision.evidence_file}
- {decision.evidence_line && `:${decision.evidence_line}`}
- </div>
+ <h3 className="mb-2 text-sm font-medium text-[var(--color-text-secondary)]">
+ Since this decision
+ </h3>
+ <div className="space-y-2 text-sm">
+ {decision.last_code_change && (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Affected files last changed{" "}
+ {new Date(decision.last_code_change).toLocaleDateString()}.
+ </p>
)}
+ <div className="flex flex-col gap-1.5">
+ <Link
+ href={`/repos/${repoId}/commits?sort=date`}
+ className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:underline"
+ >
+ <GitCommitHorizontal className="h-3.5 w-3.5" />
+ Recent commits to this repo
+ </Link>
+ <Link
+ href={`/repos/${repoId}/code-health?tab=hotspots`}
+ className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:underline"
+ >
+ <Flame className="h-3.5 w-3.5" />
+ Hotspots &amp; churn in affected areas
+ </Link>
+ </div>
{decision.evidence_commits.length > 0 && (
- <div>Commits: {decision.evidence_commits.map((c) => c.slice(0, 8)).join(", ")}</div>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Evidence commits:{" "}
+ {decision.evidence_commits.slice(0, 4).map((c, i) => (
+ <React.Fragment key={c}>
+ {i > 0 && ", "}
+ <Link
+ href={`/repos/${repoId}/commits?commit=${c}`}
+ className="font-mono hover:text-[var(--color-accent-primary)] hover:underline"
+ >
+ {c.slice(0, 8)}
+ </Link>
+ </React.Fragment>
+ ))}
+ </p>
)}
</div>
</div>
@@ -341,6 +405,33 @@ export function DecisionDetail({ decision, repoId }: DecisionDetailProps) {
);
}
+function PrevNextLink({
+ href,
+ label,
+ children,
+}: {
+ href: string | null;
+ label: string;
+ children: React.ReactNode;
+}) {
+ if (!href) {
+ return (
+ <span className="inline-flex items-center gap-0.5 rounded-md border border-[var(--color-border-default)] px-2 py-1 text-xs text-[var(--color-text-tertiary)] opacity-50">
+ {children}
+ </span>
+ );
+ }
+ return (
+ <Link
+ href={href}
+ aria-label={label}
+ className="inline-flex items-center gap-0.5 rounded-md border border-[var(--color-border-default)] px-2 py-1 text-xs text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ >
+ {children}
+ </Link>
+ );
+}
+
function Section({ title, text }: { title: string; text: string }) {
return (
<div>
diff --git a/packages/web/src/components/docs/docs-header.tsx b/packages/web/src/components/docs/docs-header.tsx
index 609888e46..c08daf570 100644
--- a/packages/web/src/components/docs/docs-header.tsx
+++ b/packages/web/src/components/docs/docs-header.tsx
@@ -5,9 +5,11 @@ import { useParams, usePathname } from "next/navigation";
import { BookOpen, BarChart3 } from "lucide-react";
import { cn } from "@/lib/utils/cn";
+// "Doc freshness", not "Coverage" — coverage means test coverage everywhere
+// else in the app; this tab is about documentation staleness.
const TABS = [
{ label: "Explorer", segment: "", icon: BookOpen },
- { label: "Coverage", segment: "/coverage", icon: BarChart3 },
+ { label: "Doc freshness", segment: "/coverage", icon: BarChart3 },
] as const;
/**
diff --git a/packages/web/src/components/docs/docs-page-actions.tsx b/packages/web/src/components/docs/docs-page-actions.tsx
index c9239aa46..633b0769b 100644
--- a/packages/web/src/components/docs/docs-page-actions.tsx
+++ b/packages/web/src/components/docs/docs-page-actions.tsx
@@ -43,7 +43,7 @@ export function DocsPageActions({
<ConfidenceBadge score={page.confidence} status={page.freshness_status} />
{personaHasEffect && (
<div
- className="hidden md:inline-flex items-center rounded-md border border-[var(--color-border-default)] p-0.5 shrink-0"
+ className="inline-flex items-center rounded-md border border-[var(--color-border-default)] p-0.5 shrink-0"
role="group"
aria-label="Reader level"
>
diff --git a/packages/web/src/components/docs/docs-viewer.tsx b/packages/web/src/components/docs/docs-viewer.tsx
index 497cfb49a..37f1da8d4 100644
--- a/packages/web/src/components/docs/docs-viewer.tsx
+++ b/packages/web/src/components/docs/docs-viewer.tsx
@@ -119,7 +119,7 @@ function DocsSidebar({ repoId, targetPath }: { repoId: string; targetPath: strin
</span>
</div>
<Link
- href={`/repos/${repoId}/graph?colorMode=community`}
+ href={`/repos/${repoId}/architecture?view=graph&colorMode=community`}
className="inline-flex items-center gap-1 text-[11px] text-[var(--color-accent)] hover:underline"
>
{metrics.community_label}
@@ -726,6 +726,11 @@ function DocsViewerBody({
buildHref={(rid, pid) =>
`/repos/${rid}/docs?page=${encodeURIComponent(pid)}`
}
+ renderLink={({ href, className, title, children }) => (
+ <Link href={href} className={className} title={title}>
+ {children}
+ </Link>
+ )}
/>
{hasTargetPath && <DocsSidebar repoId={repoId} targetPath={page.target_path} />}
</div>
diff --git a/packages/web/src/components/files/file-page-host.tsx b/packages/web/src/components/files/file-page-host.tsx
new file mode 100644
index 000000000..7612f3ee7
--- /dev/null
+++ b/packages/web/src/components/files/file-page-host.tsx
@@ -0,0 +1,61 @@
+"use client";
+
+import type { ReactNode } from "react";
+import { useRouter } from "next/navigation";
+import { toast } from "sonner";
+import { FilePage, type FilePageTab, type FindingStatus } from "@repowise-dev/ui/files";
+import { updateFindingStatus } from "@/lib/api/code-health";
+import type { FileDetailResponse } from "@repowise-dev/types/files";
+
+interface FilePageHostProps {
+ repoId: string;
+ data: FileDetailResponse;
+ docSlot?: ReactNode;
+ coverageCodeHtml?: string;
+ wikiHref?: string;
+ initialTab?: FilePageTab;
+}
+
+/** Client host for the file entity page: wires finding triage to the API
+ * (with toasts) and keeps the active tab in the URL for deep links. */
+export function FilePageHost({
+ repoId,
+ data,
+ docSlot,
+ coverageCodeHtml,
+ wikiHref,
+ initialTab,
+}: FilePageHostProps) {
+ const router = useRouter();
+
+ const onTabChange = (tab: FilePageTab) => {
+ const sp = new URLSearchParams(window.location.search);
+ if (tab === "doc") sp.delete("tab");
+ else sp.set("tab", tab);
+ const qs = sp.toString();
+ router.replace(qs ? `?${qs}` : window.location.pathname, { scroll: false });
+ };
+
+ const onFindingStatusChange = async (findingId: string, status: FindingStatus) => {
+ try {
+ await updateFindingStatus(repoId, findingId, status);
+ toast.success(`Finding marked ${status.replace("_", " ")}`);
+ } catch (err) {
+ toast.error("Couldn't update finding status");
+ throw err;
+ }
+ };
+
+ return (
+ <FilePage
+ data={data}
+ repoId={repoId}
+ docSlot={docSlot}
+ coverageCodeHtml={coverageCodeHtml}
+ wikiHref={wikiHref}
+ initialTab={initialTab}
+ onTabChange={onTabChange}
+ onFindingStatusChange={onFindingStatusChange}
+ />
+ );
+}
diff --git a/packages/web/src/components/graph/graph-community-panel.tsx b/packages/web/src/components/graph/graph-community-panel.tsx
index 1db4e084a..5f2ead366 100644
--- a/packages/web/src/components/graph/graph-community-panel.tsx
+++ b/packages/web/src/components/graph/graph-community-panel.tsx
@@ -1,6 +1,7 @@
"use client";
import { GraphCommunityPanel as GraphCommunityPanelShell } from "@repowise-dev/ui/graph/graph-community-panel";
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
import { useCommunityDetail } from "@/lib/hooks/use-graph";
import type { CommunityDetail } from "@repowise-dev/types/graph";
@@ -26,6 +27,7 @@ export function GraphCommunityPanel({
isLoading={isLoading}
onClose={onClose}
onExpandOnCanvas={onExpandOnCanvas}
+ memberHref={(path) => fileEntityPath(`/repos/${repoId}`, path)}
/>
);
}
diff --git a/packages/web/src/components/graph/graph-doc-panel.tsx b/packages/web/src/components/graph/graph-doc-panel.tsx
index 961357c03..d407d9cbc 100644
--- a/packages/web/src/components/graph/graph-doc-panel.tsx
+++ b/packages/web/src/components/graph/graph-doc-panel.tsx
@@ -1,6 +1,7 @@
"use client";
import { GraphDocPanel as GraphDocPanelShell } from "@repowise-dev/ui/graph/graph-doc-panel";
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
import { usePage } from "@/lib/hooks/use-page";
import type { DocPage } from "@repowise-dev/types/docs";
@@ -20,9 +21,7 @@ export function GraphDocPanel({ repoId, nodeId, onClose }: GraphDocPanelWrapperP
page={page as DocPage | null | undefined}
isLoading={isLoading}
error={error}
- fullPageHref={
- page ? `/repos/${repoId}/wiki/${encodeURIComponent(page.id)}` : undefined
- }
+ fullPageHref={page ? fileEntityPath(`/repos/${repoId}`, nodeId) : undefined}
browseDocsHref={`/repos/${repoId}/docs`}
onClose={onClose}
/>
diff --git a/packages/web/src/components/graph/graph-flow.tsx b/packages/web/src/components/graph/graph-flow.tsx
index c0713cffd..9e9f09d19 100644
--- a/packages/web/src/components/graph/graph-flow.tsx
+++ b/packages/web/src/components/graph/graph-flow.tsx
@@ -1,6 +1,8 @@
"use client";
import { useState } from "react";
+import { useRouter } from "next/navigation";
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
import {
GraphFlow as GraphFlowShell,
type GraphFlowProps as GraphFlowShellProps,
@@ -34,6 +36,7 @@ export interface GraphFlowProps {
repoId: string;
repoName?: string;
initialViewMode?: ViewMode;
+ initialColorMode?: GraphFlowShellProps["initialColorMode"];
initialSelectedNode?: string | null;
onNodeClick?: GraphFlowShellProps["onNodeClick"];
onNodeViewDocs?: GraphFlowShellProps["onNodeViewDocs"];
@@ -45,18 +48,23 @@ export interface GraphFlowProps {
* track the current scope so it can conditionally fetch the capped full
* graph (and gate the truncation banner) only for scopes that render it. */
onViewModeChange?: (mode: ViewMode) => void;
+ /** Fired when the node color mode changes so the page can sync the URL. */
+ onColorModeChange?: GraphFlowShellProps["onColorModeChange"];
}
export function GraphFlow({
repoId,
repoName,
initialViewMode,
+ initialColorMode,
initialSelectedNode,
onNodeClick,
onNodeViewDocs,
onCommunityPanelOpen,
onViewModeChange,
+ onColorModeChange,
}: GraphFlowProps) {
+ const router = useRouter();
// Constellation (Knowledge Graph) is the default scope.
const [viewMode, setViewMode] = useState<ViewMode>(initialViewMode ?? "architecture");
const [modulePath, setModulePath] = useState<string[]>([]);
@@ -124,15 +132,23 @@ export function GraphFlow({
communities={communities as CommunitySummaryItem[] | undefined}
executionFlows={executionFlowsData as ExecutionFlows | undefined}
initialViewMode={initialViewMode}
+ initialColorMode={initialColorMode}
initialSelectedNode={initialSelectedNode}
onViewModeChange={(mode) => {
setViewMode(mode);
onViewModeChange?.(mode);
}}
+ onColorModeChange={onColorModeChange}
onModulePathChange={setModulePath}
onExpandedModulesChange={(expanded) => setHasExpandedModules(expanded.size > 0)}
onNodeClick={onNodeClick}
onNodeViewDocs={onNodeViewDocs}
+ onNodeViewSymbols={(nodeId) =>
+ router.push(
+ `/repos/${repoId}/architecture?view=symbols&file=${encodeURIComponent(nodeId)}`,
+ )
+ }
+ fileHrefFor={(nodeId) => fileEntityPath(`/repos/${repoId}`, nodeId)}
onCommunityPanelOpen={onCommunityPanelOpen}
renderPathFinder={(props) => (
<PathFinderPanel
diff --git a/packages/web/src/components/health/health-file-drawer-host.tsx b/packages/web/src/components/health/health-file-drawer-host.tsx
index ddd303e82..459ec8123 100644
--- a/packages/web/src/components/health/health-file-drawer-host.tsx
+++ b/packages/web/src/components/health/health-file-drawer-host.tsx
@@ -1,6 +1,9 @@
"use client";
+import { toast } from "sonner";
import { HealthFileDrawer } from "@repowise-dev/ui/health";
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
+import { updateFindingStatus } from "@/lib/api/code-health";
import { useFileBreakdown } from "./use-file-breakdown";
export function HealthFileDrawerHost({
@@ -13,6 +16,9 @@ export function HealthFileDrawerHost({
onClose: () => void;
}) {
const { data, isLoading } = useFileBreakdown(repoId, filePath);
+ const prefix = `/repos/${repoId}`;
+ const filePageHref = filePath ? fileEntityPath(prefix, filePath) : undefined;
+
return (
<HealthFileDrawer
open={filePath !== null}
@@ -30,13 +36,25 @@ export function HealthFileDrawerHost({
}
findings={data?.findings ?? []}
suggestions={data?.suggestions ?? {}}
- fileViewHref={filePath ? `/repos/${repoId}/files?path=${encodeURIComponent(filePath)}` : undefined}
+ permalinkHref={filePageHref ? `${filePageHref}?tab=health` : undefined}
+ fileViewHref={filePageHref}
fileViewHrefFor={
- filePath
- ? (line: number) =>
- `/repos/${repoId}/files?path=${encodeURIComponent(filePath)}#L${line}`
- : undefined
+ filePageHref ? () => `${filePageHref}?tab=health` : undefined
}
+ onPartnerHref={(path) => fileEntityPath(prefix, path)}
+ onFindingStatusChange={async (findingId, status) => {
+ try {
+ await updateFindingStatus(
+ repoId,
+ findingId,
+ status as Parameters<typeof updateFindingStatus>[2],
+ );
+ toast.success(`Finding marked ${status.replace("_", " ")}`);
+ } catch (err) {
+ toast.error("Couldn't update finding status");
+ throw err;
+ }
+ }}
/>
);
}
diff --git a/packages/web/src/components/health/health-page-chrome.tsx b/packages/web/src/components/health/health-page-chrome.tsx
deleted file mode 100644
index 517e85ba5..000000000
--- a/packages/web/src/components/health/health-page-chrome.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-"use client";
-
-import Link from "next/link";
-import {
- HealthPageChrome as BaseHealthPageChrome,
- type HealthPageChromeProps as BaseHealthPageChromeProps,
-} from "@repowise-dev/ui/health";
-
-export type HealthPageChromeProps = Omit<BaseHealthPageChromeProps, "renderLink">;
-
-/** Web binding for the shared `HealthPageChrome` — injects Next's `<Link>`
- * so health-tab navigation is client-routed instead of hard-reloading. */
-export function HealthPageChrome(props: HealthPageChromeProps) {
- return (
- <BaseHealthPageChrome
- {...props}
- renderLink={({ href, label, active, icon, key }) => (
- <Link
- key={key}
- href={href}
- className={
- "inline-flex items-center gap-1.5 px-3 py-2 text-sm font-medium border-b-2 transition-colors " +
- (active
- ? "border-emerald-500 text-[var(--color-text-primary)]"
- : "border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-default)]")
- }
- >
- {icon}
- {label}
- </Link>
- )}
- />
- );
-}
diff --git a/packages/web/src/components/health/health-risks-panel.tsx b/packages/web/src/components/health/health-risks-panel.tsx
index 31d75d458..4ae766484 100644
--- a/packages/web/src/components/health/health-risks-panel.tsx
+++ b/packages/web/src/components/health/health-risks-panel.tsx
@@ -37,7 +37,7 @@ export function HealthRisksPanel({
{title}
</span>
<Link
- href={`/repos/${repoId}/health`}
+ href={`/repos/${repoId}/code-health`}
className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
>
See all →
diff --git a/packages/web/src/components/jobs/live-job-progress.tsx b/packages/web/src/components/jobs/live-job-progress.tsx
new file mode 100644
index 000000000..9c274e489
--- /dev/null
+++ b/packages/web/src/components/jobs/live-job-progress.tsx
@@ -0,0 +1,38 @@
+"use client";
+
+import { useJob } from "@/lib/hooks/use-job";
+
+/**
+ * Live progress text for a running/pending generation job. Subscribes to the
+ * job's SSE stream so dashboard rows tick without a page refresh; falls back
+ * to the server-rendered snapshot until the first event arrives.
+ */
+export function LiveJobProgress({
+ jobId,
+ initialCompleted,
+ initialTotal,
+}: {
+ jobId: string;
+ initialCompleted: number;
+ initialTotal: number;
+}) {
+ const { job, sse } = useJob(jobId);
+ const completed =
+ sse.data?.completed_pages ?? job?.completed_pages ?? initialCompleted;
+ const total = sse.data?.total_pages ?? job?.total_pages ?? initialTotal;
+ const pct = total > 0 ? Math.round((completed / total) * 100) : 0;
+
+ return (
+ <span className="inline-flex items-center gap-2 text-[var(--color-accent-primary)]">
+ <span className="tabular-nums">
+ {completed}/{total} pages
+ </span>
+ <span className="h-1 w-16 overflow-hidden rounded-full bg-[var(--color-bg-inset)]">
+ <span
+ className="block h-full rounded-full bg-[var(--color-accent-primary)] transition-[width] duration-500"
+ style={{ width: `${pct}%` }}
+ />
+ </span>
+ </span>
+ );
+}
diff --git a/packages/web/src/components/layout/mobile-nav.tsx b/packages/web/src/components/layout/mobile-nav.tsx
index ad700fa6c..763422698 100644
--- a/packages/web/src/components/layout/mobile-nav.tsx
+++ b/packages/web/src/components/layout/mobile-nav.tsx
@@ -6,27 +6,10 @@ import { usePathname } from "next/navigation";
import { BrandLogo } from "./brand-logo";
import {
Menu,
- Activity,
- BookOpen,
- LayoutDashboard,
- Lightbulb,
- MessageSquare,
- Settings,
Search,
- GitBranch,
- Code2,
- Users,
- Flame,
- GitCommitHorizontal,
- Trash2,
- Radar,
ChevronDown,
ChevronRight,
Circle,
- SlidersHorizontal,
- Layers,
- Link2,
- GitMerge,
} from "lucide-react";
import { Button } from "@repowise-dev/ui/ui/button";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@repowise-dev/ui/ui/sheet";
@@ -34,37 +17,14 @@ import { ScrollArea } from "@repowise-dev/ui/ui/scroll-area";
import { Separator } from "@repowise-dev/ui/ui/separator";
import { AddRepoDialog } from "@/components/repos/add-repo-dialog";
import { cn } from "@/lib/utils/cn";
+import {
+ GLOBAL_NAV,
+ WORKSPACE_NAV,
+ repoNavGroups,
+ isNavItemActive,
+} from "./nav-items";
import type { RepoResponse, WorkspaceResponse } from "@/lib/api/types";
-const GLOBAL_NAV = [
- { label: "Dashboard", href: "/", icon: LayoutDashboard },
- { label: "Settings", href: "/settings", icon: Settings },
-];
-
-function repoNavItems(repoId: string) {
- return [
- { label: "Overview", href: `/repos/${repoId}/overview`, icon: Activity },
- { label: "Chat", href: `/repos/${repoId}`, icon: MessageSquare, exact: true },
- { label: "Wiki", href: `/repos/${repoId}/docs`, icon: BookOpen },
- { label: "Search", href: `/repos/${repoId}/search`, icon: Search },
- { label: "Graph", href: `/repos/${repoId}/graph`, icon: GitBranch },
- { label: "Symbols", href: `/repos/${repoId}/symbols`, icon: Code2 },
- { label: "Ownership", href: `/repos/${repoId}/ownership`, icon: Users },
- { label: "Hotspots", href: `/repos/${repoId}/hotspots`, icon: Flame },
- { label: "Commits", href: `/repos/${repoId}/commits`, icon: GitCommitHorizontal },
- { label: "Dead Code", href: `/repos/${repoId}/dead-code`, icon: Trash2 },
- { label: "Blast Radius", href: `/repos/${repoId}/blast-radius`, icon: Radar },
- { label: "Decisions", href: `/repos/${repoId}/decisions`, icon: Lightbulb },
- { label: "Settings", href: `/repos/${repoId}/settings`, icon: SlidersHorizontal },
- ];
-}
-
-const WORKSPACE_NAV = [
- { label: "Overview", href: "/workspace", icon: Layers, exact: true as const },
- { label: "Contracts", href: "/workspace/contracts", icon: Link2 },
- { label: "Co-Changes", href: "/workspace/co-changes", icon: GitMerge },
-];
-
interface MobileNavProps {
repos?: RepoResponse[];
workspace?: WorkspaceResponse | null;
@@ -207,7 +167,7 @@ export function MobileNav({ repos = [], workspace }: MobileNavProps) {
<div className="space-y-0.5">
{repos.map((repo) => {
const isExpanded = expandedRepos.has(repo.id);
- const navItems = repoNavItems(repo.id);
+ const navGroups = repoNavGroups(repo.id);
return (
<div key={repo.id}>
<button
@@ -227,27 +187,36 @@ export function MobileNav({ repos = [], workspace }: MobileNavProps) {
</button>
{isExpanded && (
<div className="ml-3.5 mt-0.5 space-y-0.5 border-l border-[var(--color-border-default)] pl-3">
- {navItems.map((item) => {
- const Icon = item.icon;
- const isActive = (item as { exact?: boolean }).exact
- ? pathname === item.href
- : pathname === item.href || pathname.startsWith(`${item.href}/`);
- return (
- <Link
- key={item.href}
- href={item.href}
- className={cn(
- "flex items-center gap-2.5 rounded-lg px-2 py-1.5 text-[13px] transition-colors",
- isActive
- ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"
- : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]",
- )}
- >
- <Icon className="h-4 w-4 shrink-0" />
- {item.label}
- </Link>
- );
- })}
+ {navGroups.map((group, gi) => (
+ <React.Fragment key={group.label ?? gi}>
+ {group.label ? (
+ <p className="px-2 pt-2 pb-0.5 text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ {group.label}
+ </p>
+ ) : gi > 0 ? (
+ <div className="pt-1.5" />
+ ) : null}
+ {group.items.map((item) => {
+ const Icon = item.icon;
+ const isActive = isNavItemActive(item, pathname);
+ return (
+ <Link
+ key={item.href}
+ href={item.href}
+ className={cn(
+ "flex items-center gap-2.5 rounded-lg px-2 py-1.5 text-[13px] transition-colors",
+ isActive
+ ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]"
+ : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]",
+ )}
+ >
+ <Icon className="h-4 w-4 shrink-0" />
+ {item.label}
+ </Link>
+ );
+ })}
+ </React.Fragment>
+ ))}
</div>
)}
</div>
diff --git a/packages/web/src/components/layout/nav-items.ts b/packages/web/src/components/layout/nav-items.ts
new file mode 100644
index 000000000..fa6229e33
--- /dev/null
+++ b/packages/web/src/components/layout/nav-items.ts
@@ -0,0 +1,90 @@
+/**
+ * Single source of truth for app navigation. Both the desktop sidebar and
+ * the mobile nav consume these — the two surfaces must never diverge again.
+ *
+ * Repo IA (6 groups + Settings pinned last):
+ * Overview · Docs · Architecture · Code Health · People & History · Chat
+ */
+
+import {
+ Activity,
+ BookOpen,
+ Boxes,
+ DollarSign,
+ GitCommitHorizontal,
+ GitMerge,
+ HeartPulse,
+ LayoutDashboard,
+ Layers,
+ Lightbulb,
+ Link2,
+ MessageSquare,
+ Settings,
+ Users,
+} from "lucide-react";
+
+export interface NavItem {
+ label: string;
+ href: string;
+ icon: React.ComponentType<{ className?: string }>;
+ exact?: boolean;
+}
+
+export interface NavGroup {
+ /** Optional section label rendered above the items. */
+ label?: string;
+ items: NavItem[];
+}
+
+export const GLOBAL_NAV: NavItem[] = [
+ { label: "Dashboard", href: "/", icon: LayoutDashboard },
+ { label: "Settings", href: "/settings", icon: Settings },
+];
+
+export const WORKSPACE_NAV: NavItem[] = [
+ { label: "Overview", href: "/workspace", icon: Layers, exact: true },
+ { label: "Contracts", href: "/workspace/contracts", icon: Link2 },
+ { label: "Co-Changes", href: "/workspace/co-changes", icon: GitMerge },
+];
+
+export function repoNavGroups(repoId: string): NavGroup[] {
+ const base = `/repos/${repoId}`;
+ return [
+ {
+ items: [
+ { label: "Overview", href: `${base}/overview`, icon: Activity },
+ { label: "Docs", href: `${base}/docs`, icon: BookOpen },
+ { label: "Architecture", href: `${base}/architecture`, icon: Boxes },
+ { label: "Code Health", href: `${base}/code-health`, icon: HeartPulse },
+ ],
+ },
+ {
+ label: "People & History",
+ items: [
+ { label: "Commits", href: `${base}/commits`, icon: GitCommitHorizontal },
+ { label: "Contributors", href: `${base}/owners`, icon: Users },
+ { label: "Decisions", href: `${base}/decisions`, icon: Lightbulb },
+ ],
+ },
+ {
+ items: [{ label: "Chat", href: `${base}/chat`, icon: MessageSquare }],
+ },
+ {
+ label: "Settings",
+ items: [
+ { label: "Usage & savings", href: `${base}/costs`, icon: DollarSign },
+ { label: "Settings", href: `${base}/settings`, icon: Settings },
+ ],
+ },
+ ];
+}
+
+/** Flat repo nav list (command palette, breadcrumb fallbacks, …). */
+export function repoNavItems(repoId: string): NavItem[] {
+ return repoNavGroups(repoId).flatMap((g) => g.items);
+}
+
+export function isNavItemActive(item: NavItem, pathname: string): boolean {
+ if (item.exact) return pathname === item.href;
+ return pathname === item.href || pathname.startsWith(`${item.href}/`);
+}
diff --git a/packages/web/src/components/layout/repo-breadcrumb-label.ts b/packages/web/src/components/layout/repo-breadcrumb-label.ts
index 55f795ee6..0ca83be6d 100644
--- a/packages/web/src/components/layout/repo-breadcrumb-label.ts
+++ b/packages/web/src/components/layout/repo-breadcrumb-label.ts
@@ -1,7 +1,12 @@
const SEGMENT_LABELS: Record<string, string> = {
overview: "Overview",
docs: "Docs",
+ chat: "Chat",
+ architecture: "Architecture",
+ "code-health": "Code Health",
coverage: "Coverage",
+ "refactoring-targets": "Refactoring Targets",
+ trend: "Trend",
search: "Search",
graph: "Graph",
symbols: "Symbols",
@@ -10,11 +15,17 @@ const SEGMENT_LABELS: Record<string, string> = {
"dead-code": "Dead Code",
"blast-radius": "Blast Radius",
decisions: "Decisions",
- costs: "Costs",
+ commits: "Commits",
+ owners: "Contributors",
+ modules: "Modules",
+ wiki: "Wiki",
+ health: "Code Health",
+ costs: "Usage & Savings",
risk: "Risk",
security: "Security",
settings: "Settings",
c4: "Knowledge Graph",
+ files: "Files",
};
export function getRepoBreadcrumbSegmentLabel(segment: string): string {
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index efbf93f7d..89955c384 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -5,29 +5,20 @@ import Link from "next/link";
import { usePathname } from "next/navigation";
import { BrandLogo } from "./brand-logo";
import {
- LayoutDashboard,
- Activity,
- BookOpen,
- GitBranch,
- Lightbulb,
- MessageSquare,
- Code2,
- ShieldAlert,
- GitCommitHorizontal,
- DollarSign,
- Settings,
ChevronDown,
ChevronRight,
Circle,
PanelLeft,
- Layers,
- Link2,
- GitMerge,
- Users,
- Boxes,
- HeartPulse,
+ Search,
} from "lucide-react";
import { cn } from "@/lib/utils/cn";
+import {
+ GLOBAL_NAV,
+ WORKSPACE_NAV,
+ repoNavGroups,
+ isNavItemActive,
+ type NavItem,
+} from "./nav-items";
import { ScrollArea } from "@repowise-dev/ui/ui/scroll-area";
import { Separator } from "@repowise-dev/ui/ui/separator";
import { Tooltip, TooltipContent, TooltipTrigger } from "@repowise-dev/ui/ui/tooltip";
@@ -35,43 +26,6 @@ import { ThemeToggle } from "@repowise-dev/ui/shared/theme-toggle";
import { AddRepoDialog } from "@/components/repos/add-repo-dialog";
import type { RepoResponse, WorkspaceResponse } from "@/lib/api/types";
-interface NavItem {
- label: string;
- href: string;
- icon: React.ComponentType<{ className?: string }>;
- exact?: boolean;
-}
-
-const GLOBAL_NAV: NavItem[] = [
- { label: "Dashboard", href: "/", icon: LayoutDashboard },
- { label: "Settings", href: "/settings", icon: Settings },
-];
-
-const WORKSPACE_NAV: NavItem[] = [
- { label: "Overview", href: "/workspace", icon: Layers, exact: true },
- { label: "Contracts", href: "/workspace/contracts", icon: Link2 },
- { label: "Co-Changes", href: "/workspace/co-changes", icon: GitMerge },
-];
-
-
-function repoNavItems(repoId: string): NavItem[] {
- return [
- { label: "Overview", href: `/repos/${repoId}/overview`, icon: Activity },
- { label: "Chat", href: `/repos/${repoId}`, icon: MessageSquare, exact: true },
- { label: "Wiki", href: `/repos/${repoId}/docs`, icon: BookOpen },
- { label: "Risk", href: `/repos/${repoId}/risk`, icon: ShieldAlert },
- { label: "Commits", href: `/repos/${repoId}/commits`, icon: GitCommitHorizontal },
- { label: "Health", href: `/repos/${repoId}/health`, icon: HeartPulse, exact: true },
- { label: "Graph", href: `/repos/${repoId}/graph`, icon: GitBranch },
- { label: "Knowledge Graph", href: `/repos/${repoId}/c4`, icon: Boxes },
- { label: "Symbols", href: `/repos/${repoId}/symbols`, icon: Code2 },
- { label: "Contributors", href: `/repos/${repoId}/owners`, icon: Users },
- { label: "Decisions", href: `/repos/${repoId}/decisions`, icon: Lightbulb },
- { label: "Costs", href: `/repos/${repoId}/costs`, icon: DollarSign },
- { label: "Settings", href: `/repos/${repoId}/settings`, icon: Settings },
- ];
-}
-
interface SidebarProps {
repos?: RepoResponse[];
activeRepoId?: string;
@@ -177,6 +131,7 @@ export function Sidebar({ repos = [], activeRepoId, workspace }: SidebarProps) {
iconOnly={isIconOnly}
/>
))}
+ <SidebarSearchButton iconOnly={isIconOnly} />
</nav>
{/* Workspace nav — only shown in workspace mode */}
@@ -219,7 +174,7 @@ export function Sidebar({ repos = [], activeRepoId, workspace }: SidebarProps) {
{repos.map((repo) => {
const isExpanded = expandedRepos.has(repo.id);
const isActive = derivedActiveRepoId === repo.id;
- const navItems = repoNavItems(repo.id);
+ const navGroups = repoNavGroups(repo.id);
const needsIndex =
repo.workspace_status === "needs_index" ||
repo.id.startsWith("ws:");
@@ -317,14 +272,25 @@ export function Sidebar({ repos = [], activeRepoId, workspace }: SidebarProps) {
</button>
{isExpanded && (
<div id={`sidebar-repo-${repo.id}`} className="ml-3.5 mt-0.5 space-y-0.5 border-l border-[var(--color-border-default)] pl-3">
- {navItems.map((item) => (
- <SidebarNavItem
- key={item.href}
- item={item}
- isActive={item.exact ? pathname === item.href : (pathname === item.href || pathname.startsWith(`${item.href}/`))}
- size="sm"
- iconOnly={false}
- />
+ {navGroups.map((group, gi) => (
+ <React.Fragment key={group.label ?? gi}>
+ {group.label ? (
+ <p className="px-2 pt-2 pb-0.5 text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ {group.label}
+ </p>
+ ) : gi > 0 ? (
+ <div className="pt-1.5" />
+ ) : null}
+ {group.items.map((item) => (
+ <SidebarNavItem
+ key={item.href}
+ item={item}
+ isActive={isNavItemActive(item, pathname)}
+ size="sm"
+ iconOnly={false}
+ />
+ ))}
+ </React.Fragment>
))}
</div>
)}
@@ -365,6 +331,41 @@ export function Sidebar({ repos = [], activeRepoId, workspace }: SidebarProps) {
);
}
+function SidebarSearchButton({ iconOnly }: { iconOnly: boolean }) {
+ const openPalette = () =>
+ window.dispatchEvent(new CustomEvent("repowise:open-command-palette"));
+
+ if (iconOnly) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ onClick={openPalette}
+ aria-label="Search"
+ className="flex w-full items-center justify-center rounded-lg p-2.5 text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ >
+ <Search className="h-[18px] w-[18px] shrink-0" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="right">Search</TooltipContent>
+ </Tooltip>
+ );
+ }
+
+ return (
+ <button
+ onClick={openPalette}
+ className="flex w-full items-center gap-2.5 rounded-lg px-2 py-2 text-sm text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ >
+ <Search className="h-[18px] w-[18px] shrink-0" />
+ <span className="flex-1 truncate text-left">Search</span>
+ <kbd className="rounded border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-[10px] text-[var(--color-text-tertiary)]">
+ ⌘K
+ </kbd>
+ </button>
+ );
+}
+
function SidebarNavItem({
item,
isActive,
diff --git a/packages/web/src/components/layout/themed-toaster.tsx b/packages/web/src/components/layout/themed-toaster.tsx
index b74f741b5..2c72abc18 100644
--- a/packages/web/src/components/layout/themed-toaster.tsx
+++ b/packages/web/src/components/layout/themed-toaster.tsx
@@ -1,30 +1,16 @@
"use client";
/**
- * ThemedToaster — Sonner toaster that follows the active next-themes theme.
- *
- * The root layout is a server component, so the Toaster's `theme` prop can't
- * read `useTheme` there. This thin client wrapper bridges them: it passes the
- * resolved theme (light/dark, falling back to system) so toasts match the
- * themed surfaces in either mode.
+ * ThemedToaster — shared token-themed toaster that follows the active
+ * next-themes theme. The root layout is a server component, so this thin
+ * client wrapper bridges `useTheme` to the presentational Toaster in
+ * packages/ui.
*/
import { useTheme } from "next-themes";
-import { Toaster } from "sonner";
+import { Toaster } from "@repowise-dev/ui/shared";
export function ThemedToaster() {
const { resolvedTheme } = useTheme();
- return (
- <Toaster
- theme={resolvedTheme === "light" ? "light" : "dark"}
- position="bottom-right"
- toastOptions={{
- style: {
- background: "var(--color-bg-elevated)",
- border: "1px solid var(--color-border-default)",
- color: "var(--color-text-primary)",
- },
- }}
- />
- );
+ return <Toaster theme={resolvedTheme === "light" ? "light" : "dark"} />;
}
diff --git a/packages/web/src/components/overview/overview-tabs.tsx b/packages/web/src/components/overview/overview-tabs.tsx
new file mode 100644
index 000000000..dc70981e9
--- /dev/null
+++ b/packages/web/src/components/overview/overview-tabs.tsx
@@ -0,0 +1,52 @@
+"use client";
+
+import { parseAsStringLiteral, useQueryState } from "nuqs";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@repowise-dev/ui/ui/tabs";
+import { ErrorBoundary } from "@repowise-dev/ui/shared";
+import { PulseTab } from "./pulse-tab";
+import { StructureTab } from "./structure-tab";
+import type { Hotspot } from "@repowise-dev/types/git";
+import type { OverviewDecisionSlim } from "@repowise-dev/types/overview";
+
+const TAB_VALUES = ["pulse", "structure"] as const;
+
+interface OverviewTabsProps {
+ repoId: string;
+ hotspots: Hotspot[];
+ hotspotTotal: number;
+ decisions: OverviewDecisionSlim[];
+}
+
+/** Two purposeful, URL-synced tabs: Pulse (activity) and Structure (how
+ * it's built). Tab content fetches its own data and streams in behind
+ * skeletons; the summary slices arrive as props from the server payload. */
+export function OverviewTabs({ repoId, hotspots, hotspotTotal, decisions }: OverviewTabsProps) {
+ const [tab, setTab] = useQueryState(
+ "tab",
+ parseAsStringLiteral(TAB_VALUES).withDefault("pulse"),
+ );
+
+ return (
+ <Tabs value={tab} onValueChange={(v) => setTab(v as (typeof TAB_VALUES)[number])}>
+ <TabsList>
+ <TabsTrigger value="pulse">Pulse</TabsTrigger>
+ <TabsTrigger value="structure">Structure</TabsTrigger>
+ </TabsList>
+ <TabsContent value="pulse" className="mt-4">
+ <ErrorBoundary title="Couldn't load activity">
+ <PulseTab
+ repoId={repoId}
+ hotspots={hotspots}
+ hotspotTotal={hotspotTotal}
+ decisions={decisions}
+ />
+ </ErrorBoundary>
+ </TabsContent>
+ <TabsContent value="structure" className="mt-4">
+ <ErrorBoundary title="Couldn't load structure">
+ <StructureTab repoId={repoId} />
+ </ErrorBoundary>
+ </TabsContent>
+ </Tabs>
+ );
+}
diff --git a/packages/web/src/components/overview/pulse-tab.tsx b/packages/web/src/components/overview/pulse-tab.tsx
new file mode 100644
index 000000000..40016f76b
--- /dev/null
+++ b/packages/web/src/components/overview/pulse-tab.tsx
@@ -0,0 +1,76 @@
+"use client";
+
+import useSWR from "swr";
+import { CommitsMini } from "@repowise-dev/ui/dashboard/commits-mini";
+import { DecisionsTimeline } from "@repowise-dev/ui/dashboard/decisions-timeline";
+import { HotspotsMini } from "@repowise-dev/ui/dashboard/hotspots-mini";
+import { CommitCategorySparkline } from "@repowise-dev/ui/git/commit-category-sparkline";
+import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+import { getCommitsPage } from "@/lib/api/git";
+import type { Hotspot } from "@repowise-dev/types/git";
+import type { OverviewDecisionSlim } from "@repowise-dev/types/overview";
+
+interface PulseTabProps {
+ repoId: string;
+ hotspots: Hotspot[];
+ hotspotTotal: number;
+ decisions: OverviewDecisionSlim[];
+}
+
+/** Default Overview tab: real activity — recent commits, change pressure,
+ * and the decisions timeline. Commits stream in client-side; the hotspot
+ * and decision slices arrive with the summary payload. */
+export function PulseTab({ repoId, hotspots, hotspotTotal, decisions }: PulseTabProps) {
+ const { data: commitsPage, isLoading } = useSWR(
+ `overview-commits:${repoId}`,
+ () => getCommitsPage(repoId, { sort: "date", limit: 10 }),
+ { revalidateOnFocus: false, revalidateOnReconnect: false },
+ );
+
+ const aggregatedCategories: Record<string, number> = {};
+ for (const h of hotspots) {
+ for (const [cat, count] of Object.entries(h.commit_categories ?? {})) {
+ aggregatedCategories[cat] = (aggregatedCategories[cat] || 0) + count;
+ }
+ }
+ const hasCategories = Object.values(aggregatedCategories).some((v) => v > 0);
+
+ return (
+ <div className="space-y-4">
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ {isLoading ? (
+ <Card>
+ <CardContent className="space-y-2 pt-4">
+ {Array.from({ length: 6 }).map((_, i) => (
+ <Skeleton key={i} className="h-5 w-full" />
+ ))}
+ </CardContent>
+ </Card>
+ ) : (
+ <CommitsMini commits={commitsPage?.items ?? []} repoId={repoId} />
+ )}
+ <DecisionsTimeline decisions={decisions} repoId={repoId} />
+ </div>
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <HotspotsMini hotspots={hotspots} repoId={repoId} total={hotspotTotal} />
+ {hasCategories && (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">Commit Activity</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <CommitCategorySparkline categories={aggregatedCategories} />
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 mt-2 text-[10px] text-[var(--color-text-tertiary)]">
+ <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "var(--color-info)" }} /> Feature</span>
+ <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "var(--color-error)" }} /> Fix</span>
+ <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "var(--color-accent-secondary)" }} /> Refactor</span>
+ <span className="flex items-center gap-1"><span className="inline-block h-2 w-2 rounded-sm" style={{ background: "var(--color-accent-fill)" }} /> Dependency</span>
+ </div>
+ </CardContent>
+ </Card>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/overview/structure-tab.tsx b/packages/web/src/components/overview/structure-tab.tsx
new file mode 100644
index 000000000..533182f14
--- /dev/null
+++ b/packages/web/src/components/overview/structure-tab.tsx
@@ -0,0 +1,124 @@
+"use client";
+
+import useSWR from "swr";
+import { DependencyHeatmap } from "@repowise-dev/ui/dashboard/dependency-heatmap";
+import { ModuleOverviewGrid } from "@repowise-dev/ui/dashboard/module-overview-grid";
+import { OwnershipTreemap } from "@repowise-dev/ui/dashboard/ownership-treemap";
+import { ExecutionFlowsPanel } from "@repowise-dev/ui/dashboard/execution-flows-panel";
+import { BusFactorPanel } from "@repowise-dev/ui/git/bus-factor-panel";
+import { EmptyState } from "@repowise-dev/ui/shared";
+import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
+import { CommunitySummaryGridWrapper } from "@/components/dashboard/community-summary-grid-wrapper";
+import { useCommunities, useExecutionFlows, useModuleGraph } from "@/lib/hooks/use-graph";
+import { getHotspotsPage, getOwnership } from "@/lib/api/git";
+
+const SWR_OPTS = { revalidateOnFocus: false, revalidateOnReconnect: false };
+
+function PanelSkeleton({ rows = 6 }: { rows?: number }) {
+ return (
+ <Card>
+ <CardContent className="space-y-2 pt-4">
+ {Array.from({ length: rows }).map((_, i) => (
+ <Skeleton key={i} className="h-5 w-full" />
+ ))}
+ </CardContent>
+ </Card>
+ );
+}
+
+interface StructureTabProps {
+ repoId: string;
+}
+
+/** "How is this built" — module map, dependency heatmap, communities,
+ * execution flows, plus ownership treemap and bus factor fed by the full
+ * ownership/hotspot datasets (not the summary slice). */
+export function StructureTab({ repoId }: StructureTabProps) {
+ const { graph: moduleGraph, isLoading: modulesLoading } = useModuleGraph(repoId);
+ const { communities, isLoading: communitiesLoading } = useCommunities(repoId);
+ const { flows, isLoading: flowsLoading } = useExecutionFlows(repoId, {
+ top_n: 5,
+ max_depth: 5,
+ });
+ const { data: ownership, isLoading: ownershipLoading } = useSWR(
+ `overview-ownership:${repoId}`,
+ () => getOwnership(repoId, "module"),
+ SWR_OPTS,
+ );
+ const { data: hotspotsPage, isLoading: hotspotsLoading } = useSWR(
+ `overview-hotspots:${repoId}`,
+ () => getHotspotsPage(repoId, { limit: 50 }),
+ SWR_OPTS,
+ );
+
+ const hasModules = !!moduleGraph && moduleGraph.nodes.length > 0;
+
+ return (
+ <div className="space-y-4">
+ {modulesLoading ? (
+ <PanelSkeleton rows={4} />
+ ) : hasModules ? (
+ <ModuleOverviewGrid nodes={moduleGraph.nodes} edges={moduleGraph.edges} repoId={repoId} />
+ ) : (
+ <EmptyState
+ title="No module graph yet"
+ description="Module structure appears once indexing completes. Run repowise update to refresh."
+ />
+ )}
+
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
+ {modulesLoading ? (
+ <PanelSkeleton />
+ ) : hasModules ? (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">Module Dependencies</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <DependencyHeatmap moduleGraph={moduleGraph} />
+ </CardContent>
+ </Card>
+ ) : null}
+ {communitiesLoading ? (
+ <PanelSkeleton />
+ ) : communities && communities.length > 0 ? (
+ <CommunitySummaryGridWrapper communities={communities} repoId={repoId} />
+ ) : null}
+ </div>
+
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
+ {flowsLoading ? (
+ <PanelSkeleton />
+ ) : flows && flows.flows.length > 0 ? (
+ <ExecutionFlowsPanel flows={flows.flows} repoId={repoId} />
+ ) : null}
+ {hotspotsLoading ? (
+ <PanelSkeleton />
+ ) : hotspotsPage && hotspotsPage.items.length > 0 ? (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">Bus Factor</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <BusFactorPanel hotspots={hotspotsPage.items} />
+ </CardContent>
+ </Card>
+ ) : null}
+ </div>
+
+ {ownershipLoading ? (
+ <PanelSkeleton rows={8} />
+ ) : ownership && ownership.length > 0 ? (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">Ownership Map</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <OwnershipTreemap entries={ownership} />
+ </CardContent>
+ </Card>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/web/src/components/repos/coordinator-health-panel.tsx b/packages/web/src/components/repos/coordinator-health-panel.tsx
index 68de2cc7c..b44a12e5f 100644
--- a/packages/web/src/components/repos/coordinator-health-panel.tsx
+++ b/packages/web/src/components/repos/coordinator-health-panel.tsx
@@ -16,10 +16,15 @@ const STATUS_BADGE: Record<CoordinatorHealth["status"], string> = {
critical: "bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400",
};
-function StatRow({ label, value }: { label: string; value: string }) {
+function StatRow({ label, value, help }: { label: string; value: string; help?: string }) {
return (
<div className="flex items-center justify-between py-1.5 border-b border-[var(--color-border)] last:border-0">
- <span className="text-xs text-[var(--color-text-secondary)]">{label}</span>
+ <span
+ className={`text-xs text-[var(--color-text-secondary)] ${help ? "cursor-help underline decoration-dotted decoration-[var(--color-border-default)] underline-offset-2" : ""}`}
+ title={help}
+ >
+ {label}
+ </span>
<span className="text-xs font-medium text-[var(--color-text-primary)]">{value}</span>
</div>
);
@@ -61,7 +66,11 @@ export function CoordinatorHealthPanel({ repoId, initial }: Props) {
<StatRow label="SQL Pages" value={fmt(data.sql_pages)} />
<StatRow label="Vector Count" value={fmt(data.vector_count)} />
<StatRow label="Graph Nodes" value={fmt(data.graph_nodes)} />
- <StatRow label="Drift" value={fmtPct(data.drift_pct)} />
+ <StatRow
+ label="Drift"
+ value={fmtPct(data.drift_pct)}
+ help="How far the SQL, vector and graph stores disagree about what's indexed. 0% means all three are in sync; high drift usually means an interrupted index — run a sync to reconcile."
+ />
</>
) : (
<p className="text-xs text-[var(--color-text-secondary)]">
diff --git a/packages/web/src/components/risk/dead-code-tab.tsx b/packages/web/src/components/risk/dead-code-tab.tsx
index 9a2484b5e..c5e24506e 100644
--- a/packages/web/src/components/risk/dead-code-tab.tsx
+++ b/packages/web/src/components/risk/dead-code-tab.tsx
@@ -1,8 +1,10 @@
"use client";
import { useState } from "react";
+import { useRouter } from "next/navigation";
import useSWR from "swr";
import { toast } from "sonner";
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
import { Button } from "@repowise-dev/ui/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
@@ -15,6 +17,7 @@ import { getDeadCodeSummary, listDeadCode, analyzeDeadCode } from "@/lib/api/dea
import type { DeadCodeFindingResponse, DeadCodeSummaryResponse } from "@/lib/api/types";
export function DeadCodeTab({ repoId }: { repoId: string }) {
+ const router = useRouter();
const [analyzing, setAnalyzing] = useState(false);
const { data: summary, isLoading: loadingSummary, error: summaryError, mutate: mutateSummary } =
@@ -35,6 +38,41 @@ export function DeadCodeTab({ repoId }: { repoId: string }) {
const findingsList = findings ?? [];
const safeFindings = findingsList.filter((f) => f.safe_to_delete);
+ // "Propose cleanup" builds an agent-ready brief from the safe pile and
+ // copies it — the cheapest path from finding to action until a server-side
+ // cleanup-PR flow exists.
+ const handlePropose = async (findingIds: string[]) => {
+ const selected = safeFindings.filter((f) => findingIds.includes(f.id));
+ const byFile = new Map<string, typeof selected>();
+ for (const f of selected) {
+ byFile.set(f.file_path, [...(byFile.get(f.file_path) ?? []), f]);
+ }
+ const lines = [...byFile.entries()].map(([path, fs]) => {
+ const symbols = fs
+ .map((f) => f.symbol_name)
+ .filter(Boolean)
+ .join(", ");
+ return `- ${path}${symbols ? ` (${symbols})` : ""} — ${fs
+ .map((f) => f.reason)
+ .filter(Boolean)
+ .slice(0, 1)
+ .join("")}`;
+ });
+ const brief = [
+ "Remove the following dead code. Each entry was flagged high-confidence",
+ "safe-to-delete by repowise's dead-code analysis. Verify with a project",
+ "search before deleting, then run the test suite.",
+ "",
+ ...lines,
+ ].join("\n");
+ try {
+ await navigator.clipboard.writeText(brief);
+ toast.success(`Cleanup brief for ${byFile.size} files copied — paste it to your agent`);
+ } catch {
+ toast.error("Couldn't copy to clipboard");
+ }
+ };
+
const handleAnalyze = async () => {
setAnalyzing(true);
try {
@@ -75,7 +113,12 @@ export function DeadCodeTab({ repoId }: { repoId: string }) {
) : null}
{findings && safeFindings.length > 0 && (
- <SafeToDeletePile findings={safeFindings} reclaimableLines={summary?.deletable_lines} />
+ <SafeToDeletePile
+ findings={safeFindings}
+ reclaimableLines={summary?.deletable_lines}
+ onPropose={handlePropose}
+ onSelect={(f) => router.push(fileEntityPath(`/repos/${repoId}`, f.file_path))}
+ />
)}
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
diff --git a/packages/web/src/components/risk/heatmap-tab.tsx b/packages/web/src/components/risk/heatmap-tab.tsx
deleted file mode 100644
index a92870a64..000000000
--- a/packages/web/src/components/risk/heatmap-tab.tsx
+++ /dev/null
@@ -1,163 +0,0 @@
-"use client";
-
-import { useMemo, useState } from "react";
-import { useRouter } from "next/navigation";
-import useSWR from "swr";
-import { OwnershipTreemap } from "@repowise-dev/ui/git/ownership-treemap";
-import { listModuleHealth } from "@/lib/api/modules";
-import type { ModuleHealthSummary } from "@/lib/api/types";
-import { BusFactorPanel } from "@repowise-dev/ui/git/bus-factor-panel";
-import { ContributorBar } from "@repowise-dev/ui/git/contributor-bar";
-import { HotspotTrendStrip } from "@repowise-dev/ui/git/hotspot-trend-strip";
-import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
-import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
-import { getOwnership, getGitSummary, getHotspots } from "@/lib/api/git";
-import { formatNumber } from "@repowise-dev/ui/lib/format";
-import { cn } from "@/lib/utils/cn";
-import type { OwnershipEntry, GitSummaryResponse, HotspotResponse } from "@/lib/api/types";
-
-type Granularity = "module" | "file";
-
-export function HeatmapTab({ repoId }: { repoId: string }) {
- const router = useRouter();
- const [granularity, setGranularity] = useState<Granularity>("module");
-
- const { data: entries, isLoading: loadingEntries } = useSWR<OwnershipEntry[]>(
- `ownership:${repoId}:${granularity}`,
- () => getOwnership(repoId, granularity),
- { revalidateOnFocus: false },
- );
- const { data: summary } = useSWR<GitSummaryResponse>(
- `git-summary:${repoId}`,
- () => getGitSummary(repoId),
- { revalidateOnFocus: false },
- );
- const { data: hotspots } = useSWR<HotspotResponse[]>(
- `hotspots-for-ownership:${repoId}`,
- () => getHotspots(repoId, 100),
- { revalidateOnFocus: false },
- );
- // Module-level bus-factor overlay for the treemap. Only needed at module
- // granularity — file mode uses its own per-row bus factor in tooltips.
- const { data: moduleHealth } = useSWR(
- granularity === "module" ? `module-health:${repoId}:all` : null,
- () => listModuleHealth(repoId, { sort: "file_count", limit: 500 }),
- { revalidateOnFocus: false },
- );
-
- const busFactorByModule = useMemo(() => {
- const map: Record<string, number> = {};
- for (const m of (moduleHealth?.items ?? []) as ModuleHealthSummary[]) {
- map[m.module_path] = Math.round(m.median_bus_factor);
- }
- return map;
- }, [moduleHealth]);
-
- const list = entries ?? [];
-
- return (
- <div className="space-y-6">
- {loadingEntries && list.length === 0 ? (
- <Skeleton className="h-72 w-full" />
- ) : list.length > 0 ? (
- <Card>
- <CardHeader className="pb-2">
- <div className="flex items-center justify-between">
- <CardTitle className="text-sm">Ownership Heatmap</CardTitle>
- <div className="flex rounded-md border border-[var(--color-border-default)] overflow-hidden text-xs">
- {(["module", "file"] as Granularity[]).map((g) => (
- <button
- key={g}
- onClick={() => setGranularity(g)}
- className={cn(
- "px-3 py-1.5 font-medium transition-colors capitalize",
- granularity === g
- ? "bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)]"
- : "bg-transparent text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]",
- )}
- >
- {g}
- </button>
- ))}
- </div>
- </div>
- <p className="text-xs text-[var(--color-text-tertiary)] pt-1">
- Tile size = code volume. Color = primary owner. Border = bus factor —
- red ≤1, amber 2, green ≥3. Dashed amber outline marks silo modules
- (one owner &gt;80%).
- </p>
- </CardHeader>
- <CardContent className="pt-0">
- <OwnershipTreemap
- entries={list}
- busFactorByModule={granularity === "module" ? busFactorByModule : undefined}
- onSelect={(e) =>
- router.push(
- `/repos/${repoId}/modules/${encodeURIComponent(e.module_path)}`,
- )
- }
- />
- </CardContent>
- </Card>
- ) : null}
-
- {hotspots && hotspots.length > 0 && (
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">Hotspot trend</CardTitle>
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Top files by churn. Heating arrows mark files where the last 30 days are
- outpacing the 90-day baseline.
- </p>
- </CardHeader>
- <CardContent className="pt-0">
- <HotspotTrendStrip hotspots={hotspots} />
- </CardContent>
- </Card>
- )}
-
- <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
- {hotspots && hotspots.length > 0 && (
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">Bus Factor Analysis</CardTitle>
- </CardHeader>
- <CardContent className="pt-0">
- <BusFactorPanel hotspots={hotspots} />
- </CardContent>
- </Card>
- )}
-
- {summary && summary.top_owners.length > 0 && (
- <Card>
- <CardHeader className="pb-2">
- <CardTitle className="text-sm">Top Contributors</CardTitle>
- </CardHeader>
- <CardContent className="pt-0">
- <ContributorBar owners={summary.top_owners} />
- <div className="mt-3 space-y-1.5">
- {summary.top_owners.slice(0, 10).map((o, i) => {
- const key = o.email ?? `name:${o.name}`;
- return (
- <button
- key={o.email || `owner-${i}`}
- onClick={() =>
- router.push(`/repos/${repoId}/owners/${encodeURIComponent(key)}`)
- }
- className="flex w-full items-center justify-between rounded-md px-2 py-1 text-xs hover:bg-[var(--color-bg-elevated)]"
- >
- <span className="text-[var(--color-text-secondary)] truncate text-left">{o.name}</span>
- <span className="text-[var(--color-text-tertiary)] tabular-nums ml-2">
- {Math.round((o.pct ?? 0) * 100)}%
- </span>
- </button>
- );
- })}
- </div>
- </CardContent>
- </Card>
- )}
- </div>
- </div>
- );
-}
diff --git a/packages/web/src/components/risk/hotspots-tab.tsx b/packages/web/src/components/risk/hotspots-tab.tsx
index 66cf99634..8cf391fa7 100644
--- a/packages/web/src/components/risk/hotspots-tab.tsx
+++ b/packages/web/src/components/risk/hotspots-tab.tsx
@@ -8,6 +8,7 @@ import { SymbolDrawerWrapper } from "@/components/symbols/symbol-drawer-wrapper"
import type { HotspotResponse as HotspotRowType, Paginated, SymbolResponse } from "@/lib/api/types";
import type { FileCardData } from "@repowise-dev/ui/shared/file-card";
import { HotspotTable } from "@repowise-dev/ui/git/hotspot-table";
+import { HotspotTrendStrip } from "@repowise-dev/ui/git/hotspot-trend-strip";
import { ChurnHistogram } from "@repowise-dev/ui/git/churn-histogram";
import { CommitCategoryDonut } from "@repowise-dev/ui/git/commit-category-donut";
import { RiskDistributionChart } from "@repowise-dev/ui/git/risk-distribution-chart";
@@ -136,7 +137,21 @@ export function HotspotsTab({ repoId }: { repoId: string }) {
</div>
)}
- {/* Top contributors lives on the Heatmap tab; not duplicated here. */}
+ {list.length > 0 && (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm">Hotspot trend</CardTitle>
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Top files by churn. Heating arrows mark files where the last 30 days are
+ outpacing the 90-day baseline.
+ </p>
+ </CardHeader>
+ <CardContent className="pt-0">
+ <HotspotTrendStrip hotspots={list} />
+ </CardContent>
+ </Card>
+ )}
+
<HotspotTable
hotspots={list}
repoId={repoId}
diff --git a/packages/web/src/components/risk/impact-tab.tsx b/packages/web/src/components/risk/impact-tab.tsx
index a9e8653a5..51c3f82e1 100644
--- a/packages/web/src/components/risk/impact-tab.tsx
+++ b/packages/web/src/components/risk/impact-tab.tsx
@@ -1,53 +1,65 @@
"use client";
-import { useState } from "react";
+import { useEffect, useRef, useState } from "react";
import useSWR from "swr";
-import { Plus, Flame } from "lucide-react";
+import { Plus, Flame, X } from "lucide-react";
import { Button } from "@repowise-dev/ui/ui/button";
import { Card, CardHeader, CardTitle, CardContent } from "@repowise-dev/ui/ui/card";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
import { BlastRadiusResults } from "@repowise-dev/ui/blast-radius";
+import { ReviewerSuggestions } from "@repowise-dev/ui/git/reviewer-suggestions";
import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";
+import type { ReviewerSuggestion } from "@repowise-dev/types/modules";
import { analyzeBlastRadius } from "@/lib/api/blast-radius";
-import { getHotspots } from "@/lib/api/git";
+import { getHotspots, getReviewerSuggestions } from "@/lib/api/git";
+import { searchNodes } from "@/lib/api/graph";
export function ImpactTab({ repoId }: { repoId: string }) {
- const [files, setFiles] = useState("");
+ const [selected, setSelected] = useState<string[]>([]);
const [maxDepth, setMaxDepth] = useState(3);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [result, setResult] = useState<BlastRadiusResponse | null>(null);
+ const [reviewers, setReviewers] = useState<ReviewerSuggestion[] | null>(null);
const { data: hotspotSuggestions, isLoading: hotspotSuggestionsLoading } = useSWR(
repoId ? ["blast-radius-suggestions", repoId] : null,
() => getHotspots(repoId, 8),
);
- const addSuggestion = (path: string) => {
- setFiles((prev) => {
- const lines = prev.split("\n").map((l) => l.trim()).filter(Boolean);
- if (lines.includes(path)) return prev;
- return [...lines, path].join("\n");
+ const addPaths = (paths: string[]) => {
+ setSelected((prev) => {
+ const set = new Set(prev);
+ for (const p of paths) {
+ const trimmed = p.trim();
+ if (trimmed) set.add(trimmed);
+ }
+ return [...set];
});
};
+ const removePath = (path: string) =>
+ setSelected((prev) => prev.filter((p) => p !== path));
const useAllHotspots = () => {
if (!hotspotSuggestions) return;
- setFiles(hotspotSuggestions.map((h) => h.file_path).join("\n"));
+ addPaths(hotspotSuggestions.map((h) => h.file_path));
};
- const clearFiles = () => setFiles("");
const handleAnalyze = async () => {
- const changed = files.split("\n").map((l) => l.trim()).filter(Boolean);
- if (changed.length === 0) {
- setError("Enter at least one file path.");
+ if (selected.length === 0) {
+ setError("Add at least one file path.");
return;
}
setLoading(true);
setError(null);
setResult(null);
+ setReviewers(null);
try {
- const data = await analyzeBlastRadius(repoId, { changed_files: changed, max_depth: maxDepth });
+ const [data, suggestions] = await Promise.all([
+ analyzeBlastRadius(repoId, { changed_files: selected, max_depth: maxDepth }),
+ getReviewerSuggestions(repoId, selected, 8).catch(() => null),
+ ]);
setResult(data);
+ setReviewers(suggestions?.suggestions ?? null);
} catch (err) {
setError(err instanceof Error ? err.message : "Analysis failed.");
} finally {
@@ -67,15 +79,15 @@ export function ImpactTab({ repoId }: { repoId: string }) {
</CardHeader>
<CardContent className="pt-0 space-y-4">
<p className="text-xs text-[var(--color-text-tertiary)]">
- Paste file paths (one per line) — typically your PR diff. Or click a hotspot below to
- prefill, or use{" "}
+ Type to search the file index, paste a list of paths (your PR diff),
+ click a hotspot below, or{" "}
<button
type="button"
onClick={useAllHotspots}
className="underline underline-offset-2 hover:text-[var(--color-text-primary)]"
disabled={!hotspotSuggestions || hotspotSuggestions.length === 0}
>
- Use top hotspots
+ use top hotspots
</button>
.
</p>
@@ -94,7 +106,7 @@ export function ImpactTab({ repoId }: { repoId: string }) {
<button
key={h.file_path}
type="button"
- onClick={() => addSuggestion(h.file_path)}
+ onClick={() => addPaths([h.file_path])}
className="inline-flex items-center gap-1 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2.5 py-1 text-[11px] font-mono text-[var(--color-text-secondary)] hover:border-[var(--color-accent-primary)] hover:text-[var(--color-text-primary)] transition-colors"
title={h.file_path}
aria-label={`Add ${h.file_path} to changed files`}
@@ -107,17 +119,8 @@ export function ImpactTab({ repoId }: { repoId: string }) {
</div>
)}
- <label htmlFor="risk-impact-changed-files" className="sr-only">
- Changed file paths, one per line
- </label>
- <textarea
- id="risk-impact-changed-files"
- className="w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3 py-2 text-xs font-mono text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] focus:outline-none focus:ring-1 focus:ring-[var(--color-accent-primary)] resize-y min-h-[120px]"
- placeholder={"src/auth/login.py\nsrc/models/user.py\n..."}
- value={files}
- onChange={(e) => setFiles(e.target.value)}
- aria-label="Changed file paths, one per line"
- />
+ <FilePathPicker repoId={repoId} selected={selected} onAdd={addPaths} onRemove={removePath} />
+
<div className="flex items-center gap-4 flex-wrap">
<label className="flex items-center gap-2 text-xs text-[var(--color-text-secondary)]">
Max depth
@@ -134,17 +137,200 @@ export function ImpactTab({ repoId }: { repoId: string }) {
<Button onClick={handleAnalyze} disabled={loading} size="sm">
{loading ? "Analyzing…" : "Analyze"}
</Button>
- {files && (
- <Button onClick={clearFiles} disabled={loading} size="sm" variant="outline">
+ {selected.length > 0 && (
+ <Button onClick={() => setSelected([])} disabled={loading} size="sm" variant="outline">
Clear
</Button>
)}
</div>
- {error && <p className="text-xs text-red-500">{error}</p>}
+ {error && <p className="text-xs text-[var(--color-error)]">{error}</p>}
</CardContent>
</Card>
- {result && <BlastRadiusResults result={result} />}
+ {result && (
+ <BlastRadiusResults
+ result={result}
+ reviewersSlot={
+ reviewers && reviewers.length > 0 ? (
+ <ReviewerSuggestions
+ suggestions={reviewers}
+ subtitle={`Based on authorship and co-change history for ${selected.length} changed paths`}
+ />
+ ) : undefined
+ }
+ />
+ )}
+ </div>
+ );
+}
+
+/**
+ * Chips + typeahead input over the repo's file index (graph node search).
+ * Pasting a multi-line / comma-separated list adds every path at once.
+ */
+function FilePathPicker({
+ repoId,
+ selected,
+ onAdd,
+ onRemove,
+}: {
+ repoId: string;
+ selected: string[];
+ onAdd: (paths: string[]) => void;
+ onRemove: (path: string) => void;
+}) {
+ const [query, setQuery] = useState("");
+ const [suggestions, setSuggestions] = useState<string[]>([]);
+ const [openList, setOpenList] = useState(false);
+ const [activeIndex, setActiveIndex] = useState(-1);
+ const containerRef = useRef<HTMLDivElement>(null);
+
+ // Debounced typeahead over the graph node index.
+ useEffect(() => {
+ if (!query.trim()) {
+ setSuggestions([]);
+ setOpenList(false);
+ return;
+ }
+ let cancelled = false;
+ const t = window.setTimeout(async () => {
+ try {
+ const results = await searchNodes(repoId, query.trim(), 8);
+ if (cancelled) return;
+ const paths = results
+ .map((r) => r.node_id)
+ .filter((p) => !selected.includes(p));
+ setSuggestions(paths);
+ setOpenList(paths.length > 0);
+ setActiveIndex(-1);
+ } catch {
+ if (!cancelled) setSuggestions([]);
+ }
+ }, 200);
+ return () => {
+ cancelled = true;
+ window.clearTimeout(t);
+ };
+ }, [query, repoId, selected]);
+
+ // Close the list when clicking outside.
+ useEffect(() => {
+ const handler = (e: MouseEvent) => {
+ if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
+ setOpenList(false);
+ }
+ };
+ document.addEventListener("mousedown", handler);
+ return () => document.removeEventListener("mousedown", handler);
+ }, []);
+
+ const commit = (path: string) => {
+ onAdd([path]);
+ setQuery("");
+ setSuggestions([]);
+ setOpenList(false);
+ };
+
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === "ArrowDown" && suggestions.length > 0) {
+ e.preventDefault();
+ setOpenList(true);
+ setActiveIndex((i) => (i + 1) % suggestions.length);
+ } else if (e.key === "ArrowUp" && suggestions.length > 0) {
+ e.preventDefault();
+ setActiveIndex((i) => (i <= 0 ? suggestions.length - 1 : i - 1));
+ } else if (e.key === "Enter") {
+ e.preventDefault();
+ if (openList && activeIndex >= 0 && suggestions[activeIndex]) {
+ commit(suggestions[activeIndex]);
+ } else if (query.trim()) {
+ commit(query.trim());
+ }
+ } else if (e.key === "Escape") {
+ setOpenList(false);
+ } else if (e.key === "Backspace" && !query && selected.length > 0) {
+ onRemove(selected[selected.length - 1]!);
+ }
+ };
+
+ const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
+ const text = e.clipboardData.getData("text");
+ if (/[\n,]/.test(text)) {
+ e.preventDefault();
+ onAdd(text.split(/[\n,]+/));
+ setQuery("");
+ }
+ };
+
+ return (
+ <div ref={containerRef} className="relative">
+ <div
+ className="flex flex-wrap items-center gap-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1.5 focus-within:ring-1 focus-within:ring-[var(--color-accent-primary)]"
+ onClick={() => containerRef.current?.querySelector("input")?.focus()}
+ >
+ {selected.map((p) => (
+ <span
+ key={p}
+ className="inline-flex items-center gap-1 rounded border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-1.5 py-0.5 text-[11px] font-mono text-[var(--color-text-primary)]"
+ title={p}
+ >
+ <span className="truncate max-w-[280px]">{p}</span>
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ onRemove(p);
+ }}
+ aria-label={`Remove ${p}`}
+ className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </span>
+ ))}
+ <input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ onKeyDown={handleKeyDown}
+ onPaste={handlePaste}
+ onFocus={() => suggestions.length > 0 && setOpenList(true)}
+ placeholder={selected.length === 0 ? "src/auth/login.py — type to search, paste a list, Enter to add" : "Add another…"}
+ aria-label="Changed file paths"
+ role="combobox"
+ aria-expanded={openList}
+ aria-controls="impact-file-suggestions"
+ aria-autocomplete="list"
+ className="min-w-[180px] flex-1 bg-transparent px-1 py-0.5 text-xs font-mono text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] focus:outline-none"
+ />
+ </div>
+ {openList && suggestions.length > 0 ? (
+ <ul
+ id="impact-file-suggestions"
+ role="listbox"
+ className="absolute z-20 mt-1 w-full max-h-56 overflow-y-auto rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] py-1 shadow-lg"
+ >
+ {suggestions.map((s, i) => (
+ <li key={s} role="option" aria-selected={i === activeIndex}>
+ <button
+ type="button"
+ onMouseDown={(e) => {
+ e.preventDefault();
+ commit(s);
+ }}
+ onMouseEnter={() => setActiveIndex(i)}
+ className={`block w-full truncate px-3 py-1.5 text-left text-xs font-mono ${
+ i === activeIndex
+ ? "bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)]"
+ : "text-[var(--color-text-secondary)]"
+ }`}
+ title={s}
+ >
+ {s}
+ </button>
+ </li>
+ ))}
+ </ul>
+ ) : null}
</div>
);
}
diff --git a/packages/web/src/components/risk/risk-summary-strip.tsx b/packages/web/src/components/risk/risk-summary-strip.tsx
index 7fb865a25..197289f08 100644
--- a/packages/web/src/components/risk/risk-summary-strip.tsx
+++ b/packages/web/src/components/risk/risk-summary-strip.tsx
@@ -9,7 +9,7 @@ import { getDeadCodeSummary } from "@/lib/api/dead-code";
import { getDecisionHealth } from "@/lib/api/decisions";
import { listSecurityFindings } from "@/lib/api/security";
-const RISK_BASE = (repoId: string) => `/repos/${repoId}/risk`;
+const RISK_BASE = (repoId: string) => `/repos/${repoId}/code-health`;
/**
* Always-visible 5-card strip atop /repos/[id]/risk. Pulls cached SWR data
@@ -58,7 +58,7 @@ export function RiskSummaryStrip({ repoId }: { repoId: string }) {
value={formatNumber(siloCount)}
description="single-owner modules"
icon={<Users className="h-4 w-4 text-amber-400" />}
- href={`${RISK_BASE(repoId)}?tab=heatmap`}
+ href={`/repos/${repoId}/owners`}
/>
<StatCard
label="Reclaimable"
@@ -83,7 +83,7 @@ export function RiskSummaryStrip({ repoId }: { repoId: string }) {
: "scan not run"
}
icon={<ShieldAlert className="h-4 w-4 text-red-400" />}
- href={`/repos/${repoId}/security`}
+ href={`${RISK_BASE(repoId)}?tab=security`}
/>
</div>
);
diff --git a/packages/web/src/components/risk/routed-to-risk-banner.tsx b/packages/web/src/components/risk/routed-to-risk-banner.tsx
index cee62c98e..b6dab572b 100644
--- a/packages/web/src/components/risk/routed-to-risk-banner.tsx
+++ b/packages/web/src/components/risk/routed-to-risk-banner.tsx
@@ -25,7 +25,7 @@ const TAB_TITLE: Record<RoutedToRiskBannerProps["tab"], string> = {
* keeps deep links + bookmarks working while the IA migration is rolled out.
*/
export function RoutedToRiskBanner({ repoId, tab, tabLabel }: RoutedToRiskBannerProps) {
- const target = `/repos/${repoId}/risk?tab=${tab}`;
+ const target = `/repos/${repoId}/code-health?tab=${tab}`;
const label = tabLabel ?? TAB_TITLE[tab];
return (
<div className="flex flex-wrap items-center gap-2 rounded-lg border border-[var(--color-accent-primary)]/30 bg-[var(--color-accent-primary)]/8 px-3 py-2 text-xs text-[var(--color-text-secondary)]">
diff --git a/packages/web/src/components/risk/security-tab.tsx b/packages/web/src/components/risk/security-tab.tsx
index b4b9422f9..fc25308c6 100644
--- a/packages/web/src/components/risk/security-tab.tsx
+++ b/packages/web/src/components/risk/security-tab.tsx
@@ -1,13 +1,17 @@
"use client";
-import { useMemo } from "react";
+import { useMemo, useState } from "react";
import useSWR from "swr";
+import { RotateCw } from "lucide-react";
+import { toast } from "sonner";
import { SeverityDistribution } from "@repowise-dev/ui/security/severity-distribution";
import { SecurityFindingsTable } from "@repowise-dev/ui/security/findings-table";
import { FindingsByDirectory } from "@repowise-dev/ui/security/findings-by-directory";
+import { Button } from "@repowise-dev/ui/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
import { listSecurityFindings, type SecurityFinding } from "@/lib/api/security";
+import { syncRepo } from "@/lib/api/repos";
import { useFileCardHost } from "@/components/shared/file-card-host";
import type { FileCardData } from "@repowise-dev/ui/shared/file-card";
@@ -17,6 +21,19 @@ export function SecurityTab({ repoId }: { repoId: string }) {
() => listSecurityFindings(repoId, { limit: 500 }),
{ revalidateOnFocus: false },
);
+ const [rescanning, setRescanning] = useState(false);
+
+ const handleRescan = async () => {
+ setRescanning(true);
+ try {
+ await syncRepo(repoId);
+ toast.success("Sync started — findings refresh when it completes");
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Couldn't start a sync");
+ } finally {
+ setRescanning(false);
+ }
+ };
const { showFile, dialog } = useFileCardHost(repoId);
@@ -44,9 +61,16 @@ export function SecurityTab({ repoId }: { repoId: string }) {
return (
<div className="space-y-6">
- <p className="text-sm text-[var(--color-text-secondary)]">
- Findings detected during ingestion — secrets, dangerous patterns, and policy hits.
- </p>
+ <div className="flex flex-wrap items-center gap-2">
+ <p className="text-sm text-[var(--color-text-secondary)] mr-auto">
+ Secrets, dangerous patterns, and policy hits detected while indexing.
+ Findings refresh on every sync.
+ </p>
+ <Button size="sm" variant="outline" onClick={handleRescan} disabled={rescanning}>
+ <RotateCw className={`h-3.5 w-3.5 mr-1.5 ${rescanning ? "animate-spin" : ""}`} />
+ Re-scan
+ </Button>
+ </div>
{isLoading ? (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
diff --git a/packages/web/src/components/search/command-palette.tsx b/packages/web/src/components/search/command-palette.tsx
index 78e21cba0..35caaa78a 100644
--- a/packages/web/src/components/search/command-palette.tsx
+++ b/packages/web/src/components/search/command-palette.tsx
@@ -1,11 +1,13 @@
"use client";
-import { useEffect, useState, useCallback } from "react";
-import { useRouter } from "next/navigation";
+import { useEffect, useState, useCallback, useMemo } from "react";
+import { usePathname, useRouter } from "next/navigation";
import { Command } from "cmdk";
-import { Search, LayoutDashboard, Settings, BookOpen, Layers, Link2, GitMerge } from "lucide-react";
+import { Search, LayoutDashboard, Settings, BookOpen, Layers, Link2, GitMerge, MessageSquare } from "lucide-react";
import { useSearch } from "@/lib/hooks/use-search";
import { truncatePath } from "@repowise-dev/ui/lib/format";
+import { repoNavItems } from "@/components/layout/nav-items";
+import { pageHref } from "@/lib/utils/page-href";
import type { RepoResponse, WorkspaceResponse } from "@/lib/api/types";
interface CommandPaletteProps {
@@ -18,9 +20,22 @@ export function CommandPalette({ repos, workspace }: CommandPaletteProps) {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const router = useRouter();
+ const pathname = usePathname();
const { results, isLoading } = useSearch(query, { limit: 8 });
+ // Active repo: from the URL when inside one, else the only repo.
+ const activeRepo = useMemo(() => {
+ const m = pathname?.match(/^\/repos\/([^/]+)/);
+ const fromPath = m ? repos.find((r) => r.id === m[1]) : undefined;
+ return fromPath ?? (repos.length === 1 ? repos[0] : undefined);
+ }, [pathname, repos]);
+
+ const repoPages = useMemo(
+ () => (activeRepo ? repoNavItems(activeRepo.id) : []),
+ [activeRepo],
+ );
+
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key === "k") {
@@ -76,6 +91,54 @@ export function CommandPalette({ repos, workspace }: CommandPaletteProps) {
{isLoading ? "Searching…" : "No results found."}
</Command.Empty>
+ {/* Quick-ask — always available when a repo is in scope */}
+ {activeRepo && (
+ <Command.Group heading="Ask" className="px-2 pb-1">
+ <Command.Item
+ value={`ask-repowise ${query}`}
+ onSelect={() =>
+ navigate(
+ query.trim()
+ ? `/repos/${activeRepo.id}/chat?q=${encodeURIComponent(query.trim())}`
+ : `/repos/${activeRepo.id}/chat`,
+ )
+ }
+ className="flex items-center gap-2.5 rounded-md px-3 py-2 text-sm text-[var(--color-text-secondary)] cursor-pointer hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] data-[selected=true]:bg-[var(--color-bg-elevated)] data-[selected=true]:text-[var(--color-text-primary)]"
+ >
+ <MessageSquare className="h-4 w-4 text-[var(--color-accent-primary)]" />
+ <span className="truncate">
+ {query.trim() ? (
+ <>
+ Ask repowise: <span className="text-[var(--color-text-primary)]">“{query.trim()}”</span>
+ </>
+ ) : (
+ "Ask repowise…"
+ )}
+ </span>
+ </Command.Item>
+ </Command.Group>
+ )}
+
+ {/* Per-repo page navigation */}
+ {activeRepo && repoPages.length > 0 && (
+ <Command.Group heading={`Go to — ${activeRepo.name}`} className="px-2 pb-1">
+ {repoPages.map((item) => {
+ const Icon = item.icon;
+ return (
+ <Command.Item
+ key={item.href}
+ value={`goto ${activeRepo.name} ${item.label}`}
+ onSelect={() => navigate(item.href)}
+ className="flex items-center gap-2.5 rounded-md px-3 py-2 text-sm text-[var(--color-text-secondary)] cursor-pointer hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] data-[selected=true]:bg-[var(--color-bg-elevated)] data-[selected=true]:text-[var(--color-text-primary)]"
+ >
+ <Icon className="h-4 w-4" />
+ {item.label}
+ </Command.Item>
+ );
+ })}
+ </Command.Group>
+ )}
+
{/* Quick navigation */}
<Command.Group
heading="Navigate"
@@ -136,7 +199,7 @@ export function CommandPalette({ repos, workspace }: CommandPaletteProps) {
<Command.Item
key={repo.id}
value={`repo-${repo.name}`}
- onSelect={() => navigate(`/repos/${repo.id}`)}
+ onSelect={() => navigate(`/repos/${repo.id}/overview`)}
className="flex items-center gap-2.5 rounded-md px-3 py-2 text-sm text-[var(--color-text-secondary)] cursor-pointer hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] data-[selected=true]:bg-[var(--color-bg-elevated)] data-[selected=true]:text-[var(--color-text-primary)]"
>
<BookOpen className="h-4 w-4" />
@@ -154,10 +217,11 @@ export function CommandPalette({ repos, workspace }: CommandPaletteProps) {
key={r.page_id}
value={`page-${r.title}`}
onSelect={() => {
- // Use first available repo as context for the wiki route.
- // The repo ID is only used for supplemental data (git panel, breadcrumb).
- const fallbackRepoId = repos[0]?.id ?? "";
- navigate(`/repos/${fallbackRepoId}/wiki/${encodeURIComponent(r.page_id)}`);
+ // Prefer the active repo for context; fall back to the
+ // first one. File pages open their canonical entity page,
+ // everything else opens inside the docs SPA.
+ const repoId = activeRepo?.id ?? repos[0]?.id ?? "";
+ navigate(pageHref(repoId, r.page_id));
}}
className="flex flex-col items-start rounded-md px-3 py-2 text-sm cursor-pointer hover:bg-[var(--color-bg-elevated)] data-[selected=true]:bg-[var(--color-bg-elevated)]"
>
diff --git a/packages/web/src/components/search/search-result-card.tsx b/packages/web/src/components/search/search-result-card.tsx
index 2b0df6a92..96980b5cf 100644
--- a/packages/web/src/components/search/search-result-card.tsx
+++ b/packages/web/src/components/search/search-result-card.tsx
@@ -3,6 +3,7 @@ import { Badge } from "@repowise-dev/ui/ui/badge";
import { truncatePath } from "@repowise-dev/ui/lib/format";
import { getPageTypeLabel } from "@repowise-dev/ui/lib/page-types";
import { cn } from "@/lib/utils/cn";
+import { pageHref } from "@/lib/utils/page-href";
import type { SearchResultResponse } from "@/lib/api/types";
interface SearchResultCardProps {
@@ -30,7 +31,7 @@ function highlightSnippet(snippet: string, query: string): React.ReactNode {
}
export function SearchResultCard({ result, query, repoId }: SearchResultCardProps) {
- const href = `/repos/${repoId}/wiki/${encodeURIComponent(result.page_id)}`;
+ const href = pageHref(repoId, result.page_id);
return (
<Link
diff --git a/packages/web/src/components/settings/webhook-section.tsx b/packages/web/src/components/settings/webhook-section.tsx
index 8de1e3a43..79ec2f35e 100644
--- a/packages/web/src/components/settings/webhook-section.tsx
+++ b/packages/web/src/components/settings/webhook-section.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { Copy, Check } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@repowise-dev/ui/ui/card";
import { Button } from "@repowise-dev/ui/ui/button";
@@ -33,8 +33,24 @@ function CopyField({ label, value }: { label: string; value: string }) {
);
}
+/**
+ * Best-effort server URL for webhook registration: the configured API URL
+ * when set, else the dashboard origin (API requests are proxied through it
+ * via Next rewrites, so webhooks reach the backend the same way).
+ */
+export function resolveWebhookBaseUrl(): string {
+ const configured = process.env.NEXT_PUBLIC_REPOWISE_API_URL;
+ if (configured) return configured.replace(/\/$/, "");
+ if (typeof window !== "undefined") return window.location.origin;
+ return "http://localhost:7337";
+}
+
export function WebhookSection() {
- const serverUrl = "http://your-server:7337";
+ const [serverUrl, setServerUrl] = useState("http://localhost:7337");
+ // Resolved in an effect so SSR and the first client render agree.
+ useEffect(() => {
+ setServerUrl(resolveWebhookBaseUrl());
+ }, []);
return (
<Card>
@@ -47,6 +63,10 @@ export function WebhookSection() {
<CardContent className="space-y-4">
<CopyField label="GitHub Webhook URL" value={`${serverUrl}/api/webhooks/github`} />
<CopyField label="GitLab Webhook URL" value={`${serverUrl}/api/webhooks/gitlab`} />
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ URLs use this dashboard&apos;s server address. If GitHub/GitLab can&apos;t
+ reach it, substitute your server&apos;s public hostname.
+ </p>
<div className="rounded border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-3 space-y-1">
<p className="text-xs font-medium text-[var(--color-text-secondary)]">
diff --git a/packages/web/src/components/shared/file-card-host.tsx b/packages/web/src/components/shared/file-card-host.tsx
index b4d048a09..d08d885d4 100644
--- a/packages/web/src/components/shared/file-card-host.tsx
+++ b/packages/web/src/components/shared/file-card-host.tsx
@@ -22,11 +22,11 @@ export function useFileCardHost(repoId?: string) {
customLinks ??
(repoId
? {
- graph: `/repos/${repoId}/graph?node=${encodeURIComponent(next.file_path)}`,
+ graph: `/repos/${repoId}/architecture?view=graph&node=${encodeURIComponent(next.file_path)}`,
docs: `/repos/${repoId}/docs?file=${encodeURIComponent(next.file_path)}`,
- symbols: `/repos/${repoId}/symbols?q=${encodeURIComponent(next.file_path)}`,
- blastRadius: `/repos/${repoId}/risk?tab=impact&file=${encodeURIComponent(next.file_path)}`,
- deadCode: `/repos/${repoId}/risk?tab=dead-code`,
+ symbols: `/repos/${repoId}/architecture?view=symbols&q=${encodeURIComponent(next.file_path)}`,
+ blastRadius: `/repos/${repoId}/code-health?tab=impact&file=${encodeURIComponent(next.file_path)}`,
+ deadCode: `/repos/${repoId}/code-health?tab=dead-code`,
decisions: `/repos/${repoId}/decisions?file=${encodeURIComponent(next.file_path)}`,
}
: undefined);
diff --git a/packages/web/src/components/symbols/hotspot-top-symbols-host.tsx b/packages/web/src/components/symbols/hotspot-top-symbols-host.tsx
index f85e66986..4167af13c 100644
--- a/packages/web/src/components/symbols/hotspot-top-symbols-host.tsx
+++ b/packages/web/src/components/symbols/hotspot-top-symbols-host.tsx
@@ -30,7 +30,7 @@ export function HotspotTopSymbolsHost({ repoId, filePath, onSelectSymbol }: Prop
{ revalidateOnFocus: false },
);
- const seeAllHref = `/repos/${repoId}/symbols?q=${encodeURIComponent(filePath)}`;
+ const seeAllHref = `/repos/${repoId}/architecture?view=symbols&q=${encodeURIComponent(filePath)}`;
return (
<TopSymbolsRow
diff --git a/packages/web/src/components/symbols/symbol-git-panel-wrapper.tsx b/packages/web/src/components/symbols/symbol-git-panel-wrapper.tsx
index 9f5e6ff2a..ed0fda617 100644
--- a/packages/web/src/components/symbols/symbol-git-panel-wrapper.tsx
+++ b/packages/web/src/components/symbols/symbol-git-panel-wrapper.tsx
@@ -113,7 +113,7 @@ export function SymbolGitPanelWrapper({ symbol, repoId }: Props) {
router.push(`/repos/${repoId}/decisions/${encodeURIComponent(id)}`)
}
onOpenBlastRadius={() =>
- router.push(`/repos/${repoId}/blast-radius?file=${encodeURIComponent(filePath)}`)
+ router.push(`/repos/${repoId}/code-health?tab=impact&file=${encodeURIComponent(filePath)}`)
}
/>
);
diff --git a/packages/web/src/components/symbols/symbol-table-wrapper.tsx b/packages/web/src/components/symbols/symbol-table-wrapper.tsx
index 9e2ed0c49..0baa255f9 100644
--- a/packages/web/src/components/symbols/symbol-table-wrapper.tsx
+++ b/packages/web/src/components/symbols/symbol-table-wrapper.tsx
@@ -1,6 +1,8 @@
"use client";
import { useMemo, useState } from "react";
+import { useSearchParams } from "next/navigation";
+import { X } from "lucide-react";
import useSWRInfinite from "swr/infinite";
import { SymbolTable, type SymbolFilters } from "@repowise-dev/ui/symbols/symbol-table";
import { HotSymbolsBoard, type HotSymbol } from "@repowise-dev/ui/symbols/hot-symbols-board";
@@ -16,6 +18,12 @@ interface Props {
}
export function SymbolTableWrapper({ repoId }: Props) {
+ // `?file=` deep link (graph inspection panel "Symbols" action) scopes the
+ // table to one source file until dismissed.
+ const searchParams = useSearchParams();
+ const [fileFilter, setFileFilter] = useState<string | null>(
+ () => searchParams.get("file"),
+ );
const [filters, setFilters] = useState<SymbolFilters>({
q: "",
kind: "all",
@@ -31,8 +39,8 @@ export function SymbolTableWrapper({ repoId }: Props) {
// The fetch key changes whenever any filter does — SWR will fall back to
// page 0 cleanly without us having to reset infinite state by hand.
const keyPayload = useMemo(
- () => ({ ...filters, q: debouncedQ }),
- [filters, debouncedQ],
+ () => ({ ...filters, q: debouncedQ, file: fileFilter }),
+ [filters, debouncedQ, fileFilter],
);
const { data, size, setSize, isLoading, isValidating } = useSWRInfinite<
@@ -51,6 +59,7 @@ export function SymbolTableWrapper({ repoId }: Props) {
language: keyPayload.language !== "all" ? keyPayload.language : undefined,
visibility:
keyPayload.visibility !== "all" ? keyPayload.visibility : undefined,
+ file_path: keyPayload.file || undefined,
in_hot_files: keyPayload.inHotFiles || undefined,
in_entry_points: keyPayload.inEntryPoints || undefined,
sort: keyPayload.sort,
@@ -84,6 +93,24 @@ export function SymbolTableWrapper({ repoId }: Props) {
return (
<div className="space-y-6">
+ {fileFilter && (
+ <div className="flex items-center gap-2">
+ <span className="inline-flex items-center gap-1.5 rounded-full border border-[var(--color-accent-primary)]/40 bg-[var(--color-accent-muted)] px-2.5 py-1 text-[11px] font-mono text-[var(--color-accent-primary)]">
+ {fileFilter}
+ <button
+ type="button"
+ onClick={() => setFileFilter(null)}
+ aria-label="Clear file filter"
+ className="hover:opacity-70"
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </span>
+ <span className="text-[11px] text-[var(--color-text-tertiary)]">
+ showing symbols in this file only
+ </span>
+ </div>
+ )}
{hotSymbols.length > 0 && (
<HotSymbolsBoard items={hotSymbols} onSelect={setSelected} />
)}
diff --git a/packages/web/src/components/wiki/human-notes.tsx b/packages/web/src/components/wiki/human-notes.tsx
new file mode 100644
index 000000000..cc321d6f6
--- /dev/null
+++ b/packages/web/src/components/wiki/human-notes.tsx
@@ -0,0 +1,120 @@
+"use client";
+
+import { useState } from "react";
+import { toast } from "sonner";
+import { Pencil, StickyNote, X } from "lucide-react";
+import { Button } from "@repowise-dev/ui/ui/button";
+import { updatePageNotes } from "@/lib/api/pages";
+
+/**
+ * Human-curated note pinned above a page's generated content, now editable
+ * in place. Notes survive regeneration server-side.
+ */
+export function HumanNotes({
+ pageId,
+ initialNotes,
+}: {
+ pageId: string;
+ initialNotes: string | null;
+}) {
+ const [notes, setNotes] = useState(initialNotes);
+ const [editing, setEditing] = useState(false);
+ const [draft, setDraft] = useState(initialNotes ?? "");
+ const [saving, setSaving] = useState(false);
+
+ async function save() {
+ setSaving(true);
+ try {
+ const updated = await updatePageNotes(pageId, draft.trim() || null);
+ setNotes(updated.human_notes);
+ setDraft(updated.human_notes ?? "");
+ setEditing(false);
+ toast.success(updated.human_notes ? "Note saved" : "Note removed");
+ } catch (e) {
+ toast.error("Couldn't save note", {
+ description: e instanceof Error ? e.message : undefined,
+ });
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ if (!editing && !notes) {
+ return (
+ <button
+ onClick={() => setEditing(true)}
+ className="mb-5 inline-flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-text-secondary)]"
+ >
+ <StickyNote className="h-3.5 w-3.5" />
+ Add a note for your team — it survives regeneration
+ </button>
+ );
+ }
+
+ return (
+ <div className="mb-5 rounded-lg border border-[var(--color-border-accent)] bg-[var(--color-accent-blue)]/5 px-4 py-3">
+ <div className="mb-1.5 flex items-center gap-1.5">
+ <StickyNote className="h-3.5 w-3.5 text-[var(--color-accent-blue)]" />
+ <span className="text-xs font-medium uppercase tracking-wider text-[var(--color-accent-blue)]">
+ Human Notes
+ </span>
+ {!editing && (
+ <button
+ onClick={() => setEditing(true)}
+ aria-label="Edit note"
+ className="ml-auto text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-text-primary)]"
+ >
+ <Pencil className="h-3 w-3" />
+ </button>
+ )}
+ {editing && (
+ <button
+ onClick={() => {
+ setEditing(false);
+ setDraft(notes ?? "");
+ }}
+ aria-label="Cancel editing"
+ className="ml-auto text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-text-primary)]"
+ >
+ <X className="h-3 w-3" />
+ </button>
+ )}
+ </div>
+ {editing ? (
+ <div className="space-y-2">
+ <textarea
+ value={draft}
+ onChange={(e) => setDraft(e.target.value)}
+ rows={4}
+ autoFocus
+ aria-label="Human note"
+ placeholder="Context the generated docs can't know — gotchas, history, plans…"
+ className="w-full resize-y rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-2 text-sm text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-tertiary)]"
+ />
+ <div className="flex items-center gap-2">
+ <Button size="sm" onClick={() => void save()} disabled={saving}>
+ {saving ? "Saving…" : "Save note"}
+ </Button>
+ {notes && (
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={saving}
+ onClick={() => {
+ setDraft("");
+ void save();
+ }}
+ >
+ Remove note
+ </Button>
+ )}
+ </div>
+ </div>
+ ) : (
+ <p className="whitespace-pre-wrap text-sm leading-relaxed text-[var(--color-text-secondary)]">
+ {notes}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/packages/web/src/components/wiki/regenerate-button.tsx b/packages/web/src/components/wiki/regenerate-button.tsx
index 7642b1a16..52bdf4dab 100644
--- a/packages/web/src/components/wiki/regenerate-button.tsx
+++ b/packages/web/src/components/wiki/regenerate-button.tsx
@@ -2,9 +2,11 @@
import { useState } from "react";
import { toast } from "sonner";
-import { useSWRConfig } from "swr";
+import useSWR, { useSWRConfig } from "swr";
import { RegenerateButton as RegenerateButtonShell } from "@repowise-dev/ui/wiki/regenerate-button";
-import { regeneratePage } from "@/lib/api/pages";
+import { ConfirmDialog } from "@repowise-dev/ui/ui/confirm-dialog";
+import { formatTokens } from "@repowise-dev/ui/lib/format";
+import { getPageById, regeneratePage } from "@/lib/api/pages";
import { GenerationProgressWrapper as GenerationProgress } from "@/components/jobs/generation-progress-wrapper";
interface Props {
@@ -17,8 +19,27 @@ export function RegenerateButtonWrapper({ pageId }: Props) {
const { mutate } = useSWRConfig();
const [loading, setLoading] = useState(false);
const [jobId, setJobId] = useState<string | null>(null);
+ const [confirmOpen, setConfirmOpen] = useState(false);
+
+ // Token history for the cost estimate in the confirm dialog. Same SWR key
+ // the wiki page uses, so this is usually already cached.
+ const { data: page } = useSWR(
+ `/api/pages/lookup?page_id=${pageId}`,
+ () => getPageById(pageId),
+ { revalidateOnFocus: false },
+ );
+
+ const estimate =
+ page && (page.input_tokens > 0 || page.output_tokens > 0)
+ ? `Based on the last generation this will spend roughly ${formatTokens(
+ page.input_tokens,
+ )} input + ${formatTokens(page.output_tokens)} output tokens` +
+ (page.provider_name ? ` on ${page.provider_name}` : "") +
+ "."
+ : "Token cost depends on the page's sources; no previous generation is recorded to estimate from.";
async function handleRegenerate() {
+ setConfirmOpen(false);
setLoading(true);
try {
const result = await regeneratePage(pageId);
@@ -40,12 +61,24 @@ export function RegenerateButtonWrapper({ pageId }: Props) {
}
return (
- <RegenerateButtonShell
- onRegenerate={handleRegenerate}
- isLoading={loading}
- isInProgress={!!jobId}
- onDialogClose={() => setJobId(null)}
- jobSlot={jobId ? <GenerationProgress jobId={jobId} onDone={handleDone} /> : null}
- />
+ <>
+ <RegenerateButtonShell
+ onRegenerate={() => setConfirmOpen(true)}
+ isLoading={loading}
+ isInProgress={!!jobId}
+ onDialogClose={() => setJobId(null)}
+ jobSlot={jobId ? <GenerationProgress jobId={jobId} onDone={handleDone} /> : null}
+ />
+ <ConfirmDialog
+ open={confirmOpen}
+ onOpenChange={setConfirmOpen}
+ title="Regenerate this page?"
+ description={`The current content is archived as a version and replaced. ${estimate}`}
+ confirmLabel="Regenerate"
+ destructive={false}
+ loading={loading}
+ onConfirm={() => void handleRegenerate()}
+ />
+ </>
);
}
diff --git a/packages/web/src/lib/api/code-health.ts b/packages/web/src/lib/api/code-health.ts
index 9d0f60789..26464ea8e 100644
--- a/packages/web/src/lib/api/code-health.ts
+++ b/packages/web/src/lib/api/code-health.ts
@@ -27,6 +27,8 @@ export interface HealthFinding {
reason: string;
details: Record<string, unknown>;
status: string;
+ /** Matching symbol id when the finding names a function; links to the symbol page. */
+ symbol_id?: string | null;
}
export interface HealthModuleRow {
diff --git a/packages/web/src/lib/api/external-systems.ts b/packages/web/src/lib/api/external-systems.ts
new file mode 100644
index 000000000..2adf37d54
--- /dev/null
+++ b/packages/web/src/lib/api/external-systems.ts
@@ -0,0 +1,12 @@
+import type { ExternalSystemsRegistry } from "@repowise-dev/types/external-systems";
+
+import { apiGet } from "./client";
+
+/** Full dependency registry (one row per name + manifest, undeduplicated). */
+export async function getExternalSystems(
+ repoId: string,
+): Promise<ExternalSystemsRegistry> {
+ return apiGet<ExternalSystemsRegistry>(
+ `/api/repos/${repoId}/external-systems`,
+ );
+}
diff --git a/packages/web/src/lib/api/files.ts b/packages/web/src/lib/api/files.ts
new file mode 100644
index 000000000..ba48b1ece
--- /dev/null
+++ b/packages/web/src/lib/api/files.ts
@@ -0,0 +1,25 @@
+import type { FileDetailResponse } from "@repowise-dev/types/files";
+import { apiGet, BASE_URL, buildHeaders } from "./client";
+
+/** Canonical file-detail aggregate for the file entity page. */
+export async function getFileDetail(
+ repoId: string,
+ filePath: string,
+): Promise<FileDetailResponse> {
+ // Encode each segment but keep the slashes — the server route uses a
+ // catch-all path converter.
+ const encoded = filePath.split("/").map(encodeURIComponent).join("/");
+ return apiGet<FileDetailResponse>(`/api/repos/${repoId}/files/${encoded}`);
+}
+
+/** Raw file content from the repo checkout (plain text, not JSON). */
+export async function getFileContent(repoId: string, filePath: string): Promise<string> {
+ const url = new URL(
+ `${BASE_URL}/api/repos/${repoId}/file-content`,
+ typeof window !== "undefined" ? window.location.href : "http://localhost",
+ );
+ url.searchParams.set("file_path", filePath);
+ const res = await fetch(url.toString(), { headers: buildHeaders() });
+ if (!res.ok) throw new Error(`Failed to fetch file content (${res.status})`);
+ return res.text();
+}
diff --git a/packages/web/src/lib/api/git.ts b/packages/web/src/lib/api/git.ts
index 47f0200ca..d7139f777 100644
--- a/packages/web/src/lib/api/git.ts
+++ b/packages/web/src/lib/api/git.ts
@@ -1,5 +1,6 @@
import { apiGet } from "./client";
import type {
+ AgentTrend,
CommitDetailResponse,
CommitResponse,
GitMetadataResponse,
@@ -115,16 +116,27 @@ export async function getGitSummary(
*/
export async function getCommitsPage(
repoId: string,
- options: { sort?: "risk" | "date"; limit?: number; offset?: number } = {},
+ options: {
+ sort?: "risk" | "date";
+ authorship?: "all" | "agent" | "human";
+ limit?: number;
+ offset?: number;
+ } = {},
): Promise<Paginated<CommitResponse>> {
- const { sort = "risk", limit = 50, offset = 0 } = options;
+ const { sort = "risk", authorship = "all", limit = 50, offset = 0 } = options;
return apiGet<Paginated<CommitResponse>>(`/api/repos/${repoId}/commits`, {
sort,
+ authorship,
limit,
offset,
});
}
+/** Monthly agent-vs-human commit volume across the indexed window. */
+export async function getAgentTrend(repoId: string): Promise<AgentTrend> {
+ return apiGet<AgentTrend>(`/api/repos/${repoId}/commits/agent-trend`);
+}
+
export async function getCommit(
repoId: string,
sha: string,
diff --git a/packages/web/src/lib/api/overview.ts b/packages/web/src/lib/api/overview.ts
new file mode 100644
index 000000000..9427c893d
--- /dev/null
+++ b/packages/web/src/lib/api/overview.ts
@@ -0,0 +1,7 @@
+import type { OverviewSummaryResponse } from "@repowise-dev/types/overview";
+import { apiGet } from "./client";
+
+/** One-call Overview payload — replaces the old N-call waterfall. */
+export async function getOverviewSummary(repoId: string): Promise<OverviewSummaryResponse> {
+ return apiGet<OverviewSummaryResponse>(`/api/repos/${repoId}/overview-summary`);
+}
diff --git a/packages/web/src/lib/api/pages.ts b/packages/web/src/lib/api/pages.ts
index ba6a6a9e7..229a61e4a 100644
--- a/packages/web/src/lib/api/pages.ts
+++ b/packages/web/src/lib/api/pages.ts
@@ -1,4 +1,4 @@
-import { apiGet, apiPost } from "./client";
+import { apiGet, apiPatch, apiPost } from "./client";
import type { PageResponse, PageVersionResponse } from "./types";
export async function listPages(
@@ -43,6 +43,17 @@ export async function getPageVersions(
});
}
+/** Set or clear the human-curated note pinned above a page's generated content. */
+export async function updatePageNotes(
+ pageId: string,
+ humanNotes: string | null,
+): Promise<PageResponse> {
+ return apiPatch<PageResponse>(
+ `/api/pages/lookup/notes?page_id=${encodeURIComponent(pageId)}`,
+ { human_notes: humanNotes },
+ );
+}
+
/** Force-regenerate a page by ID */
export async function regeneratePage(pageId: string): Promise<{ job_id: string }> {
return apiPost<{ job_id: string }>("/api/pages/lookup/regenerate", undefined, undefined, { page_id: pageId });
diff --git a/packages/web/src/lib/api/symbols.ts b/packages/web/src/lib/api/symbols.ts
index d061e128f..b6bcc2b0a 100644
--- a/packages/web/src/lib/api/symbols.ts
+++ b/packages/web/src/lib/api/symbols.ts
@@ -1,3 +1,4 @@
+import type { SymbolDetailResponse } from "@repowise-dev/types/symbols";
import { apiGet } from "./client";
import type { Paginated, SymbolResponse } from "./types";
@@ -47,3 +48,14 @@ export async function lookupSymbolByName(
export async function getSymbolById(symbolDbId: string): Promise<SymbolResponse> {
return apiGet<SymbolResponse>(`/api/symbols/${encodeURIComponent(symbolDbId)}`);
}
+
+/** Symbol entity-page aggregate: row + blame + callers/callees + decisions. */
+export async function getSymbolDetail(
+ repoId: string,
+ symbolId: string,
+): Promise<SymbolDetailResponse> {
+ return apiGet<SymbolDetailResponse>("/api/symbols/detail", {
+ repo_id: repoId,
+ symbol_id: symbolId,
+ });
+}
diff --git a/packages/web/src/lib/api/types/decisions.ts b/packages/web/src/lib/api/types/decisions.ts
index 05c4cf789..cbab43310 100644
--- a/packages/web/src/lib/api/types/decisions.ts
+++ b/packages/web/src/lib/api/types/decisions.ts
@@ -27,10 +27,22 @@ export interface DecisionRecordResponse {
verification?: DecisionVerification;
created_at: string;
updated_at: string;
+ /** Evidence rows backing the record. Populated by the list endpoint only. */
+ evidence_count?: number | null;
+ /** Top-ranked evidence row, slimmed. Populated by the list endpoint only. */
+ evidence_preview?: EvidencePreview | null;
}
export type DecisionVerification = "exact" | "fuzzy" | "unverified";
+export interface EvidencePreview {
+ source: string;
+ source_quote: string;
+ verification: DecisionVerification;
+ evidence_file?: string | null;
+ evidence_line?: number | null;
+}
+
export interface DecisionEvidence {
id: string;
source: string;
diff --git a/packages/web/src/lib/api/types/git.ts b/packages/web/src/lib/api/types/git.ts
index b4f4038c2..469a73ff7 100644
--- a/packages/web/src/lib/api/types/git.ts
+++ b/packages/web/src/lib/api/types/git.ts
@@ -107,6 +107,15 @@ export interface CommitResponse {
change_risk_level: ReviewPriority | null;
risk_percentile: number;
review_priority: ReviewPriority;
+ /** Label of the dominant risk driver; null when never risk-scored. */
+ top_driver?: string | null;
+ /** Author's cumulative prior-commit count at commit time. */
+ author_experience?: number | null;
+ /** Coding-agent attribution; null for human-authored commits. */
+ agent_name?: string | null;
+ /** 1 = near-autonomous bot, 2 = human-driven agent, 3 = assisted. */
+ agent_autonomy_tier?: number | null;
+ agent_confidence?: string | null;
}
export interface RiskDriverResponse {
@@ -117,6 +126,22 @@ export interface RiskDriverResponse {
}
export interface CommitDetailResponse extends CommitResponse {
- author_experience?: number | null;
drivers: RiskDriverResponse[];
+ agent_channel?: string | null;
+}
+
+export interface AgentTrendBucket {
+ month: string;
+ total_commits: number;
+ agent_commits: number;
+ agent_pct: number;
+ tier_counts: Record<string, number>;
+}
+
+export interface AgentTrend {
+ buckets: AgentTrendBucket[];
+ total_commits: number;
+ agent_commits: number;
+ agent_pct: number;
+ agent_names: { name: string; count: number }[];
}
diff --git a/packages/web/src/lib/api/types/ownership.ts b/packages/web/src/lib/api/types/ownership.ts
index 227ea6232..b732cf697 100644
--- a/packages/web/src/lib/api/types/ownership.ts
+++ b/packages/web/src/lib/api/types/ownership.ts
@@ -57,8 +57,21 @@ export interface OwnerProfileResponse {
lines_deleted_90d_est: number;
modules: OwnerModuleRollup[];
top_files: OwnerFileEntry[];
+ /** Uncapped count behind the top_files slice (for "+N more"). */
+ files_touched_total?: number;
co_authors: OwnerCoAuthor[];
+ /** Uncapped count behind the co_authors slice (for "+N more"). */
+ co_authors_total?: number;
commit_categories: Record<string, number>;
+ /** Agent activity on owned files; null when nothing attributed. */
+ agent_collab?: OwnerAgentCollab | null;
+}
+
+export interface OwnerAgentCollab {
+ files_with_agent_commits: number;
+ agent_commit_count: number;
+ agent_share_pct: number | null;
+ tier_counts: Record<string, number>;
}
// ---------------------------------------------------------------------------
diff --git a/packages/web/src/lib/utils/page-href.ts b/packages/web/src/lib/utils/page-href.ts
new file mode 100644
index 000000000..c2bba9690
--- /dev/null
+++ b/packages/web/src/lib/utils/page-href.ts
@@ -0,0 +1,15 @@
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
+
+/**
+ * Resolve the best in-app destination for a wiki page id.
+ *
+ * File pages route to the canonical file entity page; everything else opens
+ * inside the docs SPA (`/docs?page=`) instead of the standalone wiki route,
+ * so navigation keeps the tree/reading context.
+ */
+export function pageHref(repoId: string, pageId: string): string {
+ if (pageId.startsWith("file_page:")) {
+ return fileEntityPath(`/repos/${repoId}`, pageId.slice("file_page:".length));
+ }
+ return `/repos/${repoId}/docs?page=${encodeURIComponent(pageId)}`;
+}
diff --git a/tests/unit/server/conftest.py b/tests/unit/server/conftest.py
index 8790334ef..d9533c444 100644
--- a/tests/unit/server/conftest.py
+++ b/tests/unit/server/conftest.py
@@ -32,6 +32,7 @@ def _create_test_app():
costs,
dead_code,
decisions,
+ external_systems,
git,
graph,
health,
@@ -80,6 +81,7 @@ def _create_test_app():
app.include_router(owners.router)
app.include_router(modules.router)
app.include_router(decisions.router)
+ app.include_router(external_systems.router)
return app
diff --git a/tests/unit/server/test_decisions_api.py b/tests/unit/server/test_decisions_api.py
index c14bb0345..41fbf3521 100644
--- a/tests/unit/server/test_decisions_api.py
+++ b/tests/unit/server/test_decisions_api.py
@@ -99,6 +99,33 @@ async def _seed_code_link(session_factory, repo_id: str, decision_id: str) -> No
await session.flush()
+# ---------------------------------------------------------------------------
+# List evidence preview
+# ---------------------------------------------------------------------------
+
+
+async def test_list_carries_evidence_preview(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ decision_id = await _seed_decision(app.state.session_factory, repo["id"])
+ bare_id = await _seed_decision(
+ app.state.session_factory, repo["id"], title="No evidence yet"
+ )
+ await _seed_evidence(app.state.session_factory, decision_id)
+
+ resp = await client.get(f"/api/repos/{repo['id']}/decisions")
+ assert resp.status_code == 200
+ rows = {d["id"]: d for d in resp.json()}
+ rich = rows[decision_id]
+ assert rich["evidence_count"] == 1
+ assert rich["evidence_preview"]["source_quote"] == (
+ "# ADR: Use SQLite for all unit tests."
+ )
+ assert rich["evidence_preview"]["verification"] == "exact"
+ assert rows[bare_id]["evidence_count"] == 0
+ assert rows[bare_id]["evidence_preview"] is None
+
+
# ---------------------------------------------------------------------------
# Evidence endpoint
# ---------------------------------------------------------------------------
diff --git a/tests/unit/server/test_external_systems.py b/tests/unit/server/test_external_systems.py
new file mode 100644
index 000000000..13267818c
--- /dev/null
+++ b/tests/unit/server/test_external_systems.py
@@ -0,0 +1,85 @@
+"""Tests for the /api/repos/{repo_id}/external-systems dependency registry."""
+
+from __future__ import annotations
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import ExternalSystem
+from tests.unit.server.conftest import create_test_repo
+
+
+async def _seed(session_factory, repo_id: str) -> None:
+ async with get_session(session_factory) as session:
+ session.add_all(
+ [
+ ExternalSystem(
+ repository_id=repo_id,
+ name="react",
+ display_name="React",
+ ecosystem="npm",
+ category="framework",
+ version="^19.0.0",
+ declared_in="packages/web/package.json",
+ is_dev_dep=False,
+ ),
+ ExternalSystem(
+ repository_id=repo_id,
+ name="vitest",
+ display_name="Vitest",
+ ecosystem="npm",
+ category="tool",
+ version="^4.1.5",
+ declared_in="packages/ui/package.json",
+ is_dev_dep=True,
+ ),
+ ExternalSystem(
+ repository_id=repo_id,
+ name="fastapi",
+ display_name="FastAPI",
+ ecosystem="pypi",
+ category="framework",
+ version=">=0.110",
+ declared_in="packages/server/pyproject.toml",
+ is_dev_dep=False,
+ ),
+ ]
+ )
+ await session.flush()
+
+
+async def test_registry_lists_all_rows(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ resp = await client.get(f"/api/repos/{repo['id']}/external-systems")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["total"] == 3
+ assert data["prod_count"] == 2
+ assert data["dev_count"] == 1
+ assert data["ecosystems"] == ["npm", "pypi"]
+ assert data["manifests"] == [
+ "packages/server/pyproject.toml",
+ "packages/ui/package.json",
+ "packages/web/package.json",
+ ]
+ # Sorted by category prominence (framework first), then name.
+ assert [e["name"] for e in data["items"]] == ["fastapi", "react", "vitest"]
+ react = data["items"][1]
+ assert react["display_name"] == "React"
+ assert react["version"] == "^19.0.0"
+ assert react["declared_in"] == "packages/web/package.json"
+ assert react["is_dev_dep"] is False
+
+
+async def test_registry_empty(client: AsyncClient) -> None:
+ repo = await create_test_repo(client)
+ resp = await client.get(f"/api/repos/{repo['id']}/external-systems")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["total"] == 0
+ assert data["items"] == []
diff --git a/tests/unit/server/test_git.py b/tests/unit/server/test_git.py
index e3a245ef6..c54423e69 100644
--- a/tests/unit/server/test_git.py
+++ b/tests/unit/server/test_git.py
@@ -237,6 +237,105 @@ async def test_get_commit_not_found(client: AsyncClient) -> None:
assert resp.status_code == 404
+async def _insert_agent_commit(session_factory, repo_id: str) -> None:
+ from datetime import UTC, datetime
+
+ async with get_session(session_factory) as session:
+ await crud.upsert_git_commits_bulk(
+ session,
+ repo_id,
+ [
+ {
+ "sha": "dddddddd44",
+ "author_name": "claude",
+ "author_email": "[email protected]",
+ "committed_at": datetime.fromtimestamp(4000, tz=UTC),
+ "subject": "agent commit",
+ "lines_added": 10,
+ "lines_deleted": 2,
+ "files_changed": 1,
+ "dirs_changed": 1,
+ "subsystems_changed": 1,
+ "entropy": 0.5,
+ "is_fix": False,
+ "author_experience": 1,
+ "change_risk_score": 3.0,
+ "change_risk_level": "low",
+ "agent_name": "claude-code",
+ "agent_autonomy_tier": 2,
+ "agent_channel": "git_footer",
+ "agent_confidence": "high",
+ }
+ ],
+ )
+
+
+async def test_commits_carry_agent_provenance_and_top_driver(
+ client: AsyncClient, app
+) -> None:
+ repo = await create_test_repo(client)
+ await _insert_git_commits(app.state.session_factory, repo["id"])
+ await _insert_agent_commit(app.state.session_factory, repo["id"])
+
+ resp = await client.get(f"/api/repos/{repo['id']}/commits", params={"sort": "date"})
+ assert resp.status_code == 200
+ items = resp.json()["items"]
+ assert items[0]["sha"] == "dddddddd44"
+ assert items[0]["agent_name"] == "claude-code"
+ assert items[0]["agent_autonomy_tier"] == 2
+ assert items[0]["agent_confidence"] == "high"
+ assert items[0]["author_experience"] == 1
+ # Human rows carry no agent attribution but do carry a top driver.
+ human = items[-1]
+ assert human["agent_name"] is None
+ assert isinstance(human["top_driver"], str) and human["top_driver"]
+
+ detail = await client.get(f"/api/repos/{repo['id']}/commits/dddddddd")
+ assert detail.status_code == 200
+ assert detail.json()["agent_channel"] == "git_footer"
+
+
+async def test_commits_authorship_filter(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _insert_git_commits(app.state.session_factory, repo["id"])
+ await _insert_agent_commit(app.state.session_factory, repo["id"])
+
+ agents = await client.get(
+ f"/api/repos/{repo['id']}/commits", params={"authorship": "agent"}
+ )
+ assert agents.status_code == 200
+ assert agents.json()["total"] == 1
+ assert agents.json()["items"][0]["agent_name"] == "claude-code"
+
+ humans = await client.get(
+ f"/api/repos/{repo['id']}/commits", params={"authorship": "human"}
+ )
+ assert humans.json()["total"] == 3
+ assert all(c["agent_name"] is None for c in humans.json()["items"])
+
+
+async def test_agent_trend(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _insert_git_commits(app.state.session_factory, repo["id"])
+ await _insert_agent_commit(app.state.session_factory, repo["id"])
+
+ resp = await client.get(f"/api/repos/{repo['id']}/commits/agent-trend")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["total_commits"] == 4
+ assert data["agent_commits"] == 1
+ assert data["agent_pct"] == 25.0
+ assert data["agent_names"] == [{"name": "claude-code", "count": 1}]
+ # All four fixture commits share the epoch-1970 month bucket.
+ assert len(data["buckets"]) == 1
+ bucket = data["buckets"][0]
+ assert bucket["total_commits"] == 4
+ assert bucket["tier_counts"] == {"2": 1}
+
+
@pytest.mark.asyncio
async def test_get_git_summary(client: AsyncClient, app) -> None:
repo = await create_test_repo(client)
diff --git a/tests/unit/server/test_owners.py b/tests/unit/server/test_owners.py
index c54e61a5e..5417db196 100644
--- a/tests/unit/server/test_owners.py
+++ b/tests/unit/server/test_owners.py
@@ -105,6 +105,42 @@ async def test_get_owner_profile(client: AsyncClient, app) -> None:
assert "Bob" in coauthors
+async def test_owner_profile_agent_collab_and_totals(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+ # Give Alice's owned file an agent-provenance rollup.
+ async with get_session(app.state.session_factory) as session:
+ await crud.upsert_git_metadata(
+ session,
+ repository_id=repo["id"],
+ file_path="src/main.py",
+ agent_commit_count=10,
+ agent_authored_pct=0.2,
+ agent_tier_counts_json=json.dumps({"2": 7, "3": 3}),
+ )
+
+ key = quote("[email protected]", safe="")
+ resp = await client.get(f"/api/repos/{repo['id']}/owners/{key}")
+ assert resp.status_code == 200
+ data = resp.json()
+ collab = data["agent_collab"]
+ assert collab is not None
+ assert collab["files_with_agent_commits"] == 1
+ assert collab["agent_commit_count"] == 10
+ assert collab["agent_share_pct"] == 20.0 # 10 of 50 commits on main.py
+ assert collab["tier_counts"] == {"2": 7, "3": 3}
+ # Truncation totals match the (small) fixture exactly.
+ assert data["files_touched_total"] == len(data["top_files"])
+ assert data["co_authors_total"] == len(data["co_authors"])
+
+ # Bob owns only utils.py, which has no provenance rollup -> null.
+ bob = await client.get(
+ f"/api/repos/{repo['id']}/owners/{quote('[email protected]', safe='')}"
+ )
+ assert bob.json()["agent_collab"] is None
+
+
@pytest.mark.asyncio
async def test_last_commit_uses_authors_own_timestamp(client: AsyncClient, app) -> None:
"""A contributor's last_commit_at is their *own* last commit to a file,
diff --git a/tests/unit/server/test_pages.py b/tests/unit/server/test_pages.py
index eed1ece03..4c2be9534 100644
--- a/tests/unit/server/test_pages.py
+++ b/tests/unit/server/test_pages.py
@@ -83,6 +83,38 @@ async def test_get_page_versions_empty(client: AsyncClient, app) -> None:
assert resp.json() == [] # First version has no archived versions
+async def test_update_page_notes_roundtrip(client: AsyncClient, app) -> None:
+ _, page_id = await _create_page(client, app.state.session_factory)
+
+ resp = await client.patch(
+ "/api/pages/lookup/notes",
+ params={"page_id": page_id},
+ json={"human_notes": "Reviewed by platform team."},
+ )
+ assert resp.status_code == 200
+ assert resp.json()["human_notes"] == "Reviewed by platform team."
+
+ # Whitespace-only clears the note back to null.
+ cleared = await client.patch(
+ "/api/pages/lookup/notes",
+ params={"page_id": page_id},
+ json={"human_notes": " "},
+ )
+ assert cleared.status_code == 200
+ assert cleared.json()["human_notes"] is None
+
+
+async def test_update_page_notes_not_found(client: AsyncClient) -> None:
+ resp = await client.patch(
+ "/api/pages/lookup/notes",
+ params={"page_id": "file_page:missing.py"},
+ json={"human_notes": "x"},
+ )
+ assert resp.status_code == 404
+
+
@pytest.mark.asyncio
async def test_regenerate_page_returns_202(client: AsyncClient, app) -> None:
_, page_id = await _create_page(client, app.state.session_factory)