Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat: shared UI/server building blocks for both web surfaces (#423)
Swati Ahuja3464aaf678f5
diff --git a/docs/design/contrast_check.py b/docs/design/contrast_check.pyindex b3411309c..cca99523e 100644--- a/docs/design/contrast_check.py+++ b/docs/design/contrast_check.py@@ -1,220 +1,21 @@#!/usr/bin/env python3-"""Theme tokens — WCAG contrast verification.+"""Wrapper — the canonical contrast gate ships with the ui package.-Computes WCAG 2.1 relative-luminance contrast ratios for every critical-text/surface, accent-on-surface, and status pair in both light and dark-modes, and asserts the floors from the redesign plan:-- - body text on primary surfaces >= 7.0 (AAA)- - secondary text / large text / status >= 4.5 (AA)- - interactive / non-text UI >= 3.0--Semi-transparent tokens (borders, muted fills) are alpha-composited over-their surface before the ratio is computed, so the numbers reflect what a-user actually sees. Run: python3 docs/design/contrast_check.py-Exits non-zero if any required pair misses its floor (CI gate).+The gate lives at packages/ui/scripts/contrast-check.py so downstream+consumers run the same check from node_modules. This wrapper keeps the+historical invocation (`python3 docs/design/contrast_check.py`) working."""from __future__ import annotations-import re+import pathlib+import runpyimport sys--# ---------------------------------------------------------------------------# Color helpers-# ---------------------------------------------------------------------------def _hex_to_rgb(h: str) -> tuple[float, float, float]:- h = h.lstrip("#")- if len(h) == 3:- h = "".join(c * 2 for c in h)- return tuple(int(h[i : i + 2], 16) / 255 for i in (0, 2, 4))---def _parse(color: str) -> tuple[float, float, float, float]:- """Return (r, g, b, alpha) in 0..1 from a hex or rgba() string."""- color = color.strip()- if color.startswith("#"):- r, g, b = _hex_to_rgb(color)- return r, g, b, 1.0- m = re.match(r"rgba?\(([^)]+)\)", color)- if not m:- raise ValueError(f"unparseable color: {color}")- parts = [p.strip() for p in m.group(1).split(",")]- r, g, b = (int(parts[i]) / 255 for i in range(3))- a = float(parts[3]) if len(parts) > 3 else 1.0- return r, g, b, a---def _composite(fg: str, bg: str) -> tuple[float, float, float]:- """Alpha-composite fg over an opaque bg, return opaque rgb."""- fr, fg_, fb, fa = _parse(fg)- br, bg_, bb, _ = _parse(bg)- return (- fr * fa + br * (1 - fa),- fg_ * fa + bg_ * (1 - fa),- fb * fa + bb * (1 - fa),- )---def _lin(c: float) -> float:- return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4---def _lum(rgb: tuple[float, float, float]) -> float:- r, g, b = (_lin(c) for c in rgb)- return 0.2126 * r + 0.7152 * g + 0.0722 * b---def contrast(fg: str, bg: str) -> float:- """WCAG contrast ratio of fg over (opaque) bg, compositing alpha first."""- fg_rgb = _composite(fg, bg)- bg_rgb = _composite(bg, bg)- l1, l2 = _lum(fg_rgb), _lum(bg_rgb)- hi, lo = max(l1, l2), min(l1, l2)- return (hi + 0.05) / (lo + 0.05)---# ---------------------------------------------------------------------------# Token values (must mirror packages/ui/styles/globals.css)-# ---------------------------------------------------------------------------LIGHT = {- "bg-root": "#FBF6F1",- "bg-surface": "#FFFFFF",- "bg-elevated": "#FBF4EE",- "bg-inset": "#F4EAE1",- "bg-canvas": "#F4EAE1", # --color-bg-canvas → var(--color-bg-inset)- "text-primary": "#241B2C",- "text-secondary": "#5E5360",- "text-tertiary": "#8C7F88",- "text-inverse": "#FFFFFF",- "text-on-accent": "#241B2C",- "accent-primary": "#A16215",- "accent-fill": "#F59520",- "accent-secondary": "#58436C",- "border-default": "rgba(88,67,108,0.12)",- "border-active": "rgba(176,107,18,0.90)",- "success": "#1D8155",- "warning": "#9A6614",- "error": "#B23A2E",- "info": "#58436C",- # Blueprint diagram ink (light) — KG canvas + mermaid.- "diagram-node-fill": "#241B2C",- "diagram-node-fill-2": "#4A4152",- "diagram-node-text": "#FBF6F1",- "diagram-node-border": "#241B2C",- "gradient-ember-end": "#F7A94D",- # KG node faces (light) — paper cards with ink outline.- "kg-node-fill": "#FFFDF8",- "kg-node-fill-2": "#F3ECE2",- "kg-node-text": "#241B2C",- "kg-node-border": "#241B2C",- "kg-node-border-2": "#8C7F88",- # Textured face composite: 0.78 warm-white wash over the paper photo- # (avg ~#E6E8E9) — what text actually sits on.- "kg-node-face-textured": "#FAF8F4",- # Community family hubs (light) — graph clustering palette.- "community-1": "#C0641A", "community-2": "#58436C", "community-3": "#B23A2E",- "community-4": "#6B7A3D", "community-5": "#B06A86", "community-6": "#4A5D7A",- "community-7": "#A8821F", "community-8": "#8A7A66", "community-9": "#7A2F4A",- "community-10": "#B85A38", "community-11": "#2F6B66", "community-12": "#5E5360",-}--DARK = {- "bg-root": "#17131D",- "bg-surface": "#211B29",- "bg-elevated": "#2A2335",- "bg-inset": "#110D17",- "bg-canvas": "#110D17", # --color-bg-canvas → var(--color-bg-inset)- "text-primary": "#EEEAF4",- "text-secondary": "#A79DB3",- "text-tertiary": "#786F84",- "text-inverse": "#17131D",- "text-on-accent": "#17131D",- "accent-primary": "#F59520",- "accent-fill": "#F59520",- "accent-secondary": "#A98FC4",- "border-default": "rgba(213,197,232,0.10)",- "border-active": "rgba(245,149,32,0.55)",- "success": "#34D399",- "warning": "#F2A03D",- "error": "#E06A5A",- "info": "#A98FC4",- # Blueprint diagram ink (dark) — border carries canvas separation.- "diagram-node-fill": "#322A3E",- "diagram-node-fill-2": "#261F30",- "diagram-node-text": "#EEEAF4",- "diagram-node-border": "rgba(222,210,235,0.45)",- "gradient-ember-end": "#F7A94D",- # KG node faces (dark) — alias back to the solid ink blocks.- "kg-node-fill": "#322A3E",- "kg-node-fill-2": "#261F30",- "kg-node-text": "#EEEAF4",- "kg-node-border": "rgba(222,210,235,0.45)",- "kg-node-border-2": "rgba(222,210,235,0.45)",- # Textured face composite: 0.85 ink wash (#322A3E) over the paper photo.- "kg-node-face-textured": "#4D4658",- # Community family hubs (dark) — lifted to read on the near-black canvas.- "community-1": "#F59520", "community-2": "#A98FC4", "community-3": "#E06A5A",- "community-4": "#A9BB6F", "community-5": "#D795B1", "community-6": "#8FA3C0",- "community-7": "#D9B04A", "community-8": "#B8A68E", "community-9": "#C4708F",- "community-10": "#EBA585", "community-11": "#6FB3AB", "community-12": "#A79DB3",-}--# (fg, bg, floor, label) — floor is the WCAG ratio the pair must meet.-CHECKS = [- ("text-primary", "bg-root", 7.0, "Body text on page"),- ("text-primary", "bg-surface", 7.0, "Body text on card"),- ("text-primary", "bg-elevated", 7.0, "Body text on elevated"),- ("text-secondary", "bg-root", 4.5, "Secondary text on page"),- ("text-secondary", "bg-surface", 4.5, "Secondary text on card"),- ("text-tertiary", "bg-surface", 3.0, "Tertiary/hint on card"),- ("accent-primary", "bg-surface", 4.5, "Accent text on card"),- ("accent-primary", "bg-root", 4.5, "Accent text on page"),- ("accent-secondary", "bg-surface", 4.5, "Plum link-alt on card"),- ("text-on-accent", "accent-fill", 4.5, "Text on accent fill (CTA)"),- ("text-inverse", "accent-primary", 4.5, "Text on accent-primary fill"),- ("success", "bg-surface", 4.5, "Success text on card"),- ("warning", "bg-surface", 4.5, "Warning text on card"),- ("error", "bg-surface", 4.5, "Error text on card"),- ("info", "bg-surface", 4.5, "Info text on card"),- ("border-active", "bg-surface", 3.0, "Active border on card"),- # Blueprint ink nodes (KG canvas): text on both ink weights; the node- # boundary (fill in light, border in dark) must separate from the canvas.- ("diagram-node-text", "diagram-node-fill", 4.5, "Ink node text on primary fill"),- ("diagram-node-text", "diagram-node-fill-2", 4.5, "Ink node text on secondary fill"),- ("diagram-node-border", "bg-canvas", 3.0, "Ink node boundary on canvas"),- ("kg-node-text", "kg-node-fill", 4.5, "KG card text on primary face"),- ("kg-node-text", "kg-node-fill-2", 4.5, "KG card text on secondary face"),- ("kg-node-border", "bg-canvas", 3.0, "KG card outline on canvas"),- ("kg-node-border-2", "bg-canvas", 3.0, "KG supporting outline on canvas"),- ("kg-node-text", "kg-node-face-textured", 4.5, "KG card text on textured face"),- ("text-on-accent", "gradient-ember-end", 4.5, "Text on ember gradient end"),- # Community hubs are non-text node fills on the graph canvas — floor 3.0:1.- *[- (f"community-{n}", "bg-canvas", 3.0, f"Community {n} hub on canvas")- for n in range(1, 13)- ],-]---def run() -> int:- failures = 0- rows: list[str] = []- for mode, tokens in (("Light", LIGHT), ("Dark", DARK)):- rows.append(f"\n### {mode} mode\n")- rows.append("| Pair | Ratio | Floor | Result |")- rows.append("|------|-------|-------|--------|")- for fg, bg, floor, label in CHECKS:- ratio = contrast(tokens[fg], tokens[bg])- ok = ratio >= floor- if not ok:- failures += 1- mark = "PASS" if ok else "**FAIL**"- rows.append(f"| {label} | {ratio:.2f} | {floor:.1f} | {mark} |")- print("\n".join(rows))- print(f"\n**Total pairs:** {len(CHECKS) * 2} · **Failures:** {failures}")- return 1 if failures else 0-+GATE = (+ pathlib.Path(__file__).resolve().parents[2]+ / "packages" / "ui" / "scripts" / "contrast-check.py"+)if __name__ == "__main__":- sys.exit(run())+ sys.argv[0] = str(GATE)+ runpy.run_path(str(GATE), run_name="__main__")diff --git a/docs/design/no-raw-hex-check.sh b/docs/design/no-raw-hex-check.shindex 064b11787..4d8accfc2 100755--- a/docs/design/no-raw-hex-check.sh+++ b/docs/design/no-raw-hex-check.sh@@ -1,47 +1,10 @@#!/usr/bin/env bash#-# no-raw-hex gate (design tokens) — fails if a raw hex color literal appears-# in packages/ui/src OUTSIDE the allowlist below. Wire into CI.-#-# The allowlist has two kinds of entries:-# * BRAND/STRUCTURAL — hex that must stay literal because it's an identity-# color or is consumed where a CSS var() cannot resolve (e.g. <canvas>).-# * DEFERRED-VIZ — viz subsystems whose theme-aware tokenization needs-# runtime CSS-var resolution + visual QA; tracked as follow-up. Listed-# explicitly so the gate stays honest (it is NOT silently ignoring them).-#-# Everything else — charts, badges, tooltips, treemaps, shared/primitives —-# must route color through the design tokens. New raw hex there fails CI.-#-# Usage: bash docs/design/no-raw-hex-check.sh+# Wrapper — the canonical no-raw-hex gate ships with the ui package+# (packages/ui/scripts/no-raw-hex-check.sh) so downstream consumers run the+# same check from node_modules. This wrapper keeps the historical invocation+# (`bash docs/design/no-raw-hex-check.sh`) working; defaults scan+# packages/ui/src exactly as before.set -euo pipefail-cd "$(dirname "$0")/../.."-ROOT="packages/ui/src"--# Files/dirs allowed to contain raw hex (regex, matched against the path).-ALLOW='(__tests__|\.test\.)' # test fixtures-ALLOW+='|lib/confidence\.ts' # BRAND: LANGUAGE/EDGE color hex (canvas)-ALLOW+='|costs/provider-comparison\.tsx' # BRAND: provider identity colors-ALLOW+='|workspace/workspace-graph-node\.tsx' # dynamic langColor hex-alpha concat-ALLOW+='|graph-primitives/tone-styles\.ts' # BRAND: categorical node-tone palette (like lang colors)-ALLOW+='|wiki/git-history-panel\.tsx' # BRAND: per-author categorical bar colors-# DEFERRED-VIZ — canvas subsystems with their own runtime light/dark palette-# (driven by the global theme), pending an aesthetic warm-palette retune:-ALLOW+='|c4/export/svg-exporter\.ts' # SVG serializer resolves LIVE theme tokens; hex are headless-export fallbacks only (kg-ux B7)-ALLOW+='|/graph/sigma/' # Sigma canvas renderer (internal light/dark palette)--violations=$(grep -rnE '#[0-9a-fA-F]{3,8}\b' "$ROOT" 2>/dev/null \- | grep -vE "$ALLOW" || true)--if [ -n "$violations" ]; then- echo "no-raw-hex gate FAILED — raw hex outside the token system:"- echo "$violations"- echo- echo "Route color through a design token (var(--color-*)), or add a"- echo "documented allowlist entry if it is a brand/canvas constant."- exit 1-fi--echo "no-raw-hex gate passed — cleaned surfaces route color through tokens."-echo "(Deferred viz subsystems are allowlisted; see this script's header.)"+exec bash "$(dirname "${BASH_SOURCE[0]}")/../../packages/ui/scripts/no-raw-hex-check.sh" "$@"diff --git a/package-lock.json b/package-lock.jsonindex d8d8730d4..5d299f411 100644--- a/package-lock.json+++ b/package-lock.json@@ -14439,6 +14439,7 @@"name": "@repowise-dev/ui","version": "0.1.0","dependencies": {+ "@lottiefiles/dotlottie-react": "^0.19.4","@radix-ui/react-dialog": "^1.1.15","@radix-ui/react-hover-card": "^1.1.15","@radix-ui/react-label": "^2.1.8",diff --git a/packages/cli/src/repowise/cli/ui/brand.py b/packages/cli/src/repowise/cli/ui/brand.pyindex 9e2a57faa..39bcfe7fd 100644--- a/packages/cli/src/repowise/cli/ui/brand.py+++ b/packages/cli/src/repowise/cli/ui/brand.py@@ -22,20 +22,25 @@ ERR = "bold red"# ---------------------------------------------------------------------------# Breathing room required beyond the rendered banner width before we pick the-# full variant; below that we fall back to compact (same design, 1-char strokes).+# long tagline; below that we use the short one._BANNER_WIDTH_MARGIN = 4def print_banner(console: Console, repo_name: str | None = None) -> None:- """Print the repowise owl banner, tagline, and optional repo name."""+ """Print the repowise owl banner, tagline, and optional repo name.++ Always renders the compact art (1-char strokes — about two thirds the+ width of the full variant) so the banner stays understated; only the+ tagline grows on wide terminals.+ """from repowise.cli import __version__from repowise.cli.ui import mascot- compact = console.width < mascot.banner_width() + _BANNER_WIDTH_MARGIN+ narrow = console.width < mascot.banner_width() + _BANNER_WIDTH_MARGINconsole.print()- console.print(mascot.banner_text(repo_name, compact=compact))+ console.print(mascot.banner_text(repo_name, compact=True))console.print()- if compact:+ if narrow:console.print(f" [dim]codebase intelligence · v{__version__}[/dim]", highlight=False)else:console.print(diff --git a/packages/server/src/repowise/server/routers/c4.py b/packages/server/src/repowise/server/routers/c4.pyindex 4d0be7d0b..7135af5e2 100644--- a/packages/server/src/repowise/server/routers/c4.py+++ b/packages/server/src/repowise/server/routers/c4.py@@ -18,15 +18,9 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom fastapi import APIRouter, Depends, HTTPException, Queryfrom repowise.server.deps import get_db_session, verify_api_keyfrom repowise.server.schemas import (- ArchEdgeResponse,ArchitectureViewResponse,- ArchLayerResponse,- ArchNodeResponse,- ArchSubGroupResponse,- ArchTourStepResponse,C4ComponentResponse,C4ContainerResponse,- C4ExternalSystemResponse,C4L1Response,C4L2Response,C4L3Response,@@ -35,25 +29,22 @@ from repowise.server.schemas import (C4SystemResponse,)from repowise.server.services import c4_builder-from repowise.server.services.c4_builder.architecture import build_architecture_viewfrom repowise.server.services.c4_builder.mermaid import (to_mermaid_l1,to_mermaid_l2,to_mermaid_l3,)from repowise.server.services.c4_builder.models import (- ArchEdge,- ArchitectureView,- ArchLayer,- ArchNode,- ArchTourStep,Component,Container,- ExternalSystemView,Person,Relation,System,)+from repowise.server.services.c4_builder.serialize import (+ build_architecture_view_response,+ external_system_response,+)router = APIRouter(prefix="/api/graph",@@ -71,7 +62,7 @@ async def get_c4_l1(return C4L1Response(system=_system(view.system),people=[_person(p) for p in view.people],- external_systems=[_external(e) for e in view.external_systems],+ external_systems=[external_system_response(e) for e in view.external_systems],relations=[_relation(r) for r in view.relations],)@@ -84,7 +75,7 @@ async def get_c4_l2(view = await c4_builder.build_l2(session, repo_id)return C4L2Response(containers=[_container(c) for c in view.containers],- external_systems=[_external(e) for e in view.external_systems],+ external_systems=[external_system_response(e) for e in view.external_systems],relations=[_relation(r) for r in view.relations],)@@ -101,7 +92,7 @@ async def get_c4_l3(return C4L3Response(container=_container(view.container),components=[_component(c) for c in view.components],- external_systems=[_external(e) for e in view.external_systems],+ external_systems=[external_system_response(e) for e in view.external_systems],relations=[_relation(r) for r in view.relations],)@@ -154,17 +145,6 @@ def _person(p: Person) -> C4PersonResponse:return C4PersonResponse(id=p.id, name=p.name, description=p.description)-def _external(e: ExternalSystemView) -> C4ExternalSystemResponse:- return C4ExternalSystemResponse(- id=e.id,- name=e.name,- display_name=e.display_name,- category=e.category,- ecosystem=e.ecosystem,- version=e.version,- )--def _container(c: Container) -> C4ContainerResponse:return C4ContainerResponse(id=c.id,@@ -200,7 +180,7 @@ def _relation(r: Relation) -> C4RelationResponse:# ----------------------------------------------------------------------------# Architecture view endpoint + adapters+# Architecture view endpoint — thin wrapper over services.c4_builder.serialize# ---------------------------------------------------------------------------@@ -210,95 +190,6 @@ async def get_architecture_view(include_symbols: bool = Query(False, description="Include symbol-level nodes"),session: AsyncSession = Depends(get_db_session),) -> ArchitectureViewResponse:- view = await build_architecture_view(session, repo_id, include_symbols=include_symbols)- return _architecture_view_response(view)---def _arch_layer(layer: ArchLayer) -> ArchLayerResponse:- return ArchLayerResponse(- id=layer.id,- name=layer.name,- description=layer.description,- node_ids=layer.node_ids,- file_count=layer.file_count,- complexity_distribution=layer.complexity_distribution,- health_score=layer.health_score,- sub_groups=[- ArchSubGroupResponse(id=sg.id, name=sg.name, node_ids=sg.node_ids)- for sg in layer.sub_groups- ],- display_order=layer.display_order,- )---def _arch_node(n: ArchNode) -> ArchNodeResponse:- return ArchNodeResponse(- id=n.id,- node_type=n.node_type,- name=n.name,- file_path=n.file_path,- line_range=list(n.line_range) if n.line_range else None,- summary=n.summary,- complexity=n.complexity,- tags=n.tags,- language=n.language,- pagerank=n.pagerank,- pagerank_percentile=n.pagerank_percentile,- betweenness=n.betweenness,- in_degree=n.in_degree,- out_degree=n.out_degree,- community_id=n.community_id,- is_entry_point=n.is_entry_point,- is_test=n.is_test,- is_hotspot=n.is_hotspot,- is_dead=n.is_dead,- has_doc=n.has_doc,- primary_owner=n.primary_owner,- primary_owner_pct=n.primary_owner_pct,- bus_factor=n.bus_factor,- )---def _arch_edge(e: ArchEdge) -> ArchEdgeResponse:- return ArchEdgeResponse(- source=e.source,- target=e.target,- edge_type=e.edge_type,- direction=e.direction,- weight=e.weight,- confidence=e.confidence,- )---def _arch_tour_step(s: ArchTourStep) -> ArchTourStepResponse:- return ArchTourStepResponse(- order=s.order,- title=s.title,- description=s.description,- node_ids=s.node_ids,- target_path=s.target_path,- layer_id=s.layer_id,- reason=s.reason,- depth=s.depth,- kind=s.kind,- page_type=s.page_type,- )---def _architecture_view_response(view: ArchitectureView) -> ArchitectureViewResponse:- return ArchitectureViewResponse(- project_name=view.project_name,- project_description=view.project_description,- layers=[_arch_layer(la) for la in view.layers],- nodes=[_arch_node(n) for n in view.nodes],- edges=[_arch_edge(e) for e in view.edges],- tour=[_arch_tour_step(s) for s in view.tour],- total_files=view.total_files,- total_symbols=view.total_symbols,- total_edges=view.total_edges,- languages=view.languages,- frameworks=view.frameworks,- external_systems=[_external(e) for e in view.external_systems],- entry_points=view.entry_points,- entry_candidates=view.entry_candidates,+ return await build_architecture_view_response(+ session, repo_id, include_symbols=include_symbols)diff --git a/packages/server/src/repowise/server/routers/graph/_common.py b/packages/server/src/repowise/server/routers/graph/_common.pyindex 830ebf793..e6c4c6416 100644--- a/packages/server/src/repowise/server/routers/graph/_common.py+++ b/packages/server/src/repowise/server/routers/graph/_common.py@@ -2,16 +2,13 @@from __future__ import annotations-import json-from fastapi import Depends, HTTPExceptionfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.persistence import crud-from repowise.core.persistence.models import GraphEdge, Page, Repository+from repowise.core.persistence.models import Page, Repositoryfrom repowise.server.deps import get_db_session-from repowise.server.schemas import GraphEdgeResponseasync def with_repo(@@ -36,25 +33,6 @@ def _escape_like(s: str) -> str:return s.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")-def _parse_imported_names(raw: str | None) -> list[str]:- if not raw:- return []- try:- result = json.loads(raw)- return result if isinstance(result, list) else []- except (json.JSONDecodeError, ValueError):- return []---def _edge_response(e: GraphEdge) -> GraphEdgeResponse:- """Build a GraphEdgeResponse from a GraphEdge ORM row."""- return GraphEdgeResponse(- source=e.source_node_id,- target=e.target_node_id,- imported_names=_parse_imported_names(e.imported_names_json),- )--async def _get_documented_paths(session: AsyncSession, repo_id: str) -> set[str]:"""Return the set of node_ids (file paths) that have a wiki page."""result = await session.execute(select(Page.target_path).where(Page.repository_id == repo_id))diff --git a/packages/server/src/repowise/server/routers/graph/community.py b/packages/server/src/repowise/server/routers/graph/community.pyindex a74e1f327..0744db483 100644--- a/packages/server/src/repowise/server/routers/graph/community.py+++ b/packages/server/src/repowise/server/routers/graph/community.py@@ -1,44 +1,33 @@-"""Community-level views: architecture super-graph and community summaries."""+"""Community-level views: architecture super-graph and community summaries.++The architecture and slice endpoints are thin wrappers over+:mod:`repowise.server.services.graph_views` so non-HTTP consumers can build+the same payloads without FastAPI.+"""from __future__ import annotationsfrom fastapi import APIRouter, Depends, HTTPException, Query-from sqlalchemy import or_, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.persistence import crud-from repowise.core.persistence.models import GraphEdge, GraphNode+from repowise.core.persistence.models import GraphNodefrom repowise.server.deps import get_db_sessionfrom repowise.server.mcp_server._graph_utils import community_cohesion, community_label-from repowise.server.routers.graph._common import _edge_response, with_repo-from repowise.server.routers.graph.signals import (- _EMPTY_SIGNALS,- _collect_node_signals,- _node_to_response,-)+from repowise.server.routers.graph._common import with_repofrom repowise.server.schemas import (- ArchitectureEdgeResponse,ArchitectureGraphResponse,- ArchitectureNodeResponse,CommunityDetailResponse,CommunityMember,- CommunitySliceNodeResponse,CommunitySliceResponse,CommunitySummaryItem,NeighboringCommunity,)--# Cap on slice member nodes. Communities are small relative to the repo, but a-# few mega-clusters exist; this keeps the blossom payload in the 50-300 target-# band and the satellite layout responsive.-_SLICE_MEMBER_CAP = 300-# Boundary stubs per slice: only the most-connected outside neighbors survive,-# so a blossom shows its strongest cross-cluster ties instead of a dust cloud.-_SLICE_BOUNDARY_CAP = 40-# Chunk size for member-id IN lists. The slice edge filter ORs two IN clauses-# (source + target) in one statement, so we cap each chunk well under SQLite's-# 999-parameter limit to leave room for both lists plus the repo_id bind.-_SLICE_IN_CHUNK = 400+from repowise.server.services.graph_views import (+ SLICE_MEMBER_CAP,+ build_architecture_graph,+ build_community_slice,+)router = APIRouter()@@ -52,92 +41,8 @@ async def architecture_graph(session: AsyncSession = Depends(get_db_session), # noqa: B008_repo: object = Depends(with_repo),) -> ArchitectureGraphResponse:- """High-level architecture view: one node per detected community.-- Edges between communities are weighted by the number of underlying file- edges that cross the boundary. Each super-node also carries signal counts- (hotspots, dead files, decisions, doc coverage) so the architecture view- surfaces health at a glance.- """- all_nodes = await crud.get_all_file_metrics(session, repo_id)- if not all_nodes:- return ArchitectureGraphResponse(nodes=[], edges=[])-- # Group file nodes by community- buckets: dict[int, list[GraphNode]] = {}- node_to_community: dict[str, int] = {}- for n in all_nodes:- cid = n.community_id if n.community_id is not None else 0- buckets.setdefault(cid, []).append(n)- node_to_community[n.node_id] = cid-- # Pull cross-link signals once for the whole repo so super-nodes can- # aggregate hotspot/dead/decision counts without N round-trips.- signals = await _collect_node_signals(session, repo_id, [n.node_id for n in all_nodes])-- arch_nodes: list[ArchitectureNodeResponse] = []- for cid, members in buckets.items():- if len(members) < min_members:- continue- top = max(members, key=lambda m: m.pagerank or 0.0)- hotspot_count = 0- dead_count = 0- has_decision = False- doc_hits = 0- langs: dict[str, int] = {}- for m in members:- sig = signals.get(m.node_id, _EMPTY_SIGNALS)- if sig.is_hotspot:- hotspot_count += 1- if sig.is_dead:- dead_count += 1- if sig.has_decision:- has_decision = True- if sig.has_doc:- doc_hits += 1- if m.language:- langs[m.language] = langs.get(m.language, 0) + 1- top_langs = [lang for lang, _ in sorted(langs.items(), key=lambda kv: -kv[1])[:3]]- avg_pr = sum(m.pagerank or 0.0 for m in members) / max(len(members), 1)-- arch_nodes.append(- ArchitectureNodeResponse(- community_id=cid,- label=community_label(top),- cohesion=community_cohesion(top),- member_count=len(members),- top_file=top.node_id,- avg_pagerank=avg_pr,- hotspot_count=hotspot_count,- dead_count=dead_count,- has_decision=has_decision,- doc_coverage_pct=doc_hits / max(len(members), 1),- languages=top_langs,- )- )-- arch_nodes.sort(key=lambda a: -a.member_count)- kept_communities = {a.community_id for a in arch_nodes}-- # Collapse cross-community edges- edge_result = await session.execute(select(GraphEdge).where(GraphEdge.repository_id == repo_id))- edge_counts: dict[tuple[int, int], int] = {}- for e in edge_result.scalars():- src_c = node_to_community.get(e.source_node_id)- tgt_c = node_to_community.get(e.target_node_id)- if src_c is None or tgt_c is None or src_c == tgt_c:- continue- if src_c not in kept_communities or tgt_c not in kept_communities:- continue- key = (src_c, tgt_c)- edge_counts[key] = edge_counts.get(key, 0) + 1-- arch_edges = [- ArchitectureEdgeResponse(source=s, target=t, edge_count=c)- for (s, t), c in edge_counts.items()- ]-- return ArchitectureGraphResponse(nodes=arch_nodes, edges=arch_edges)+ """High-level architecture view: one node per detected community."""+ return await build_architecture_graph(session, repo_id, min_members=min_members)@router.get(@@ -147,108 +52,13 @@ async def architecture_graph(async def community_slice(repo_id: str,community_id: int,- member_limit: int = Query(_SLICE_MEMBER_CAP, ge=1, le=600),+ member_limit: int = Query(SLICE_MEMBER_CAP, ge=1, le=600),session: AsyncSession = Depends(get_db_session), # noqa: B008_repo: object = Depends(with_repo),) -> CommunitySliceResponse:- """Return a single community's sub-graph for the constellation blossom.-- Payload = the community's member file nodes, the edges among them, and a- thin ring of one-hop *boundary stubs*: neighbor nodes outside the community- that share an edge with a member, returned as minimal nodes flagged- ``is_boundary=true`` so cross-cluster edges can render without dragging the- whole neighbor cluster in. Sized to ~50-300 nodes.- """- members = await crud.get_community_members(- session, repo_id, community_id, node_type="file", limit=member_limit + 1- )- truncated = len(members) > member_limit- if truncated:- members = members[:member_limit]- member_ids = {m.node_id for m in members}-- # Edges touching any member: among-members stay; member<->outside become- # cross-cluster links that pull in a boundary stub for the outside endpoint.- # The membership filter is pushed into SQL (source OR target in members) so- # we never load the whole repo's edge table into Python; the IN lists are- # chunked under SQLite's parameter limit. The Python filter below is kept- # as-is for correctness — the SQL only bounds the rows fetched (a- # superset-or-equal of what the Python filter keeps).- member_id_list = list(member_ids)- edge_rows: dict[str, GraphEdge] = {}- for start in range(0, len(member_id_list), _SLICE_IN_CHUNK):- chunk = member_id_list[start : start + _SLICE_IN_CHUNK]- chunk_result = await session.execute(- select(GraphEdge).where(- GraphEdge.repository_id == repo_id,- or_(- GraphEdge.source_node_id.in_(chunk),- GraphEdge.target_node_id.in_(chunk),- ),- )- )- # Dedup across chunks: an edge whose endpoints fall in different chunks- # matches twice. The PK keeps each edge once.- for e in chunk_result.scalars():- edge_rows[e.id] = e-- kept_edges: list[GraphEdge] = []- boundary_degree: dict[str, int] = {}- for e in edge_rows.values():- src_in = e.source_node_id in member_ids- tgt_in = e.target_node_id in member_ids- if not src_in and not tgt_in:- continue- kept_edges.append(e)- if not src_in:- boundary_degree[e.source_node_id] = boundary_degree.get(e.source_node_id, 0) + 1- if not tgt_in:- boundary_degree[e.target_node_id] = boundary_degree.get(e.target_node_id, 0) + 1-- # Cap boundary stubs to the most-connected neighbors: hub communities can- # touch thousands of outside files, which would flood the blossom with- # dust. Edges to dropped stubs are filtered by the visible_ids pass below.- boundary_ids = set(- sorted(boundary_degree, key=lambda n: (-boundary_degree[n], n))[:_SLICE_BOUNDARY_CAP]- )-- # Resolve boundary stub rows (minimal: just need a node row to render).- boundary_nodes: list[GraphNode] = []- if boundary_ids:- stub_result = await session.execute(- select(GraphNode).where(- GraphNode.repository_id == repo_id,- GraphNode.node_id.in_(boundary_ids),- )- )- boundary_nodes = list(stub_result.scalars().all())- resolved_boundary = {n.node_id for n in boundary_nodes}-- # Drop edges whose outside endpoint has no resolvable node (orphan ref).- visible_ids = member_ids | resolved_boundary- links = [- _edge_response(e)- for e in kept_edges- if e.source_node_id in visible_ids and e.target_node_id in visible_ids- ]-- # Member signals only (boundary stubs stay minimal / all-false signals).- signals = await _collect_node_signals(session, repo_id, list(member_ids))- nodes = [- _node_to_response(m, signals.get(m.node_id, _EMPTY_SIGNALS), CommunitySliceNodeResponse)- for m in members- ]- nodes.extend(- _node_to_response(n, _EMPTY_SIGNALS, CommunitySliceNodeResponse, is_boundary=True)- for n in boundary_nodes- )-- return CommunitySliceResponse(- nodes=nodes,- links=links,- community_id=community_id,- member_count=len(members),- truncated=truncated,+ """Return a single community's sub-graph for the constellation blossom."""+ return await build_community_slice(+ session, repo_id, community_id, member_limit=member_limit)diff --git a/packages/server/src/repowise/server/routers/graph/full_graph.py b/packages/server/src/repowise/server/routers/graph/full_graph.pyindex 25828b933..2c0c070cf 100644--- a/packages/server/src/repowise/server/routers/graph/full_graph.py+++ b/packages/server/src/repowise/server/routers/graph/full_graph.py@@ -8,13 +8,14 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.persistence.models import GraphEdge, GraphNodefrom repowise.server.deps import get_db_session-from repowise.server.routers.graph._common import _edge_response, _escape_like, with_repo-from repowise.server.routers.graph.signals import (- _EMPTY_SIGNALS,- _collect_node_signals,- _to_graph_node,-)+from repowise.server.routers.graph._common import _escape_like, with_repofrom repowise.server.schemas import GraphExportResponse, NodeSearchResult+from repowise.server.services.graph_views import edge_response+from repowise.server.services.node_signals import (+ EMPTY_SIGNALS,+ collect_node_signals,+ to_graph_node,+)# Cap on full-graph export; above this we return top-N by PageRank with truncated=True.# Sized to keep the client-side force layout responsive; clients can step the@@ -80,12 +81,12 @@ async def export_graph(edge_result = await session.execute(select(GraphEdge).where(GraphEdge.repository_id == repo_id))edges = edge_result.scalars().all()- signals = await _collect_node_signals(session, repo_id, list(kept_ids) if truncated else None)+ signals = await collect_node_signals(session, repo_id, list(kept_ids) if truncated else None)- node_responses = [_to_graph_node(n, signals.get(n.node_id, _EMPTY_SIGNALS)) for n in nodes]+ node_responses = [to_graph_node(n, signals.get(n.node_id, EMPTY_SIGNALS)) for n in nodes]link_responses = [- _edge_response(e)+ edge_response(e)for e in edgesif e.source_node_id in kept_ids and e.target_node_id in kept_ids]diff --git a/packages/server/src/repowise/server/routers/graph/module_graph.py b/packages/server/src/repowise/server/routers/graph/module_graph.pyindex 7ae987cb8..d0f174dd9 100644--- a/packages/server/src/repowise/server/routers/graph/module_graph.py+++ b/packages/server/src/repowise/server/routers/graph/module_graph.py@@ -9,12 +9,15 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.persistence.models import GraphEdge, GraphNode, Pagefrom repowise.server.deps import get_db_sessionfrom repowise.server.routers.graph._common import with_repo-from repowise.server.routers.graph.signals import _EMPTY_SIGNALS, _collect_node_signalsfrom repowise.server.schemas import (ModuleEdgeResponse,ModuleGraphResponse,ModuleNodeResponse,)+from repowise.server.services.node_signals import (+ EMPTY_SIGNALS,+ collect_node_signals,+)router = APIRouter()@@ -65,7 +68,7 @@ async def module_graph(# Collect signals once for all file nodes; aggregate per module below.all_node_ids = [n.node_id for n in nodes]- signals = await _collect_node_signals(session, repo_id, all_node_ids)+ signals = await collect_node_signals(session, repo_id, all_node_ids)node_to_module: dict[str, str] = {}module_nodes: list[ModuleNodeResponse] = []@@ -81,7 +84,7 @@ async def module_graph(has_decision = Falseowner_tally: dict[str, int] = {}for n in module_file_nodes:- sig = signals.get(n.node_id, _EMPTY_SIGNALS)+ sig = signals.get(n.node_id, EMPTY_SIGNALS)if sig.is_hotspot:hotspot_count += 1if sig.is_dead:diff --git a/packages/server/src/repowise/server/routers/graph/neighborhoods.py b/packages/server/src/repowise/server/routers/graph/neighborhoods.pyindex 252145e30..bd85c4197 100644--- a/packages/server/src/repowise/server/routers/graph/neighborhoods.py+++ b/packages/server/src/repowise/server/routers/graph/neighborhoods.py@@ -13,13 +13,7 @@ from repowise.core.persistence.models import (GraphNode,)from repowise.server.deps import get_db_session-from repowise.server.routers.graph._common import _edge_response, with_repo-from repowise.server.routers.graph.signals import (- _EMPTY_SIGNALS,- _collect_node_signals,- _node_to_response,- _to_graph_node,-)+from repowise.server.routers.graph._common import with_repofrom repowise.server.schemas import (DeadCodeGraphNodeResponse,DeadCodeGraphResponse,@@ -30,6 +24,13 @@ from repowise.server.schemas import (HotFilesGraphResponse,HotFilesNodeResponse,)+from repowise.server.services.graph_views import edge_response+from repowise.server.services.node_signals import (+ EMPTY_SIGNALS,+ collect_node_signals,+ node_to_response,+ to_graph_node,+)router = APIRouter()@@ -81,7 +82,7 @@ async def ego_graph(node_rows = node_result.scalars().all()ego_edge_responses = [- _edge_response(e)+ edge_response(e)for e in edgesif e.source_node_id in ego_node_ids and e.target_node_id in ego_node_ids]@@ -95,9 +96,9 @@ async def ego_graph(git_row = git_result.scalar_one_or_none()git_meta = GitMetadataResponse.from_orm(git_row) if git_row else None- signals = await _collect_node_signals(session, repo_id, list(ego_node_ids))+ signals = await collect_node_signals(session, repo_id, list(ego_node_ids))- node_responses = [_to_graph_node(n, signals.get(n.node_id, _EMPTY_SIGNALS)) for n in node_rows]+ node_responses = [to_graph_node(n, signals.get(n.node_id, EMPTY_SIGNALS)) for n in node_rows]return EgoGraphResponse(nodes=node_responses,@@ -154,12 +155,12 @@ async def entry_points_graph()nodes = node_result.scalars().all()- signals = await _collect_node_signals(session, repo_id, list(reachable))+ signals = await collect_node_signals(session, repo_id, list(reachable))- node_responses = [_to_graph_node(n, signals.get(n.node_id, _EMPTY_SIGNALS)) for n in nodes]+ node_responses = [to_graph_node(n, signals.get(n.node_id, EMPTY_SIGNALS)) for n in nodes]link_responses = [- _edge_response(e)+ edge_response(e)for e in edgesif e.source_node_id in reachable and e.target_node_id in reachable]@@ -265,12 +266,12 @@ async def dead_code_graph(neighbor_nodes = []all_node_ids = dead_node_ids | neighbor_ids- signals = await _collect_node_signals(session, repo_id, list(all_node_ids))+ signals = await collect_node_signals(session, repo_id, list(all_node_ids))def _to_dead_node(n: GraphNode, confidence_group: str) -> DeadCodeGraphNodeResponse:- return _node_to_response(+ return node_to_response(n,- signals.get(n.node_id, _EMPTY_SIGNALS),+ signals.get(n.node_id, EMPTY_SIGNALS),DeadCodeGraphNodeResponse,confidence_group=confidence_group,)@@ -293,7 +294,7 @@ async def dead_code_graph(and e.target_node_id in all_node_ids):seen.add(key)- link_responses.append(_edge_response(e))+ link_responses.append(edge_response(e))return DeadCodeGraphResponse(nodes=node_responses, links=link_responses)@@ -356,12 +357,12 @@ async def hot_files_graph(neighbor_nodes = []all_node_ids = hot_node_ids | neighbor_ids- signals = await _collect_node_signals(session, repo_id, list(all_node_ids))+ signals = await collect_node_signals(session, repo_id, list(all_node_ids))def _to_hot_node(n: GraphNode, commit_count: int) -> HotFilesNodeResponse:- return _node_to_response(+ return node_to_response(n,- signals.get(n.node_id, _EMPTY_SIGNALS),+ signals.get(n.node_id, EMPTY_SIGNALS),HotFilesNodeResponse,commit_count=commit_count,)@@ -370,6 +371,6 @@ async def hot_files_graph(_to_hot_node(n, 0) for n in neighbor_nodes]- link_responses = [_edge_response(e) for e in out_edges if e.target_node_id in all_node_ids]+ link_responses = [edge_response(e) for e in out_edges if e.target_node_id in all_node_ids]return HotFilesGraphResponse(nodes=node_responses, links=link_responses)diff --git a/packages/server/src/repowise/server/schemas/graph.py b/packages/server/src/repowise/server/schemas/graph.pyindex 821ff7539..ed95e7f91 100644--- a/packages/server/src/repowise/server/schemas/graph.py+++ b/packages/server/src/repowise/server/schemas/graph.py@@ -19,7 +19,7 @@ class GraphNodeResponse(BaseModel):is_test: bool = Falseis_entry_point: bool = Falsehas_doc: bool = False- # Cross-link signals (populated by _collect_node_signals)+ # Cross-link signals (populated by services.node_signals.collect_node_signals)is_hotspot: bool = Falsechurn_percentile: float | None = Noneis_dead: bool = Falsediff --git a/packages/server/src/repowise/server/services/c4_builder/serialize.py b/packages/server/src/repowise/server/services/c4_builder/serialize.pynew file mode 100644index 000000000..7be1e133b--- /dev/null+++ b/packages/server/src/repowise/server/services/c4_builder/serialize.py@@ -0,0 +1,146 @@+"""Architecture-view serialization — builder dataclasses → response models.++Pure functions (no FastAPI imports): the HTTP router and any non-HTTP+consumer — e.g. an indexer precomputing per-snapshot artifacts — call the+same code so both serving paths emit identical shapes+(``model_dump(mode="json")`` for the artifact form).+"""++from __future__ import annotations++from sqlalchemy.ext.asyncio import AsyncSession++from repowise.server.schemas import (+ ArchEdgeResponse,+ ArchitectureViewResponse,+ ArchLayerResponse,+ ArchNodeResponse,+ ArchSubGroupResponse,+ ArchTourStepResponse,+ C4ExternalSystemResponse,+)+from repowise.server.services.c4_builder.architecture import build_architecture_view+from repowise.server.services.c4_builder.models import (+ ArchEdge,+ ArchitectureView,+ ArchLayer,+ ArchNode,+ ArchTourStep,+ ExternalSystemView,+)+++def external_system_response(e: ExternalSystemView) -> C4ExternalSystemResponse:+ return C4ExternalSystemResponse(+ id=e.id,+ name=e.name,+ display_name=e.display_name,+ category=e.category,+ ecosystem=e.ecosystem,+ version=e.version,+ )+++def _arch_layer(layer: ArchLayer) -> ArchLayerResponse:+ return ArchLayerResponse(+ id=layer.id,+ name=layer.name,+ description=layer.description,+ node_ids=layer.node_ids,+ file_count=layer.file_count,+ complexity_distribution=layer.complexity_distribution,+ health_score=layer.health_score,+ sub_groups=[+ ArchSubGroupResponse(id=sg.id, name=sg.name, node_ids=sg.node_ids)+ for sg in layer.sub_groups+ ],+ display_order=layer.display_order,+ )+++def _arch_node(n: ArchNode) -> ArchNodeResponse:+ return ArchNodeResponse(+ id=n.id,+ node_type=n.node_type,+ name=n.name,+ file_path=n.file_path,+ line_range=list(n.line_range) if n.line_range else None,+ summary=n.summary,+ complexity=n.complexity,+ tags=n.tags,+ language=n.language,+ pagerank=n.pagerank,+ pagerank_percentile=n.pagerank_percentile,+ betweenness=n.betweenness,+ in_degree=n.in_degree,+ out_degree=n.out_degree,+ community_id=n.community_id,+ is_entry_point=n.is_entry_point,+ is_test=n.is_test,+ is_hotspot=n.is_hotspot,+ is_dead=n.is_dead,+ has_doc=n.has_doc,+ primary_owner=n.primary_owner,+ primary_owner_pct=n.primary_owner_pct,+ bus_factor=n.bus_factor,+ )+++def _arch_edge(e: ArchEdge) -> ArchEdgeResponse:+ return ArchEdgeResponse(+ source=e.source,+ target=e.target,+ edge_type=e.edge_type,+ direction=e.direction,+ weight=e.weight,+ confidence=e.confidence,+ )+++def _arch_tour_step(s: ArchTourStep) -> ArchTourStepResponse:+ return ArchTourStepResponse(+ order=s.order,+ title=s.title,+ description=s.description,+ node_ids=s.node_ids,+ target_path=s.target_path,+ layer_id=s.layer_id,+ reason=s.reason,+ depth=s.depth,+ kind=s.kind,+ page_type=s.page_type,+ )+++def architecture_view_response(view: ArchitectureView) -> ArchitectureViewResponse:+ """Serialize a built ArchitectureView into the API response model."""+ return ArchitectureViewResponse(+ project_name=view.project_name,+ project_description=view.project_description,+ layers=[_arch_layer(la) for la in view.layers],+ nodes=[_arch_node(n) for n in view.nodes],+ edges=[_arch_edge(e) for e in view.edges],+ tour=[_arch_tour_step(s) for s in view.tour],+ total_files=view.total_files,+ total_symbols=view.total_symbols,+ total_edges=view.total_edges,+ languages=view.languages,+ frameworks=view.frameworks,+ external_systems=[external_system_response(e) for e in view.external_systems],+ entry_points=view.entry_points,+ entry_candidates=view.entry_candidates,+ )+++async def build_architecture_view_response(+ session: AsyncSession,+ repo_id: str,+ include_symbols: bool = False,+) -> ArchitectureViewResponse:+ """Build + serialize the architecture view in one call.++ The single entry point for both the HTTP endpoint and artifact+ precomputation.+ """+ view = await build_architecture_view(session, repo_id, include_symbols=include_symbols)+ return architecture_view_response(view)diff --git a/packages/server/src/repowise/server/services/graph_views.py b/packages/server/src/repowise/server/services/graph_views.pynew file mode 100644index 000000000..6ba95bfd7--- /dev/null+++ b/packages/server/src/repowise/server/services/graph_views.py@@ -0,0 +1,264 @@+"""Community-level graph view builders — architecture super-graph + slice.++Pure service functions (no FastAPI imports): inputs are a DB session plus+query parameters, output is the exact response model the HTTP endpoints+serve. The graph routers are thin wrappers over these, and non-HTTP+consumers — e.g. an indexer precomputing per-snapshot artifacts — call the+SAME functions so both serving paths emit byte-identical shapes+(``model_dump(mode="json")`` for the artifact form).+"""++from __future__ import annotations++import json++from sqlalchemy import or_, select+from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.persistence import crud+from repowise.core.persistence.models import GraphEdge, GraphNode+from repowise.server.mcp_server._graph_utils import community_cohesion, community_label+from repowise.server.schemas import (+ ArchitectureEdgeResponse,+ ArchitectureGraphResponse,+ ArchitectureNodeResponse,+ CommunitySliceNodeResponse,+ CommunitySliceResponse,+ GraphEdgeResponse,+)+from repowise.server.services.node_signals import (+ EMPTY_SIGNALS,+ collect_node_signals,+ node_to_response,+)++# Cap on slice member nodes. Communities are small relative to the repo, but a+# few mega-clusters exist; this keeps the blossom payload in the 50-300 target+# band and the satellite layout responsive.+SLICE_MEMBER_CAP = 300+# Boundary stubs per slice: only the most-connected outside neighbors survive,+# so a blossom shows its strongest cross-cluster ties instead of a dust cloud.+SLICE_BOUNDARY_CAP = 40+# Chunk size for member-id IN lists. The slice edge filter ORs two IN clauses+# (source + target) in one statement, so we cap each chunk well under SQLite's+# 999-parameter limit to leave room for both lists plus the repo_id bind.+_SLICE_IN_CHUNK = 400+++def _parse_imported_names(raw: str | None) -> list[str]:+ if not raw:+ return []+ try:+ result = json.loads(raw)+ return result if isinstance(result, list) else []+ except (json.JSONDecodeError, ValueError):+ return []+++def edge_response(e: GraphEdge) -> GraphEdgeResponse:+ """Build a GraphEdgeResponse from a GraphEdge ORM row."""+ return GraphEdgeResponse(+ source=e.source_node_id,+ target=e.target_node_id,+ imported_names=_parse_imported_names(e.imported_names_json),+ )+++async def build_architecture_graph(+ session: AsyncSession,+ repo_id: str,+ min_members: int = 2,+) -> ArchitectureGraphResponse:+ """High-level architecture view: one node per detected community.++ Edges between communities are weighted by the number of underlying file+ edges that cross the boundary. Each super-node also carries signal counts+ (hotspots, dead files, decisions, doc coverage) so the architecture view+ surfaces health at a glance.+ """+ all_nodes = await crud.get_all_file_metrics(session, repo_id)+ if not all_nodes:+ return ArchitectureGraphResponse(nodes=[], edges=[])++ # Group file nodes by community+ buckets: dict[int, list[GraphNode]] = {}+ node_to_community: dict[str, int] = {}+ for n in all_nodes:+ cid = n.community_id if n.community_id is not None else 0+ buckets.setdefault(cid, []).append(n)+ node_to_community[n.node_id] = cid++ # Pull cross-link signals once for the whole repo so super-nodes can+ # aggregate hotspot/dead/decision counts without N round-trips.+ signals = await collect_node_signals(session, repo_id, [n.node_id for n in all_nodes])++ arch_nodes: list[ArchitectureNodeResponse] = []+ for cid, members in buckets.items():+ if len(members) < min_members:+ continue+ top = max(members, key=lambda m: m.pagerank or 0.0)+ hotspot_count = 0+ dead_count = 0+ has_decision = False+ doc_hits = 0+ langs: dict[str, int] = {}+ for m in members:+ sig = signals.get(m.node_id, EMPTY_SIGNALS)+ if sig.is_hotspot:+ hotspot_count += 1+ if sig.is_dead:+ dead_count += 1+ if sig.has_decision:+ has_decision = True+ if sig.has_doc:+ doc_hits += 1+ if m.language:+ langs[m.language] = langs.get(m.language, 0) + 1+ top_langs = [lang for lang, _ in sorted(langs.items(), key=lambda kv: -kv[1])[:3]]+ avg_pr = sum(m.pagerank or 0.0 for m in members) / max(len(members), 1)++ arch_nodes.append(+ ArchitectureNodeResponse(+ community_id=cid,+ label=community_label(top),+ cohesion=community_cohesion(top),+ member_count=len(members),+ top_file=top.node_id,+ avg_pagerank=avg_pr,+ hotspot_count=hotspot_count,+ dead_count=dead_count,+ has_decision=has_decision,+ doc_coverage_pct=doc_hits / max(len(members), 1),+ languages=top_langs,+ )+ )++ arch_nodes.sort(key=lambda a: -a.member_count)+ kept_communities = {a.community_id for a in arch_nodes}++ # Collapse cross-community edges+ edge_result = await session.execute(select(GraphEdge).where(GraphEdge.repository_id == repo_id))+ edge_counts: dict[tuple[int, int], int] = {}+ for e in edge_result.scalars():+ src_c = node_to_community.get(e.source_node_id)+ tgt_c = node_to_community.get(e.target_node_id)+ if src_c is None or tgt_c is None or src_c == tgt_c:+ continue+ if src_c not in kept_communities or tgt_c not in kept_communities:+ continue+ key = (src_c, tgt_c)+ edge_counts[key] = edge_counts.get(key, 0) + 1++ arch_edges = [+ ArchitectureEdgeResponse(source=s, target=t, edge_count=c)+ for (s, t), c in edge_counts.items()+ ]++ return ArchitectureGraphResponse(nodes=arch_nodes, edges=arch_edges)+++async def build_community_slice(+ session: AsyncSession,+ repo_id: str,+ community_id: int,+ member_limit: int = SLICE_MEMBER_CAP,+) -> CommunitySliceResponse:+ """Return a single community's sub-graph for the constellation blossom.++ Payload = the community's member file nodes, the edges among them, and a+ thin ring of one-hop *boundary stubs*: neighbor nodes outside the community+ that share an edge with a member, returned as minimal nodes flagged+ ``is_boundary=true`` so cross-cluster edges can render without dragging the+ whole neighbor cluster in. Sized to ~50-300 nodes.+ """+ members = await crud.get_community_members(+ session, repo_id, community_id, node_type="file", limit=member_limit + 1+ )+ truncated = len(members) > member_limit+ if truncated:+ members = members[:member_limit]+ member_ids = {m.node_id for m in members}++ # Edges touching any member: among-members stay; member<->outside become+ # cross-cluster links that pull in a boundary stub for the outside endpoint.+ # The membership filter is pushed into SQL (source OR target in members) so+ # we never load the whole repo's edge table into Python; the IN lists are+ # chunked under SQLite's parameter limit. The Python filter below is kept+ # as-is for correctness — the SQL only bounds the rows fetched (a+ # superset-or-equal of what the Python filter keeps).+ member_id_list = list(member_ids)+ edge_rows: dict[str, GraphEdge] = {}+ for start in range(0, len(member_id_list), _SLICE_IN_CHUNK):+ chunk = member_id_list[start : start + _SLICE_IN_CHUNK]+ chunk_result = await session.execute(+ select(GraphEdge).where(+ GraphEdge.repository_id == repo_id,+ or_(+ GraphEdge.source_node_id.in_(chunk),+ GraphEdge.target_node_id.in_(chunk),+ ),+ )+ )+ # Dedup across chunks: an edge whose endpoints fall in different chunks+ # matches twice. The PK keeps each edge once.+ for e in chunk_result.scalars():+ edge_rows[e.id] = e++ kept_edges: list[GraphEdge] = []+ boundary_degree: dict[str, int] = {}+ for e in edge_rows.values():+ src_in = e.source_node_id in member_ids+ tgt_in = e.target_node_id in member_ids+ if not src_in and not tgt_in:+ continue+ kept_edges.append(e)+ if not src_in:+ boundary_degree[e.source_node_id] = boundary_degree.get(e.source_node_id, 0) + 1+ if not tgt_in:+ boundary_degree[e.target_node_id] = boundary_degree.get(e.target_node_id, 0) + 1++ # Cap boundary stubs to the most-connected neighbors: hub communities can+ # touch thousands of outside files, which would flood the blossom with+ # dust. Edges to dropped stubs are filtered by the visible_ids pass below.+ boundary_ids = set(+ sorted(boundary_degree, key=lambda n: (-boundary_degree[n], n))[:SLICE_BOUNDARY_CAP]+ )++ # Resolve boundary stub rows (minimal: just need a node row to render).+ boundary_nodes: list[GraphNode] = []+ if boundary_ids:+ stub_result = await session.execute(+ select(GraphNode).where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_id.in_(boundary_ids),+ )+ )+ boundary_nodes = list(stub_result.scalars().all())+ resolved_boundary = {n.node_id for n in boundary_nodes}++ # Drop edges whose outside endpoint has no resolvable node (orphan ref).+ visible_ids = member_ids | resolved_boundary+ links = [+ edge_response(e)+ for e in kept_edges+ if e.source_node_id in visible_ids and e.target_node_id in visible_ids+ ]++ # Member signals only (boundary stubs stay minimal / all-false signals).+ signals = await collect_node_signals(session, repo_id, list(member_ids))+ nodes = [+ node_to_response(m, signals.get(m.node_id, EMPTY_SIGNALS), CommunitySliceNodeResponse)+ for m in members+ ]+ nodes.extend(+ node_to_response(n, EMPTY_SIGNALS, CommunitySliceNodeResponse, is_boundary=True)+ for n in boundary_nodes+ )++ return CommunitySliceResponse(+ nodes=nodes,+ links=links,+ community_id=community_id,+ member_count=len(members),+ truncated=truncated,+ )diff --git a/packages/server/src/repowise/server/routers/graph/signals.py b/packages/server/src/repowise/server/services/node_signals.pysimilarity index 93%rename from packages/server/src/repowise/server/routers/graph/signals.pyrename to packages/server/src/repowise/server/services/node_signals.pyindex fb140cc07..d4da1c884 100644--- a/packages/server/src/repowise/server/routers/graph/signals.py+++ b/packages/server/src/repowise/server/services/node_signals.py@@ -3,6 +3,9 @@Joins git metadata, dead-code findings, decisions, and docs into one map sothe graph endpoints can annotate nodes without N round-trips, and converts a``GraphNode`` + its signals into the various node response models.++Lives in the service layer (no FastAPI imports) so non-HTTP consumers — e.g.+an indexer precomputing graph artifacts — can reuse the same join logic."""from __future__ import annotations@@ -46,10 +49,10 @@ class NodeSignals:self.has_doc: bool = False-_EMPTY_SIGNALS = NodeSignals()+EMPTY_SIGNALS = NodeSignals()-async def _collect_node_signals(+async def collect_node_signals(session: AsyncSession,repo_id: str,node_ids: list[str] | None = None,@@ -128,7 +131,7 @@ async def _collect_node_signals(_NodeResponseT = TypeVar("_NodeResponseT")-def _node_to_response(+def node_to_response(n: GraphNode,sig: NodeSignals,response_cls: type[_NodeResponseT],@@ -160,6 +163,6 @@ def _node_to_response()-def _to_graph_node(n: GraphNode, signals: NodeSignals) -> GraphNodeResponse:+def to_graph_node(n: GraphNode, signals: NodeSignals) -> GraphNodeResponse:"""Build a GraphNodeResponse from a GraphNode + its collected signals."""- return _node_to_response(n, signals, GraphNodeResponse)+ return node_to_response(n, signals, GraphNodeResponse)diff --git a/packages/ui/__tests__/brand.test.ts b/packages/ui/__tests__/brand.test.tsnew file mode 100644index 000000000..f5ea1b7b5--- /dev/null+++ b/packages/ui/__tests__/brand.test.ts@@ -0,0 +1,66 @@+import { describe, it, expect } from "vitest";+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { BRAND, LIGHT, DARK, GRADIENTS } from "../src/brand.js";++// styles/globals.css is the single source of truth for the token system;+// the brand constants exist for surfaces that can't resolve CSS vars. This+// suite pins them together so a token retune can't silently strand the+// OG/email/badge values.+const css = readFileSync(join(__dirname, "../styles/globals.css"), "utf8");++// Whitespace-insensitive view of the stylesheet so a gradient reformat+// (line breaks, spacing after commas) doesn't break the drift guard.+const cssNormalized = css.toLowerCase().replace(/\s+/g, " ");++function escapeRegExp(s: string): string {+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++// A hex literal must appear bounded: #f59520 should not match inside+// #f59520ab (a longer, different color).+function expectHex(value: string): void {+ const re = new RegExp(escapeRegExp(value) + "(?![0-9a-f])", "i");+ expect(css).toMatch(re);+}++// Gradient strings are compared whitespace-insensitively against the+// stylesheet so only the colors/structure are pinned, not CSS formatting.+function expectGradient(value: string): void {+ const needle = value.toLowerCase().replace(/\s+/g, " ").trim();+ expect(cssNormalized).toContain(needle);+}++describe("brand constants stay in sync with styles/globals.css", () => {+ it("brand identity values appear in the stylesheet", () => {+ for (const value of Object.values(BRAND)) {+ expectHex(value);+ }+ });++ it("light surface/text values appear in the stylesheet", () => {+ for (const value of Object.values(LIGHT)) {+ expectHex(value);+ }+ });++ it("dark surface/text values appear in the stylesheet", () => {+ for (const value of Object.values(DARK)) {+ expectHex(value);+ }+ });++ it("gradients match the stylesheet definitions", () => {+ for (const value of Object.values(GRADIENTS)) {+ expectGradient(value);+ }+ });+});++describe("brand module purity", () => {+ it("has no imports (dependency-free by contract)", () => {+ const src = readFileSync(join(__dirname, "../src/brand.ts"), "utf8");+ expect(src).not.toMatch(/^\s*import\s/m);+ expect(src).not.toMatch(/\brequire\s*\(/);+ });+});diff --git a/packages/ui/__tests__/shared/owl-loader.test.tsx b/packages/ui/__tests__/shared/owl-loader.test.tsxnew file mode 100644index 000000000..657e601b4--- /dev/null+++ b/packages/ui/__tests__/shared/owl-loader.test.tsx@@ -0,0 +1,66 @@+import { describe, it, expect, vi } from "vitest";+import { render, screen, waitFor } from "@testing-library/react";+import { OwlLoader } from "../../src/shared/owl-loader.js";++// Capture the loadError handler the component registers so tests can+// trigger the fallback path without a real Lottie runtime.+const listeners: Record<string, () => void> = {};+vi.mock("@lottiefiles/dotlottie-react", () => ({+ DotLottieReact: ({+ src,+ style,+ dotLottieRefCallback,+ }: {+ src: string;+ style?: Record<string, unknown>;+ dotLottieRefCallback?: (dotLottie: unknown) => void;+ }) => {+ dotLottieRefCallback?.({+ addEventListener: (event: string, handler: () => void) => {+ listeners[event] = handler;+ },+ });+ return <div data-testid="lottie" data-src={src} style={style} />;+ },+}));++describe("OwlLoader", () => {+ it("renders the animation with the default asset path and label", () => {+ render(<OwlLoader />);++ expect(screen.getByRole("status", { name: "Loading…" })).toBeInTheDocument();+ expect(screen.getByTestId("lottie")).toHaveAttribute(+ "data-src",+ "/owl-loading.json",+ );+ expect(screen.getByText("Loading…")).toBeInTheDocument();+ });++ it("passes a custom asset path and size through to the animation", () => {+ render(<OwlLoader src="/assets/owl.json" size={80} label="Crunching…" />);++ const lottie = screen.getByTestId("lottie");+ expect(lottie).toHaveAttribute("data-src", "/assets/owl.json");+ expect(lottie).toHaveStyle({ width: "80px", height: "80px" });+ expect(screen.getByRole("status", { name: "Crunching…" })).toBeInTheDocument();+ });++ it("falls back to the brand mark when the animation fails to load", async () => {+ render(+ <OwlLoader logoDarkSrc="/logo-dark.png" logoLightSrc="/logo-light.png" />,+ );++ listeners.loadError?.();++ await waitFor(() => {+ expect(screen.queryByTestId("lottie")).not.toBeInTheDocument();+ });+ // BrandMark renders both theme variants; visibility is CSS-only.+ const imgs = document.querySelectorAll("img");+ const srcs = Array.from(imgs).map((img) => img.getAttribute("src"));+ expect(srcs).toContain("/logo-light.png");+ expect(srcs).toContain("/logo-dark.png");+ // The loading state stays announced even on the fallback path.+ expect(screen.getByRole("status", { name: "Loading…" })).toBeInTheDocument();+ });+});diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 943a86442..d39e2e0f3 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -5,7 +5,11 @@"type": "module","main": "./src/index.ts","types": "./src/index.ts",- "files": ["src", "styles"],+ "files": [+ "src",+ "styles",+ "scripts"+ ],"sideEffects": ["./styles/globals.css","**/*.css"@@ -13,6 +17,7 @@"exports": {".": "./src/index.ts","./styles.css": "./styles/globals.css",+ "./brand": "./src/brand.ts","./graph": "./src/graph/index.ts","./graph/context": "./src/graph/context.ts","./graph/elk-layout": "./src/graph/elk-layout.ts",@@ -87,9 +92,11 @@},"scripts": {"type-check": "tsc --noEmit",- "test": "vitest run"+ "test": "vitest run",+ "gates": "bash ./scripts/ui-gates.sh"},"dependencies": {+ "@lottiefiles/dotlottie-react": "^0.19.4","@radix-ui/react-dialog": "^1.1.15","@radix-ui/react-hover-card": "^1.1.15","@radix-ui/react-label": "^2.1.8",@@ -108,8 +115,8 @@"class-variance-authority": "^0.7.1","clsx": "^2.1.1","d3-force": "^3.0.0",- "elkjs": "^0.11.1","d3-hierarchy": "^3.1.2",+ "elkjs": "^0.11.1","framer-motion": "^11.11.0","fuse.js": "^7.0.0","graphology": "^0.26.0",@@ -143,5 +150,10 @@"react-dom": "^19.0.0","typescript": "^5.6.0","vitest": "^4.1.5"+ },+ "bin": {+ "repowise-ui-gates": "./scripts/ui-gates.sh",+ "repowise-ui-no-raw-hex": "./scripts/no-raw-hex-check.sh",+ "repowise-ui-contrast-check": "./scripts/contrast-check.py"}}diff --git a/packages/ui/scripts/contrast-check.py b/packages/ui/scripts/contrast-check.pynew file mode 100755index 000000000..d9c56af17--- /dev/null+++ b/packages/ui/scripts/contrast-check.py@@ -0,0 +1,278 @@+#!/usr/bin/env python3+"""Theme tokens — WCAG contrast verification (design gate).++Computes WCAG 2.1 relative-luminance contrast ratios for every critical+text/surface, accent-on-surface, and status pair in both light and dark+modes, and asserts the floors from the redesign plan:++ - body text on primary surfaces >= 7.0 (AAA)+ - secondary text / large text / status >= 4.5 (AA)+ - interactive / non-text UI >= 3.0++Semi-transparent tokens (borders, muted fills) are alpha-composited over+their surface before the ratio is computed, so the numbers reflect what a+user actually sees.++This gate ships with the ui package so every consumer verifies the SAME+canonical token set. Consumers extend (never fork) via JSON config:++ contrast-check.py [--extend config.json ...]++where config.json may contain:++ {+ "light": { "token-name": "#RRGGBB or rgba(...)" , ... },+ "dark": { "token-name": "..." , ... },+ "checks": [ ["fg-token", "bg-token", 4.5, "Label"], ... ]+ }++Extension tokens are merged into the base palettes (consumer-only tokens+should use fresh names; redefining a canonical token is allowed but means+the consumer has diverged — prefer not to). Extension checks are appended+to the base check list and run in both modes.++Exits non-zero if any required pair misses its floor (CI gate).+"""+from __future__ import annotations++import argparse+import json+import re+import sys+++# --------------------------------------------------------------------------+# Color helpers+# --------------------------------------------------------------------------+def _hex_to_rgb(h: str) -> tuple[float, float, float]:+ h = h.lstrip("#")+ if len(h) == 3:+ h = "".join(c * 2 for c in h)+ return tuple(int(h[i : i + 2], 16) / 255 for i in (0, 2, 4))+++def _parse(color: str) -> tuple[float, float, float, float]:+ """Return (r, g, b, alpha) in 0..1 from a hex or rgba() string."""+ color = color.strip()+ if color.startswith("#"):+ r, g, b = _hex_to_rgb(color)+ return r, g, b, 1.0+ m = re.match(r"rgba?\(([^)]+)\)", color)+ if not m:+ raise ValueError(f"unparseable color: {color}")+ parts = [p.strip() for p in m.group(1).split(",")]+ r, g, b = (int(parts[i]) / 255 for i in range(3))+ a = float(parts[3]) if len(parts) > 3 else 1.0+ return r, g, b, a+++def _composite(fg: str, bg: str) -> tuple[float, float, float]:+ """Alpha-composite fg over an opaque bg, return opaque rgb."""+ fr, fg_, fb, fa = _parse(fg)+ br, bg_, bb, _ = _parse(bg)+ return (+ fr * fa + br * (1 - fa),+ fg_ * fa + bg_ * (1 - fa),+ fb * fa + bb * (1 - fa),+ )+++def _lin(c: float) -> float:+ return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4+++def _lum(rgb: tuple[float, float, float]) -> float:+ r, g, b = (_lin(c) for c in rgb)+ return 0.2126 * r + 0.7152 * g + 0.0722 * b+++def contrast(fg: str, bg: str) -> float:+ """WCAG contrast ratio of fg over (opaque) bg, compositing alpha first."""+ fg_rgb = _composite(fg, bg)+ bg_rgb = _composite(bg, bg)+ l1, l2 = _lum(fg_rgb), _lum(bg_rgb)+ hi, lo = max(l1, l2), min(l1, l2)+ return (hi + 0.05) / (lo + 0.05)+++# --------------------------------------------------------------------------+# Token values (must mirror packages/ui/styles/globals.css)+# --------------------------------------------------------------------------+LIGHT = {+ "bg-root": "#FBF6F1",+ "bg-surface": "#FFFFFF",+ "bg-elevated": "#FBF4EE",+ "bg-inset": "#F4EAE1",+ "bg-canvas": "#F4EAE1", # --color-bg-canvas → var(--color-bg-inset)+ "text-primary": "#241B2C",+ "text-secondary": "#5E5360",+ "text-tertiary": "#8C7F88",+ "text-inverse": "#FFFFFF",+ "text-on-accent": "#241B2C",+ "accent-primary": "#A16215",+ "accent-fill": "#F59520",+ "accent-secondary": "#58436C",+ "border-default": "rgba(88,67,108,0.12)",+ "border-active": "rgba(176,107,18,0.90)",+ "success": "#1D8155",+ "warning": "#9A6614",+ "error": "#B23A2E",+ "info": "#58436C",+ # Blueprint diagram ink (light) — KG canvas + mermaid.+ "diagram-node-fill": "#241B2C",+ "diagram-node-fill-2": "#4A4152",+ "diagram-node-text": "#FBF6F1",+ "diagram-node-border": "#241B2C",+ "gradient-ember-end": "#F7A94D",+ # KG node faces (light) — paper cards with ink outline.+ "kg-node-fill": "#FFFDF8",+ "kg-node-fill-2": "#F3ECE2",+ "kg-node-text": "#241B2C",+ "kg-node-border": "#241B2C",+ "kg-node-border-2": "#8C7F88",+ # Textured face composite: 0.78 warm-white wash over the paper photo+ # (avg ~#E6E8E9) — what text actually sits on.+ "kg-node-face-textured": "#FAF8F4",+ # Community family hubs (light) — graph clustering palette.+ "community-1": "#C0641A", "community-2": "#58436C", "community-3": "#B23A2E",+ "community-4": "#6B7A3D", "community-5": "#B06A86", "community-6": "#4A5D7A",+ "community-7": "#A8821F", "community-8": "#8A7A66", "community-9": "#7A2F4A",+ "community-10": "#B85A38", "community-11": "#2F6B66", "community-12": "#5E5360",+}++DARK = {+ "bg-root": "#17131D",+ "bg-surface": "#211B29",+ "bg-elevated": "#2A2335",+ "bg-inset": "#110D17",+ "bg-canvas": "#110D17", # --color-bg-canvas → var(--color-bg-inset)+ "text-primary": "#EEEAF4",+ "text-secondary": "#A79DB3",+ "text-tertiary": "#786F84",+ "text-inverse": "#17131D",+ "text-on-accent": "#17131D",+ "accent-primary": "#F59520",+ "accent-fill": "#F59520",+ "accent-secondary": "#A98FC4",+ "border-default": "rgba(213,197,232,0.10)",+ "border-active": "rgba(245,149,32,0.55)",+ "success": "#34D399",+ "warning": "#F2A03D",+ "error": "#E06A5A",+ "info": "#A98FC4",+ # Blueprint diagram ink (dark) — border carries canvas separation.+ "diagram-node-fill": "#322A3E",+ "diagram-node-fill-2": "#261F30",+ "diagram-node-text": "#EEEAF4",+ "diagram-node-border": "rgba(222,210,235,0.45)",+ "gradient-ember-end": "#F7A94D",+ # KG node faces (dark) — alias back to the solid ink blocks.+ "kg-node-fill": "#322A3E",+ "kg-node-fill-2": "#261F30",+ "kg-node-text": "#EEEAF4",+ "kg-node-border": "rgba(222,210,235,0.45)",+ "kg-node-border-2": "rgba(222,210,235,0.45)",+ # Textured face composite: 0.85 ink wash (#322A3E) over the paper photo.+ "kg-node-face-textured": "#4D4658",+ # Community family hubs (dark) — lifted to read on the near-black canvas.+ "community-1": "#F59520", "community-2": "#A98FC4", "community-3": "#E06A5A",+ "community-4": "#A9BB6F", "community-5": "#D795B1", "community-6": "#8FA3C0",+ "community-7": "#D9B04A", "community-8": "#B8A68E", "community-9": "#C4708F",+ "community-10": "#EBA585", "community-11": "#6FB3AB", "community-12": "#A79DB3",+}++# (fg, bg, floor, label) — floor is the WCAG ratio the pair must meet.+CHECKS = [+ ("text-primary", "bg-root", 7.0, "Body text on page"),+ ("text-primary", "bg-surface", 7.0, "Body text on card"),+ ("text-primary", "bg-elevated", 7.0, "Body text on elevated"),+ ("text-secondary", "bg-root", 4.5, "Secondary text on page"),+ ("text-secondary", "bg-surface", 4.5, "Secondary text on card"),+ ("text-tertiary", "bg-surface", 3.0, "Tertiary/hint on card"),+ ("accent-primary", "bg-surface", 4.5, "Accent text on card"),+ ("accent-primary", "bg-root", 4.5, "Accent text on page"),+ ("accent-secondary", "bg-surface", 4.5, "Plum link-alt on card"),+ ("text-on-accent", "accent-fill", 4.5, "Text on accent fill (CTA)"),+ ("text-inverse", "accent-primary", 4.5, "Text on accent-primary fill"),+ ("success", "bg-surface", 4.5, "Success text on card"),+ ("warning", "bg-surface", 4.5, "Warning text on card"),+ ("error", "bg-surface", 4.5, "Error text on card"),+ ("info", "bg-surface", 4.5, "Info text on card"),+ ("border-active", "bg-surface", 3.0, "Active border on card"),+ # Blueprint ink nodes (KG canvas): text on both ink weights; the node+ # boundary (fill in light, border in dark) must separate from the canvas.+ ("diagram-node-text", "diagram-node-fill", 4.5, "Ink node text on primary fill"),+ ("diagram-node-text", "diagram-node-fill-2", 4.5, "Ink node text on secondary fill"),+ ("diagram-node-border", "bg-canvas", 3.0, "Ink node boundary on canvas"),+ ("kg-node-text", "kg-node-fill", 4.5, "KG card text on primary face"),+ ("kg-node-text", "kg-node-fill-2", 4.5, "KG card text on secondary face"),+ ("kg-node-border", "bg-canvas", 3.0, "KG card outline on canvas"),+ ("kg-node-border-2", "bg-canvas", 3.0, "KG supporting outline on canvas"),+ ("kg-node-text", "kg-node-face-textured", 4.5, "KG card text on textured face"),+ ("text-on-accent", "gradient-ember-end", 4.5, "Text on ember gradient end"),+ # Community hubs are non-text node fills on the graph canvas — floor 3.0:1.+ *[+ (f"community-{n}", "bg-canvas", 3.0, f"Community {n} hub on canvas")+ for n in range(1, 13)+ ],+]+++def _load_extensions(paths: list[str]) -> tuple[dict, dict, list]:+ """Merge extension configs: extra tokens per mode + extra checks."""+ light, dark, checks = dict(LIGHT), dict(DARK), list(CHECKS)+ for path in paths:+ with open(path, encoding="utf-8") as f:+ ext = json.load(f)+ light.update(ext.get("light", {}))+ dark.update(ext.get("dark", {}))+ for entry in ext.get("checks", []):+ fg, bg, floor, label = entry+ checks.append((fg, bg, float(floor), label))+ return light, dark, checks+++def run(extend: list[str]) -> int:+ light, dark, checks = _load_extensions(extend)+ failures = 0+ rows: list[str] = []+ for mode, tokens in (("Light", light), ("Dark", dark)):+ rows.append(f"\n### {mode} mode\n")+ rows.append("| Pair | Ratio | Floor | Result |")+ rows.append("|------|-------|-------|--------|")+ for fg, bg, floor, label in checks:+ try:+ ratio = contrast(tokens[fg], tokens[bg])+ except KeyError as e:+ print(+ f"contrast gate config error: token {e} not defined for "+ f"{mode.lower()} mode (check '{label}'). Extension configs "+ "must define referenced tokens in BOTH light and dark.",+ file=sys.stderr,+ )+ return 2+ ok = ratio >= floor+ if not ok:+ failures += 1+ mark = "PASS" if ok else "**FAIL**"+ rows.append(f"| {label} | {ratio:.2f} | {floor:.1f} | {mark} |")+ print("\n".join(rows))+ print(f"\n**Total pairs:** {len(checks) * 2} · **Failures:** {failures}")+ return 1 if failures else 0+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument(+ "--extend",+ action="append",+ default=[],+ metavar="JSON",+ help="JSON file adding consumer tokens (light/dark maps) and checks; repeatable",+ )+ args = parser.parse_args()+ return run(args.extend)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/packages/ui/scripts/no-raw-hex-check.sh b/packages/ui/scripts/no-raw-hex-check.shnew file mode 100755index 000000000..9c52c2c90--- /dev/null+++ b/packages/ui/scripts/no-raw-hex-check.sh@@ -0,0 +1,86 @@+#!/usr/bin/env bash+#+# no-raw-hex gate (design tokens) — fails if a raw hex color literal appears+# in the scan root OUTSIDE the allowlist below. Wire into CI.+#+# This gate ships with the ui package so every consumer enforces the SAME+# token discipline over its own source tree. Consumers extend (never fork)+# via flags:+#+# no-raw-hex-check.sh [--root DIR] [--allow REGEX]...+#+# --root DIR directory to scan (default: this package's src/)+# --allow REGEX extra allowlist entry, matched against the file path;+# repeatable. Document every entry at the call site.+#+# The base allowlist has two kinds of entries:+# * BRAND/STRUCTURAL — hex that must stay literal because it's an identity+# color or is consumed where a CSS var() cannot resolve (e.g. <canvas>).+# * DEFERRED-VIZ — viz subsystems whose theme-aware tokenization needs+# runtime CSS-var resolution + visual QA; tracked as follow-up. Listed+# explicitly so the gate stays honest (it is NOT silently ignoring them).+#+# Everything else — charts, badges, tooltips, treemaps, shared/primitives —+# must route color through the design tokens. New raw hex there fails CI.+set -euo pipefail++# Resolve through the npm .bin symlink so the default scan root points at the+# package's own src/ even when invoked as `repowise-ui-no-raw-hex`.+SELF="${BASH_SOURCE[0]}"+while [ -L "$SELF" ]; do+ target="$(readlink "$SELF")"+ case "$target" in+ /*) SELF="$target" ;;+ *) SELF="$(dirname "$SELF")/$target" ;;+ esac+done+PKG_DIR="$(cd "$(dirname "$SELF")/.." && pwd)"+ROOT="$PKG_DIR/src"++# Files/dirs allowed to contain raw hex (regex, matched against the path).+ALLOW='(__tests__|\.test\.)' # test fixtures+ALLOW+='|src/brand\.ts' # BRAND: canonical constants for var()-less surfaces (OG/email/badge)+ALLOW+='|lib/confidence\.ts' # BRAND: LANGUAGE/EDGE color hex (canvas)+ALLOW+='|costs/provider-comparison\.tsx' # BRAND: provider identity colors+ALLOW+='|workspace/workspace-graph-node\.tsx' # dynamic langColor hex-alpha concat+ALLOW+='|graph-primitives/tone-styles\.ts' # BRAND: categorical node-tone palette (like lang colors)+ALLOW+='|wiki/git-history-panel\.tsx' # BRAND: per-author categorical bar colors+# DEFERRED-VIZ — canvas subsystems with their own runtime light/dark palette+# (driven by the global theme), pending an aesthetic warm-palette retune:+ALLOW+='|c4/export/svg-exporter\.ts' # SVG serializer resolves LIVE theme tokens; hex are headless-export fallbacks only (kg-ux B7)+ALLOW+='|/graph/sigma/' # Sigma canvas renderer (internal light/dark palette)++while [ $# -gt 0 ]; do+ case "$1" in+ --root)+ ROOT="$2"; shift 2 ;;+ --allow)+ ALLOW+="|$2"; shift 2 ;;+ -h|--help)+ sed -n '2,24p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'+ exit 0 ;;+ *)+ echo "unknown argument: $1" >&2+ exit 2 ;;+ esac+done++if [ ! -d "$ROOT" ]; then+ echo "no-raw-hex gate: scan root not found: $ROOT" >&2+ exit 2+fi++violations=$(grep -rnE '#[0-9a-fA-F]{3,8}\b' "$ROOT" 2>/dev/null \+ | grep -vE "$ALLOW" || true)++if [ -n "$violations" ]; then+ echo "no-raw-hex gate FAILED — raw hex outside the token system:"+ echo "$violations"+ echo+ echo "Route color through a design token (var(--color-*)), or add a"+ echo "documented allowlist entry if it is a brand/canvas constant."+ exit 1+fi++echo "no-raw-hex gate passed — cleaned surfaces route color through tokens."+echo "(Deferred viz subsystems are allowlisted; see this script's header.)"diff --git a/packages/ui/scripts/ui-gates.sh b/packages/ui/scripts/ui-gates.shnew file mode 100755index 000000000..60547986a--- /dev/null+++ b/packages/ui/scripts/ui-gates.sh@@ -0,0 +1,50 @@+#!/usr/bin/env bash+#+# ui-gates — run both design gates (no-raw-hex + contrast) in one command.+#+# ui-gates [--root DIR] [--allow REGEX]... [--contrast-extend JSON]...+#+# --root DIR scan root for the no-raw-hex gate+# (default: this package's src/)+# --allow REGEX extra no-raw-hex allowlist entry; repeatable+# --contrast-extend JSON consumer token/check extension file for the+# contrast gate; repeatable+#+# Exits non-zero if either gate fails. Consumers wire this into CI from+# node_modules so both products enforce the same canonical token rules.+set -euo pipefail++# Resolve through the npm .bin symlink so the sibling gate scripts are+# found when invoked as `repowise-ui-gates` from a consumer repo.+SELF="${BASH_SOURCE[0]}"+while [ -L "$SELF" ]; do+ target="$(readlink "$SELF")"+ case "$target" in+ /*) SELF="$target" ;;+ *) SELF="$(dirname "$SELF")/$target" ;;+ esac+done+SCRIPT_DIR="$(cd "$(dirname "$SELF")" && pwd)"++hex_args=()+contrast_args=()+while [ $# -gt 0 ]; do+ case "$1" in+ --root|--allow)+ hex_args+=("$1" "$2"); shift 2 ;;+ --contrast-extend)+ contrast_args+=(--extend "$2"); shift 2 ;;+ -h|--help)+ sed -n '2,15p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'+ exit 0 ;;+ *)+ echo "unknown argument: $1" >&2+ exit 2 ;;+ esac+done++echo "== no-raw-hex gate =="+bash "$SCRIPT_DIR/no-raw-hex-check.sh" ${hex_args[@]+"${hex_args[@]}"}+echo+echo "== contrast gate =="+python3 "$SCRIPT_DIR/contrast-check.py" ${contrast_args[@]+"${contrast_args[@]}"}diff --git a/packages/ui/src/brand.ts b/packages/ui/src/brand.tsnew file mode 100644index 000000000..5aac5f0fb--- /dev/null+++ b/packages/ui/src/brand.ts@@ -0,0 +1,67 @@+/**+ * Canonical brand constants — for surfaces that cannot resolve CSS variables+ * (OG image routes, transactional emails, badge SVGs, terminal output).+ *+ * Values mirror styles/globals.css, the single source of truth for the token+ * system; in-app UI must keep using `var(--color-*)` tokens. This module is+ * deliberately dependency-free (no imports at all) so edge runtimes and email+ * renderers can pull it in without dragging any UI weight.+ */++/** Brand identity. */+export const BRAND = {+ /** Accent orange — the brand fill (CTAs, owl eyes, highlights). */+ accent: "#f59520",+ /** Accent text on light surfaces (darkened for 4.5:1 contrast). */+ accentTextLight: "#a16215",+ /** Brand plum — logo strokes on light surfaces, secondary accent. */+ plum: "#473659",+ /** Plum near-black — primary ink on warm paper. */+ ink: "#241b2c",+ /** Warm paper — the light-mode page background. */+ paper: "#fbf6f1",+ /** Cream — the logo stroke color on dark surfaces. */+ cream: "#fce9dd",+} as const;++/** Light-mode surface/text values (the product default). */+export const LIGHT = {+ bgRoot: "#fbf6f1",+ bgSurface: "#ffffff",+ bgElevated: "#fbf4ee",+ bgInset: "#f4eae1",+ textPrimary: "#241b2c",+ textSecondary: "#5e5360",+ textTertiary: "#8c7f88",+ accentPrimary: "#a16215",+ accentFill: "#f59520",+ accentSecondary: "#58436c",+ success: "#1d8155",+ warning: "#9a6614",+ error: "#b23a2e",+} as const;++/** Dark-mode surface/text values. */+export const DARK = {+ bgRoot: "#17131d",+ bgSurface: "#211b29",+ bgElevated: "#2a2335",+ bgInset: "#110d17",+ textPrimary: "#eeeaf4",+ textSecondary: "#a79db3",+ textTertiary: "#786f84",+ accentPrimary: "#f59520",+ accentFill: "#f59520",+ accentSecondary: "#a98fc4",+ success: "#34d399",+ warning: "#f2a03d",+ error: "#e06a5a",+} as const;++/** Signature gradients (CSS gradient strings) for hero/OG canvases. */+export const GRADIENTS = {+ sunset: "linear-gradient(135deg, #58436c 0%, #f59520 55%, #f7a94d 100%)",+ ember: "linear-gradient(135deg, #f59520 0%, #f7a94d 100%)",+ peach: "linear-gradient(160deg, #ffc4b1 0%, #f59520 100%)",+ warm: "linear-gradient(135deg, #f59520 0%, #ffd9b0 100%)",+} as const;diff --git a/packages/ui/src/shared/index.ts b/packages/ui/src/shared/index.tsindex 9a4dfaed3..f564b0cb2 100644--- a/packages/ui/src/shared/index.ts+++ b/packages/ui/src/shared/index.ts@@ -2,6 +2,7 @@ export * from "./api-error";export { BrandMark, type BrandMarkProps } from "./brand-mark";export * from "./breadcrumb";export * from "./empty-state";+export { OwlLoader, type OwlLoaderProps } from "./owl-loader";export * from "./stat-card";export * from "./results-footer";export { RowActions, type RowAction } from "./row-actions";diff --git a/packages/web/src/components/shared/owl-loader.tsx b/packages/ui/src/shared/owl-loader.tsxsimilarity index 60%rename from packages/web/src/components/shared/owl-loader.tsxrename to packages/ui/src/shared/owl-loader.tsxindex ba7186c8a..55cf464ae 100644--- a/packages/web/src/components/shared/owl-loader.tsx+++ b/packages/ui/src/shared/owl-loader.tsx@@ -1,24 +1,35 @@"use client";import { useState } from "react";-import Image from "next/image";import { DotLottieReact } from "@lottiefiles/dotlottie-react";-import { cn } from "@repowise-dev/ui/lib/cn";+import { cn } from "../lib/cn";+import { BrandMark } from "./brand-mark";++export interface OwlLoaderProps {+ /** Path to the owl Lottie asset, served from the consuming app's public/. */+ src?: string;+ /** Fallback brand-mark assets, shown if the animation fails to load. */+ logoDarkSrc?: string;+ logoLightSrc?: string;+ size?: number;+ label?: string;+ className?: string;+}/*** Brand loading animation — the owl Lottie, centered. Falls back to a* pulsing static brand mark if the animation asset fails to load, so a- * missing /owl-loading.lottie never breaks a loading state.+ * missing lottie asset never breaks a loading state. The asset itself stays+ * per-app (lazy-fetched, CDN-cached) — only the component is shared.*/export function OwlLoader({+ src = "/owl-loading.json",+ logoDarkSrc = "/repowise-logo.png",+ logoLightSrc = "/repowise-logo-light.png",size = 160,label = "Loading…",className,-}: {- size?: number;- label?: string;- className?: string;-}) {+}: OwlLoaderProps) {const [failed, setFailed] = useState(false);return (@@ -32,26 +43,16 @@ export function OwlLoader({>{failed ? (<span className="motion-safe:animate-pulse">- <Image- src="/repowise-logo-light.png"- alt=""- aria-hidden- width={size * 0.6}- height={size * 0.6}- className="dark:hidden"- />- <Image- src="/repowise-logo.png"+ <BrandMark+ darkSrc={logoDarkSrc}+ lightSrc={logoLightSrc}+ size={size * 0.6}alt=""- aria-hidden- width={size * 0.6}- height={size * 0.6}- className="hidden dark:block"/></span>) : (<DotLottieReact- src="/owl-loading.json"+ src={src}loopautoplaystyle={{ width: size, height: size }}diff --git a/packages/web/src/app/loading.tsx b/packages/web/src/app/loading.tsxindex ecae44f94..3000586b3 100644--- a/packages/web/src/app/loading.tsx+++ b/packages/web/src/app/loading.tsx@@ -1,4 +1,4 @@-import { OwlLoader } from "@/components/shared/owl-loader";+import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";export default function DashboardLoading() {return <OwlLoader />;diff --git a/packages/web/src/app/repos/[id]/c4/loading.tsx b/packages/web/src/app/repos/[id]/c4/loading.tsxindex 1db2391ef..cb1420a0f 100644--- a/packages/web/src/app/repos/[id]/c4/loading.tsx+++ b/packages/web/src/app/repos/[id]/c4/loading.tsx@@ -1,4 +1,4 @@-import { OwlLoader } from "@/components/shared/owl-loader";+import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";export default function Loading() {return <OwlLoader />;diff --git a/packages/web/src/app/repos/[id]/c4/page.tsx b/packages/web/src/app/repos/[id]/c4/page.tsxindex f6aa0d74f..2f0b28642 100644--- a/packages/web/src/app/repos/[id]/c4/page.tsx+++ b/packages/web/src/app/repos/[id]/c4/page.tsx@@ -50,7 +50,7 @@ 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 "@/components/shared/owl-loader";+import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";import { AlertTriangle } from "lucide-react";const MODE_VALUES = ["c4", "architecture"] as const;diff --git a/packages/web/src/app/repos/[id]/commits/loading.tsx b/packages/web/src/app/repos/[id]/commits/loading.tsxindex ba429ae31..d7ee5ce7f 100644--- a/packages/web/src/app/repos/[id]/commits/loading.tsx+++ b/packages/web/src/app/repos/[id]/commits/loading.tsx@@ -1,4 +1,4 @@-import { OwlLoader } from "@/components/shared/owl-loader";+import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";export default function CommitsLoading() {return <OwlLoader />;diff --git a/packages/web/src/app/repos/[id]/coverage/loading.tsx b/packages/web/src/app/repos/[id]/coverage/loading.tsxindex ab2171edb..ad16601dc 100644--- a/packages/web/src/app/repos/[id]/coverage/loading.tsx+++ b/packages/web/src/app/repos/[id]/coverage/loading.tsx@@ -1,4 +1,4 @@-import { OwlLoader } from "@/components/shared/owl-loader";+import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";export default function CoverageRedirectLoading() {return <OwlLoader />;diff --git a/packages/web/src/app/repos/[id]/dead-code/loading.tsx b/packages/web/src/app/repos/[id]/dead-code/loading.tsxindex d9589e644..e38e0ba07 100644--- a/packages/web/src/app/repos/[id]/dead-code/loading.tsx+++ b/packages/web/src/app/repos/[id]/dead-code/loading.tsx@@ -1,4 +1,4 @@-import { OwlLoader } from "@/components/shared/owl-loader";+import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";export default function DeadCodeLoading() {return <OwlLoader />;diff --git a/packages/web/src/app/repos/[id]/docs/coverage/loading.tsx b/packages/web/src/app/repos/[id]/docs/coverage/loading.tsxindex 72d500be7..9abf073af 100644--- a/packages/web/src/app/repos/[id]/docs/coverage/loading.tsx+++ b/packages/web/src/app/repos/[id]/docs/coverage/loading.tsx@@ -1,4 +1,4 @@-import { OwlLoader } from "@/components/shared/owl-loader";+import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";export default function CoverageLoading() {return <OwlLoader />;diff --git a/packages/web/src/app/repos/[id]/graph/loading.tsx b/packages/web/src/app/repos/[id]/graph/loading.tsxindex 4b33e6dd9..6fe318ef8 100644--- a/packages/web/src/app/repos/[id]/graph/loading.tsx+++ b/packages/web/src/app/repos/[id]/graph/loading.tsx@@ -1,4 +1,4 @@-import { OwlLoader } from "@/components/shared/owl-loader";+import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";export default function GraphLoading() {return <OwlLoader />;diff --git a/packages/web/src/app/repos/[id]/hotspots/loading.tsx b/packages/web/src/app/repos/[id]/hotspots/loading.tsxindex 7f770c390..331d4031a 100644--- a/packages/web/src/app/repos/[id]/hotspots/loading.tsx+++ b/packages/web/src/app/repos/[id]/hotspots/loading.tsx@@ -1,4 +1,4 @@-import { OwlLoader } from "@/components/shared/owl-loader";+import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";export default function HotspotsLoading() {return <OwlLoader />;diff --git a/packages/web/src/app/repos/[id]/loading.tsx b/packages/web/src/app/repos/[id]/loading.tsxindex 25d1f0d1f..ec07de63a 100644--- a/packages/web/src/app/repos/[id]/loading.tsx+++ b/packages/web/src/app/repos/[id]/loading.tsx@@ -1,4 +1,4 @@-import { OwlLoader } from "@/components/shared/owl-loader";+import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";export default function RepoLoading() {return <OwlLoader />;diff --git a/packages/web/src/app/repos/[id]/overview/loading.tsx b/packages/web/src/app/repos/[id]/overview/loading.tsxindex d0ecd795e..20f5cea11 100644--- a/packages/web/src/app/repos/[id]/overview/loading.tsx+++ b/packages/web/src/app/repos/[id]/overview/loading.tsx@@ -1,4 +1,4 @@-import { OwlLoader } from "@/components/shared/owl-loader";+import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";export default function OverviewLoading() {return <OwlLoader />;diff --git a/packages/web/src/app/repos/[id]/ownership/loading.tsx b/packages/web/src/app/repos/[id]/ownership/loading.tsxindex 9a6adc928..e3a3a6d7e 100644--- a/packages/web/src/app/repos/[id]/ownership/loading.tsx+++ b/packages/web/src/app/repos/[id]/ownership/loading.tsx@@ -1,4 +1,4 @@-import { OwlLoader } from "@/components/shared/owl-loader";+import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";export default function OwnershipLoading() {return <OwlLoader />;diff --git a/packages/web/src/app/repos/[id]/search/loading.tsx b/packages/web/src/app/repos/[id]/search/loading.tsxindex 1693c217f..806027c41 100644--- a/packages/web/src/app/repos/[id]/search/loading.tsx+++ b/packages/web/src/app/repos/[id]/search/loading.tsx@@ -1,4 +1,4 @@-import { OwlLoader } from "@/components/shared/owl-loader";+import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";export default function SearchLoading() {return <OwlLoader />;diff --git a/packages/web/src/app/repos/[id]/symbols/loading.tsx b/packages/web/src/app/repos/[id]/symbols/loading.tsxindex f1133ffc0..7b1772697 100644--- a/packages/web/src/app/repos/[id]/symbols/loading.tsx+++ b/packages/web/src/app/repos/[id]/symbols/loading.tsx@@ -1,4 +1,4 @@-import { OwlLoader } from "@/components/shared/owl-loader";+import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";export default function SymbolsLoading() {return <OwlLoader />;diff --git a/packages/web/src/app/repos/[id]/wiki/[...slug]/loading.tsx b/packages/web/src/app/repos/[id]/wiki/[...slug]/loading.tsxindex b814ce0be..a9865157c 100644--- a/packages/web/src/app/repos/[id]/wiki/[...slug]/loading.tsx+++ b/packages/web/src/app/repos/[id]/wiki/[...slug]/loading.tsx@@ -1,4 +1,4 @@-import { OwlLoader } from "@/components/shared/owl-loader";+import { OwlLoader } from "@repowise-dev/ui/shared/owl-loader";export default function WikiPageLoading() {return <OwlLoader />;diff --git a/tests/unit/cli/test_mascot.py b/tests/unit/cli/test_mascot.pyindex 55ce8fb15..bbb732b56 100644--- a/tests/unit/cli/test_mascot.py+++ b/tests/unit/cli/test_mascot.py@@ -138,11 +138,14 @@ def test_repo_name_with_markup_is_escaped() -> None:assert "evil[/bold]name" in console.export_text()-def test_full_banner_at_wide_width() -> None:+def test_banner_at_wide_width_stays_compact_with_long_tagline() -> None:+ # The banner art is always the compact variant; only the tagline grows+ # on wide terminals.console = Console(width=100, record=True, force_terminal=True)print_banner(console, repo_name="my-cool-repo")out = console.export_text()- assert ",_____," in out+ assert ",___," in out # compact owl used+ assert ",_____," not in out # full owl never renderedassert "codebase intelligence for developers and AI" in outassert "Repository: my-cool-repo" in outdiff --git a/tests/unit/server/services/test_c4_serialize.py b/tests/unit/server/services/test_c4_serialize.pynew file mode 100644index 000000000..dc36ad8c9--- /dev/null+++ b/tests/unit/server/services/test_c4_serialize.py@@ -0,0 +1,166 @@+"""Direct unit tests for the architecture-view serialization layer.++tests/unit/server/test_architecture_api.py pins the wire shape through the+endpoint; these exercise the dataclass → response-model adapters without+FastAPI — the contract non-HTTP consumers (artifact precomputation) rely on.+"""++from __future__ import annotations++from repowise.server.services.c4_builder.models import (+ ArchEdge,+ ArchitectureView,+ ArchLayer,+ ArchNode,+ ArchSubGroup,+ ArchTourStep,+ ExternalSystemView,+)+from repowise.server.services.c4_builder.serialize import architecture_view_response+++def _node(node_id: str = "file:src/main.py") -> ArchNode:+ return ArchNode(+ id=node_id,+ node_type="file",+ name="main.py",+ file_path="src/main.py",+ line_range=(1, 40),+ summary="entry point",+ complexity="low",+ tags=["entry"],+ language="python",+ pagerank=0.8,+ pagerank_percentile=0.99,+ betweenness=0.5,+ in_degree=0,+ out_degree=3,+ community_id=0,+ is_entry_point=True,+ is_test=False,+ is_hotspot=True,+ is_dead=False,+ has_doc=True,+ primary_owner="Alice",+ primary_owner_pct=0.7,+ bus_factor=2,+ )+++def test_architecture_view_response_round_trips_all_fields():+ view = ArchitectureView(+ project_name="demo",+ project_description="a demo",+ layers=[+ ArchLayer(+ id="layer:ui",+ name="UI",+ description="front end",+ node_ids=["file:src/main.py"],+ file_count=1,+ complexity_distribution={"low": 1},+ health_score=8.5,+ sub_groups=[+ ArchSubGroup(id="sg:forms", name="Forms", node_ids=["file:src/main.py"])+ ],+ display_order=1,+ )+ ],+ nodes=[_node()],+ edges=[+ ArchEdge(+ source="file:src/main.py",+ target="file:src/utils.py",+ edge_type="import",+ direction="out",+ weight=1.0,+ confidence=0.9,+ )+ ],+ tour=[+ ArchTourStep(+ order=1,+ title="Start here",+ description="the entry point",+ node_ids=["file:src/main.py"],+ target_path="src/main.py",+ layer_id="layer:ui",+ reason="entry",+ depth=0,+ kind="entry_point",+ page_type="module",+ )+ ],+ total_files=2,+ total_symbols=10,+ total_edges=1,+ languages=["python"],+ frameworks=["fastapi"],+ external_systems=[+ ExternalSystemView(+ id="ext:redis",+ name="redis",+ display_name="Redis",+ category="cache",+ ecosystem="pypi",+ version="5.0",+ )+ ],+ entry_points=["src/main.py"],+ entry_candidates=["src/cli.py"],+ )++ resp = architecture_view_response(view)++ assert resp.project_name == "demo"+ layer = resp.layers[0]+ assert (layer.id, layer.display_order, layer.health_score) == ("layer:ui", 1, 8.5)+ assert layer.sub_groups[0].name == "Forms"+ node = resp.nodes[0]+ assert node.line_range == [1, 40] # tuple becomes a JSON-friendly list+ assert node.primary_owner == "Alice"+ assert node.is_hotspot is True+ edge = resp.edges[0]+ assert (edge.source, edge.edge_type, edge.confidence) == (+ "file:src/main.py",+ "import",+ 0.9,+ )+ step = resp.tour[0]+ assert (step.target_path, step.layer_id, step.depth, step.kind, step.page_type) == (+ "src/main.py",+ "layer:ui",+ 0,+ "entry_point",+ "module",+ )+ ext = resp.external_systems[0]+ assert (ext.display_name, ext.category) == ("Redis", "cache")+ assert resp.entry_points == ["src/main.py"]+ assert resp.entry_candidates == ["src/cli.py"]+++def test_architecture_view_response_none_line_range():+ view = ArchitectureView(+ project_name="demo",+ project_description="",+ layers=[],+ nodes=[+ ArchNode(+ **{+ **_node().__dict__,+ "line_range": None,+ }+ )+ ],+ edges=[],+ tour=[],+ total_files=1,+ total_symbols=0,+ total_edges=0,+ languages=[],+ frameworks=[],+ external_systems=[],+ )++ assert architecture_view_response(view).nodes[0].line_range is Nonediff --git a/tests/unit/server/services/test_graph_views.py b/tests/unit/server/services/test_graph_views.pynew file mode 100644index 000000000..0c377b4e8--- /dev/null+++ b/tests/unit/server/services/test_graph_views.py@@ -0,0 +1,208 @@+"""Direct unit tests for the community-view service builders.++The HTTP endpoints are thin wrappers over these functions; the router tests+in tests/unit/server/test_graph.py pin the wire shapes, while these exercise+the builders without FastAPI — the contract non-HTTP consumers (artifact+precomputation) rely on.+"""++from __future__ import annotations++import json++import pytest++from repowise.core.persistence import (+ batch_upsert_graph_edges,+ batch_upsert_graph_nodes,+ upsert_repository,+)+from repowise.core.persistence import crud+from repowise.core.persistence.models import GraphEdge+from repowise.server.schemas import (+ ArchitectureGraphResponse,+ CommunitySliceResponse,+)+from repowise.server.services.graph_views import (+ build_architecture_graph,+ build_community_slice,+ edge_response,+)+++async def _seed_two_communities(session, tmp_path) -> str:+ """Two members in community 0, one in community 1, with a cross edge."""+ repo = await upsert_repository(session, name="demo", local_path=str(tmp_path))+ await batch_upsert_graph_nodes(+ session,+ repo.id,+ [+ {+ "node_id": "src/a.py",+ "node_type": "file",+ "language": "python",+ "symbol_count": 3,+ "pagerank": 0.8,+ "betweenness": 0.5,+ "community_id": 0,+ },+ {+ "node_id": "src/b.py",+ "node_type": "file",+ "language": "python",+ "symbol_count": 2,+ "pagerank": 0.4,+ "betweenness": 0.1,+ "community_id": 0,+ },+ {+ "node_id": "src/c.py",+ "node_type": "file",+ "language": "python",+ "symbol_count": 1,+ "pagerank": 0.2,+ "betweenness": 0.0,+ "community_id": 1,+ },+ ],+ )+ await batch_upsert_graph_edges(+ session,+ repo.id,+ [+ # Intra-community (0)+ {"source_node_id": "src/a.py", "target_node_id": "src/b.py"},+ # Cross-community (0 -> 1): pulls c.py in as a boundary stub+ {"source_node_id": "src/b.py", "target_node_id": "src/c.py"},+ ],+ )+ await session.flush()+ return repo.id+++async def test_build_architecture_graph_groups_and_edges(async_session, tmp_path):+ repo_id = await _seed_two_communities(async_session, tmp_path)++ view = await build_architecture_graph(async_session, repo_id, min_members=1)++ assert isinstance(view, ArchitectureGraphResponse)+ by_cid = {n.community_id: n for n in view.nodes}+ assert set(by_cid) == {0, 1}+ assert by_cid[0].member_count == 2+ assert by_cid[0].top_file == "src/a.py" # highest pagerank member+ assert by_cid[1].member_count == 1+ assert "python" in by_cid[0].languages+ # One underlying edge crosses the 0 -> 1 boundary+ assert [(e.source, e.target, e.edge_count) for e in view.edges] == [(0, 1, 1)]+ # Sorted by member count, biggest community first+ assert view.nodes[0].community_id == 0+++async def test_build_architecture_graph_min_members_filter(async_session, tmp_path):+ repo_id = await _seed_two_communities(async_session, tmp_path)++ view = await build_architecture_graph(async_session, repo_id, min_members=2)++ assert [n.community_id for n in view.nodes] == [0]+ # Edges into dropped communities are collapsed away+ assert view.edges == []+++async def test_build_architecture_graph_empty_repo(async_session, tmp_path):+ repo = await upsert_repository(async_session, name="empty", local_path=str(tmp_path))++ view = await build_architecture_graph(async_session, repo.id)++ assert view.nodes == []+ assert view.edges == []+++async def test_build_architecture_graph_aggregates_signals(async_session, tmp_path):+ repo_id = await _seed_two_communities(async_session, tmp_path)+ await crud.upsert_git_metadata(+ async_session,+ repository_id=repo_id,+ file_path="src/a.py",+ is_hotspot=True,+ churn_percentile=0.95,+ primary_owner_name="Alice",+ commit_count_30d=10,+ commit_count_90d=20,+ )+ await async_session.flush()++ view = await build_architecture_graph(async_session, repo_id, min_members=1)++ by_cid = {n.community_id: n for n in view.nodes}+ assert by_cid[0].hotspot_count == 1+ assert by_cid[1].hotspot_count == 0+++async def test_build_community_slice_members_and_boundary(async_session, tmp_path):+ repo_id = await _seed_two_communities(async_session, tmp_path)++ payload = await build_community_slice(async_session, repo_id, community_id=0)++ assert isinstance(payload, CommunitySliceResponse)+ assert payload.community_id == 0+ assert payload.member_count == 2+ assert payload.truncated is False+ by_id = {n.node_id: n for n in payload.nodes}+ assert set(by_id) == {"src/a.py", "src/b.py", "src/c.py"}+ assert by_id["src/a.py"].is_boundary is False+ assert by_id["src/b.py"].is_boundary is False+ assert by_id["src/c.py"].is_boundary is True # outside neighbor stub+ links = {(link.source, link.target) for link in payload.links}+ assert links == {("src/a.py", "src/b.py"), ("src/b.py", "src/c.py")}+++async def test_build_community_slice_member_limit_truncates(async_session, tmp_path):+ repo_id = await _seed_two_communities(async_session, tmp_path)++ payload = await build_community_slice(+ async_session, repo_id, community_id=0, member_limit=1+ )++ assert payload.truncated is True+ assert payload.member_count == 1+++async def test_build_community_slice_empty_community(async_session, tmp_path):+ repo_id = await _seed_two_communities(async_session, tmp_path)++ payload = await build_community_slice(async_session, repo_id, community_id=999)++ assert payload.nodes == []+ assert payload.links == []+ assert payload.member_count == 0+ assert payload.truncated is False+++def test_edge_response_parses_imported_names():+ e = GraphEdge(+ repository_id="r",+ source_node_id="a.py",+ target_node_id="b.py",+ imported_names_json=json.dumps(["helper"]),+ )+ resp = edge_response(e)+ assert resp.source == "a.py"+ assert resp.target == "b.py"+ assert resp.imported_names == ["helper"]+++def test_edge_response_tolerates_bad_json():+ e = GraphEdge(+ repository_id="r",+ source_node_id="a.py",+ target_node_id="b.py",+ imported_names_json="{not json",+ )+ assert edge_response(e).imported_names == []